### Development Environment Setup Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Example of setting environment variables for a local development setup and running a core command. ```bash export SUPERVISOR_ENDPOINT=http://192.168.1.2 export SUPERVISOR_API_TOKEN=your-token go run main.go core info ``` -------------------------------- ### App Management Examples Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Provides examples for installing, retrieving information about, streaming logs from, updating, and uninstalling Home Assistant apps. ```bash ha apps install core_ssh ``` ```bash ha apps info core_mosquitto ``` ```bash ha apps logs core_ssh --follow ``` ```bash ha apps update core_ssh ``` ```bash ha apps uninstall core_ssh ``` -------------------------------- ### Simple Progress Indicator Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Demonstrates a basic spinner setup with prefix, suffix, and final message, writing to stderr. Includes starting and stopping the spinner. ```go package main import ( "time" "os" "github.com/home-assistant/cli/spinner" ) func main() { s := spinner.New(spinner.CharSets[0], 125*time.Millisecond) s.Prefix = "Processing " s.Suffix = " Please wait" s.FinalMSG = "Done!\n" s.Writer = os.Stderr s.Start() time.Sleep(3 * time.Second) s.Stop() } ``` -------------------------------- ### Store Command Examples Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Illustrates how to interact with the Home Assistant app store, including listing available apps, installing from the store, and managing custom repositories. ```bash ha store apps ``` ```bash ha store apps install core_ssh ``` ```bash ha store repositories add https://github.com/example/repo ``` -------------------------------- ### YAML Configuration File Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md This is an example of the `$HOME/.homeassistant.yaml` configuration file. All keys correspond to flag names with underscores replacing hyphens. ```yaml endpoint: supervisor api-token: your-api-token-here log-level: warn raw-json: false no-progress: false ``` -------------------------------- ### Jobs Command Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Example of how to retrieve information about background jobs. ```bash ha jobs info ``` -------------------------------- ### Supervisor Command Examples Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Shows how to manage the Home Assistant Supervisor, including getting information, streaming logs, and initiating updates or repairs. ```bash ha supervisor info ``` ```bash ha supervisor logs --lines 50 ``` ```bash ha supervisor update ``` ```bash ha supervisor repair ``` -------------------------------- ### App CLI Command: Management Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Examples of using CLI commands to manage Home Assistant applications (add-ons), including installing, updating, and viewing logs for specific app slugs. Use these for managing installed apps. ```bash # Apps ha apps install [slug] ha apps update [slug] ha apps logs [slug] ``` -------------------------------- ### Making a Simple GET API Call Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Illustrates how to perform a basic GET request to the Home Assistant API using the client library. Ensure the client library is imported. ```go import "github.com/home-assistant/cli/client" // Simple GET request resp, err := client.GenericJSONGet("core", "info") if err != nil { client.PrintError(err) return } // Display formatted response client.ShowJSONResponse(resp) ``` -------------------------------- ### Environment Variable Configuration Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md This example demonstrates setting environment variables to configure the CLI. These variables override settings from the configuration file. ```bash export SUPERVISOR_ENDPOINT=http://192.168.1.100:8123 export SUPERVISOR_API_TOKEN=my-secret-token export SUPERVISOR_LOG_LEVEL=debug ha core info ``` -------------------------------- ### Start Spinner Animation Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Shows how to start the spinner animation. The Start method is idempotent and safe to call multiple times. Ensure to call Stop() when the operation is complete. ```go s := spinner.New(spinner.CharSets[0], 125*time.Millisecond) s.Prefix = "Processing " s.Suffix = " Please wait" s.Writer = os.Stderr s.Start() // ... perform long-running operation ... s.Stop() ``` -------------------------------- ### Start Method Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Starts the spinner animation. Subsequent calls are ignored if the spinner is already running. ```APIDOC ## Start ### Description Starts the spinner animation. Can be called multiple times; subsequent calls are ignored if already running. ### Behavior - Sets active state to true - Spawns a goroutine that cycles through character set - Clears previous output before drawing each frame - Respects the Delay duration between frames - Reads from stopChan to detect when to stop ### Example ```go s := spinner.New(spinner.CharSets[0], 125*time.Millisecond) s.Prefix = "Processing " s.Suffix = " Please wait" s.Writer = os.Stderr s.Start() // ... perform long-running operation ... s.Stop() ``` ``` -------------------------------- ### Example Construction of User Struct Source: https://github.com/home-assistant/cli/blob/master/_autodocs/types.md Demonstrates how to create a new User struct instance with specific field values. ```go user := User{ Username: "alice", Name: "Alice Smith", Owner: true, Active: true, LocalOnly: false, } ``` -------------------------------- ### Host System Management Examples Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Demonstrates commands for managing the host system, such as retrieving information, checking disk usage, and performing reboots or shutdowns. ```bash ha host info ``` ```bash ha host disks ``` ```bash ha host reboot --force ``` ```bash ha host shutdown ``` -------------------------------- ### Get Information with GenericJSONGet Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Example of using the GenericJSONGet function to retrieve information from a specified section and command. This is a common pattern for fetching data. ```go // Get information client.GenericJSONGet("section", "command") ``` -------------------------------- ### User Interaction Prompts Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Examples of using the client to prompt the user for confirmation, integer input, or password. ```go // Confirmation confirmed, err := client.AskForConfirmation("Delete backup?", 3) if err == nil && confirmed { // Proceed with deletion } // Selection menu idx, err := client.ReadInteger("Select item", 3, 1, 10) // Password input password, err := client.ReadPassword(true) // true = confirm ``` -------------------------------- ### Build Home Assistant CLI Binary Source: https://github.com/home-assistant/cli/blob/master/README.md Example command for building the Home Assistant CLI binary using Go modules. ```bash CGO_ENABLED=0 go build -ldflags="-s -w" -o "ha" ``` -------------------------------- ### Configure CLI via Config File Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Example of configuring the CLI using a YAML configuration file (`~/.homeassistant.yaml`). ```yaml endpoint: 192.168.1.100 api-token: TOKEN ``` -------------------------------- ### Core Command Examples Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Demonstrates common operations for managing Home Assistant Core, such as checking info, restarting, updating, and streaming logs. ```bash ha core info --raw-json ``` ```bash ha core restart ``` ```bash ha core update --version 2024.5.0 ``` ```bash ha core logs --follow ``` -------------------------------- ### Get Host Boot Logs Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve boot logs for the Home Assistant host system. ```bash ha host logs boots ``` -------------------------------- ### Client Package Example Usage Source: https://github.com/home-assistant/cli/blob/master/_autodocs/module-overview.md Demonstrates how to make an API call using the client package and handle the response. It also shows how to use the user interaction functions for confirmation. ```go import "github.com/home-assistant/cli/client" // Make API call resp, err := client.GenericJSONGet("core", "info") if err != nil { client.PrintError(err) return } // Display response client.ShowJSONResponse(resp) // User interaction confirmed, _ := client.AskForConfirmation("Continue?", 3) ``` -------------------------------- ### Progress Spinner Usage Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Demonstrates how to start and stop the global progress spinner for indicating ongoing operations. ```go import "github.com/home-assistant/cli/cmd" cmd.ProgressSpinner.Start() // ... do work ... cmd.ProgressSpinner.Stop() ``` -------------------------------- ### Request-Response Pattern Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Demonstrates the standard pattern for making API calls, handling responses, and displaying errors. ```go resp, err := client.GenericJSONGet("section", "command") resp, err = client.GenericJSONErrorHandling(resp, err) if err != nil { client.PrintError(err) ExitWithError = true } else { ExitWithError = !client.ShowJSONResponse(resp) } ``` -------------------------------- ### Make a Generic JSON GET Request Source: https://github.com/home-assistant/cli/blob/master/_autodocs/module-overview.md Illustrates how to use the client package to make a generic JSON GET request to retrieve core information. It includes basic error handling and displaying the JSON response. This pattern is fundamental for interacting with the Home Assistant API. ```go package main import ( "github.com/home-assistant/cli/client" ) func main() { // Get core information resp, err := client.GenericJSONGet("core", "info") if err != nil { client.PrintError(err) return } client.ShowJSONResponse(resp) } ``` -------------------------------- ### Go Function Signature Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md This snippet shows an example of a Go function signature, including parameter names and types. It is used to illustrate how functions are defined within the project. ```go func GenericJSONPost(section, command string, body map[string]any) (*resty.Response, error) ``` -------------------------------- ### Spinner Initialization and Usage Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Demonstrates how to initialize a Spinner with a character set and delay, configure its prefix, suffix, and final message, and then start and stop the animation. ```go s := spinner.New(spinner.CharSets[0], 125*time.Millisecond) s.Prefix = "Loading " s.Suffix = " Please wait..." s.FinalMSG = "Done!\n" s.Writer = os.Stderr s.Start() // ... do work ... s.Stop() ``` -------------------------------- ### Example Configuration File Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md A sample YAML configuration file for the Home Assistant CLI. This file can specify the supervisor endpoint, API token, logging level, and output formatting. ```yaml # Home Assistant Supervisor endpoint endpoint: supervisor # API token for authentication api-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... # Logging verbosity log-level: warn # Output formatting raw-json: false # Progress display no-progress: false ``` -------------------------------- ### Request-Response Pattern Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Demonstrates the typical pattern for making API calls using the client library, including error handling and displaying responses. Ensure the client library is properly initialized. ```go resp, err := client.GenericJSONGet("section", "command") resp, err = client.GenericJSONErrorHandling(resp, err) if err != nil { client.PrintError(err) } else { client.ShowJSONResponse(resp) } ``` -------------------------------- ### Resolution Center Commands Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Examples of using the resolution center to check system status and retrieve information. ```bash ha resolution info ha resolution healthcheck ha resolution check ``` -------------------------------- ### Use Progress Spinner in a Command Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of how to use the global `ProgressSpinner` within a Cobra command's `Run` function to indicate long-running operations. The spinner should be started before the operation and stopped afterwards. ```go var myCmd = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { ProgressSpinner.Start() // ... perform long-running operation ... ProgressSpinner.Stop() }, } ``` -------------------------------- ### Create and Use a Spinner Source: https://github.com/home-assistant/cli/blob/master/_autodocs/module-overview.md Demonstrates how to create a new spinner instance with custom options, set its writer, prefix, and suffix, and then start and stop the animation. This is useful for providing visual feedback during long-running terminal operations. ```go import ( "time" "github.com/home-assistant/cli/spinner" ) s := spinner.New(spinner.CharSets[0], 125*time.Millisecond, spinner.WithFinalMSG("Done!\n")) s.Writer = os.Stderr s.Prefix = "Processing " s.Suffix = " Please wait" s.Start() // ... do work ... s.Stop() ``` -------------------------------- ### CLI Command Structure Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Illustrates the general syntax for using Home Assistant CLI commands. This structure applies to most commands, with variations in subcommands and arguments. ```bash ha [arguments] [--flags] ``` -------------------------------- ### Configure CLI via Flags Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Example of configuring the Home Assistant CLI using command-line flags for endpoint and API token. ```bash ha --endpoint 192.168.1.100 --api-token TOKEN core info ``` -------------------------------- ### Example Debug Error Output Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md This snippet shows an example of the detailed debug output that includes timing, client request/response information, and status codes. ```text [...time...] DEBUG client: [GenerateURI] base=supervisor section=core command=info [...time...] DEBUG client: Request body body=map[] [...time...] DEBUG client: Response statuscode=200 status=200 OK ... ``` -------------------------------- ### Get Component Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve general information about a Home Assistant component. ```bash ha info ``` -------------------------------- ### Typical Usage of User Struct Source: https://github.com/home-assistant/cli/blob/master/_autodocs/types.md Shows how to retrieve a list of users, iterate through them, and display their properties. Also includes an example of interactively selecting a user. ```go // Get list of users users, err := getUsers() if err != nil { client.PrintError(err) return } // List users for i, user := range users { fmt.Printf("%d: %s (%s)\n", i+1, user.Username, user.Name) fmt.Printf(" Owner: %t, Active: %t, Local Only: %t\n", user.Owner, user.Active, user.LocalOnly) } // Interactively select a user idx, err := client.ReadInteger("Select a user", 3, 1, len(users)) if err == nil { selectedUser := users[idx-1] } ``` -------------------------------- ### Home Assistant CLI Usage Examples Source: https://github.com/home-assistant/cli/blob/master/README.md Basic usage patterns for the Home Assistant CLI, including general help and subcommand invocation. ```text ha help ``` ```text ha [] ``` ```text ha core info --raw-json ``` -------------------------------- ### Manage Audio Profiles Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Get or set the audio profile. Audio device management varies by hardware. ```bash ha audio profile ``` -------------------------------- ### Update All App Components Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Update all installed Home Assistant applications, specifying them by slug. ```bash ha apps update core_ssh ha apps update core_mosquitto ``` -------------------------------- ### Get General System Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Displays general system information and overview. Provides status and version details. ```bash ha info ``` -------------------------------- ### Control Component State Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Start, stop, or restart a Home Assistant component. ```bash ha start ha stop ha restart ``` -------------------------------- ### Get Docker Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve information about the Docker backend configuration. ```bash ha docker info ``` -------------------------------- ### Get General Hardware Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves general hardware information about the system. Use to check hardware capabilities. ```bash ha hardware info ``` -------------------------------- ### Configure CLI via Environment Variables Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Example of setting the supervisor endpoint and API token using environment variables. ```bash export SUPERVISOR_ENDPOINT=192.168.1.100 export SUPERVISOR_TOKEN=TOKEN ha core info ``` -------------------------------- ### Get Component Statistics Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve statistical data for a Home Assistant component. ```bash ha stats ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Illustrates the order of precedence for configuration settings: CLI flags override environment variables, which override configuration file settings. ```text endpoint: cli-endpoint # CLI flag wins api-token: config-file-token # From config file log-level: debug # CLI flag wins ``` -------------------------------- ### Set API Token Environment Variables Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Examples of setting the API token using environment variables, demonstrating the flexibility provided by Viper's binding. ```bash export SUPERVISOR_TOKEN=mytoken123 # OR export SUPERVISOR_API_TOKEN=mytoken123 ``` -------------------------------- ### Core CLI Command: Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Examples of using core CLI commands to retrieve information about Home Assistant components like the core and supervisor. Use these to check status and logs. ```bash # Information ha core info ha supervisor logs ha info ha hardware info ``` -------------------------------- ### Network CLI Command: Configuration Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Examples of using CLI commands to view network information and update network configurations, such as interface settings. Use these for managing network interfaces. ```bash # Configuration ha network info ha network update [interface] ``` -------------------------------- ### Get Network Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve current network configuration details. Network changes take effect immediately. ```bash ha network info ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Sets environment variables for a local development setup, enabling full debug logging and specifying the supervisor endpoint and token. ```bash # Local development with full logging export SUPERVISOR_ENDPOINT=http://192.168.1.100:8123 export SUPERVISOR_TOKEN=my-dev-token export SUPERVISOR_LOG_LEVEL=debug ha core info ``` -------------------------------- ### Get Audio Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve current audio device information. Volume ranges typically from 0 to 100. ```bash ha audio info ``` -------------------------------- ### Authentication CLI Command: Reset Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Example of using the CLI command to reset authentication credentials. This command is used for security-related resets. ```bash ha auth reset ``` -------------------------------- ### Backup CLI Command: Management Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Examples of using CLI commands to manage backups, including creating new backups, restoring from existing ones, and removing old backups. Specify the backup slug when needed. ```bash # Backups ha backups new ha backups restore [slug] ha backups remove [slug] ``` -------------------------------- ### Get Mount Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves information about a specific mount point. Replace 'my-mount' with the mount's name. ```bash ha mounts info ``` -------------------------------- ### Get Raw JSON Component Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve component information in raw JSON format for programmatic parsing. ```bash ha info --raw-json ``` -------------------------------- ### Get Audio Hardware Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves specific information about the system's audio hardware. Useful for troubleshooting audio issues. ```bash ha hardware audio ``` -------------------------------- ### Example: Invalid URL Error Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Demonstrates an invalid URL error when the endpoint is malformed. Ensure the endpoint URL is correctly configured. ```bash $ ha --endpoint invalid::url core info Error: invalid URL ``` -------------------------------- ### Get OS Information and Update Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Use these commands to retrieve operating system information or initiate an update. OS updates use an extended timeout of 1 hour. ```bash ha os info ha os boot-slot ha os update ha os datadisk list ``` -------------------------------- ### Get Base Request Object Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Use GetRequest to retrieve a base Resty request object configured with API token authentication and a default timeout. This provides a starting point for various API interactions. ```go func GetRequest() *resty.Request ``` ```go request := client.GetRequest() resp, err := request.Get(url) ``` -------------------------------- ### Get CLI Container Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves information about the Home Assistant CLI container. Use to check its status and configuration. ```bash ha cli info ``` -------------------------------- ### Standard CLI Error Handling Pattern Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md This Go code snippet demonstrates the typical error handling flow in the Home Assistant CLI. It shows how to make a generic JSON GET request, check for errors, print them, and manage the exit status based on the response. ```go resp, err := client.GenericJSONGet("section", "command") if err != nil { client.PrintError(err) ExitWithError = true } else { ExitWithError = !client.ShowJSONResponse(resp) } ``` -------------------------------- ### Get System Information as JSON Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves general system information in JSON format and filters the data field using jq. Useful for scripting. ```bash ha info --raw-json | jq '.data' ``` -------------------------------- ### Example: Invalid Endpoint for Command Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Illustrates an error when an invalid IP address is used as the endpoint. The fix requires using a valid IP address. ```bash $ ha --endpoint 999.999.999.999 core info Error: net::ERR_NAME_NOT_RESOLVED ``` ```bash ha --endpoint 192.168.1.100 core info ``` -------------------------------- ### Send Data with GenericJSONPost Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Example of using the GenericJSONPost function to send data to a specified section and command. This function is used for operations that modify data. ```go // Send data client.GenericJSONPost("section", "command", map[string]any{...}) ``` -------------------------------- ### Restart Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Stops the current spinner animation and starts a new one. This is equivalent to calling Stop() followed by Start(). ```APIDOC ## Restart ### Description Stops the current spinner animation and starts a new one. This is equivalent to calling Stop() followed by Start(). ### Method func (s *Spinner) Restart() ### Example ```go s.Restart() // Restarts the animation with current configuration ``` ``` -------------------------------- ### Restart Spinner Animation Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Stops the current animation and starts a new one. This is equivalent to calling Stop() then Start(). ```go func (s *Spinner) Restart() ``` ```go s.Restart() // Restarts the animation with current configuration ``` -------------------------------- ### Core CLI Command: Control Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Examples of using core CLI commands to control Home Assistant services, such as restarting, updating, or rebooting the host system. Use these for managing the HA instance. ```bash # Control ha core restart ha core update ha host reboot ``` -------------------------------- ### Example: Missing or Invalid API Token Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Shows the error message when the API token is missing or invalid. The fix involves providing a valid token via the command line or environment variable. ```bash $ ha core info Error: unauthorized: missing or invalid API token ``` ```bash ha --api-token eyJ... core info # OR export SUPERVISOR_TOKEN=eyJ... ha core info ``` -------------------------------- ### User Interaction: Read Password Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Example of securely reading a password from the user. The 'repeat' parameter likely indicates if the password needs to be entered twice for confirmation. ```go client.ReadPassword(repeat) ``` -------------------------------- ### Execute Generic JSON GET Request with Custom Timeout Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Executes a GET request to the Supervisor API with a specified custom timeout duration. ```go resp, err := client.GenericJSONGetTimeout("backups", "info", client.BackupTimeout) ``` -------------------------------- ### Set Config File Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--config` persistent flag for the root Cobra command. This flag specifies the path to the optional configuration file. ```go rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "Optional config file (default is $HOME/.homeassistant.yaml)") ``` -------------------------------- ### Handle Long Operations with Custom Timeout Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Example of setting a manual timeout for a client operation in Go. This is useful for custom code dealing with potentially long-running tasks. ```go resp, err := client.GenericJSONGetTimeout("section", "command", 10*time.Minute) if err != nil { client.PrintError(err) } ``` -------------------------------- ### Execute Generic JSON GET Request Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Executes a GET request to the Supervisor API using the DefaultTimeout. Handles standard error responses internally. ```go resp, err := client.GenericJSONGet("core", "info") if err != nil { client.PrintError(err) return } if !client.ShowJSONResponse(resp) { // Handle display error } ``` -------------------------------- ### Create a Full Backup Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Create a full backup of the Home Assistant system with a specified name. ```bash ha backups new --name "before-update" ``` -------------------------------- ### Create Basic Configuration File Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md A bash script to create a basic Home Assistant CLI configuration file in the default location and set appropriate file permissions for security. ```bash # Create basic config file mkdir -p ~/.homeassistant cat > ~/.homeassistant/.homeassistant.yaml << EOF endpoint: supervisor api-token: your-token-here log-level: warn raw-json: false no-progress: false EOF chmod 600 ~/.homeassistant/.homeassistant.yaml ``` -------------------------------- ### Example Error: Unexpected Non-JSON Response (Status 200) Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md This is an example of an error message returned when a request expecting JSON receives a non-JSON response, even with an HTTP 200 OK status. ```text Error: unexpected non-JSON response (status: 200) ``` -------------------------------- ### GenericJSONGet Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Executes a GET request to the Supervisor API with a default timeout. It takes an API section and command path as parameters and returns the HTTP response and any error encountered. It uses internal error handling and is suitable for general-purpose GET requests. ```APIDOC ## GenericJSONGet ### Description Executes a GET request to the Supervisor API with a default timeout. It takes an API section and command path as parameters and returns the HTTP response and any error encountered. It uses internal error handling and is suitable for general-purpose GET requests. ### Method GET ### Endpoint /{section}/{command} ### Parameters #### Path Parameters - **section** (string) - Required - API section path (e.g., "core", "backups", "supervisor") - **command** (string) - Required - API command path (e.g., "info", "stats") ### Request Example ```go resp, err := client.GenericJSONGet("core", "info") if err != nil { client.PrintError(err) return } if !client.ShowJSONResponse(resp) { // Handle display error } ``` ### Response #### Success Response (200) - **response** (*resty.Response) - The HTTP response from the Supervisor. - **error** (error) - Any error that occurred during the request. #### Response Example (Response body depends on the specific API endpoint called) ``` -------------------------------- ### Performing a Custom API Request Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Illustrates how to construct and execute a custom API request using the client library, including setting path parameters. ```go request := client.GetJSONRequest() request.SetPathParams(map[string]string{"id": "123"}) resp, err := request.Get(url) resp, err = client.GenericJSONErrorHandling(resp, err) ``` -------------------------------- ### Create Full Backup with Progress and Error Handling Source: https://github.com/home-assistant/cli/blob/master/_autodocs/module-overview.md Initiates a full backup with compression and displays progress. Includes robust error handling for the API request. ```go func backupWithProgress(name string) error { options := map[string]any{ "name": name, "compressed": true, } ProgressSpinner.Start() resp, err := client.GenericJSONPostTimeout( "backups", "new/full", options, client.BackupTimeout, ) ProgressSpinner.Stop() resp, err = client.GenericJSONErrorHandling(resp, err) if err != nil { return err } return nil } ``` -------------------------------- ### View Component Options Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Display the current configuration options for a component. ```bash ha options ``` -------------------------------- ### Get Backup Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves information about a specific backup. Replace 'backup-slug' with the actual backup identifier. ```bash ha backups info ``` -------------------------------- ### Testing and Formatting Commands Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Commands for running tests and formatting the Go code according to standard practices. ```bash # Test go test ./... # Format gofmt -s ``` -------------------------------- ### Get DNS Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves current DNS information. Use this to check the status of the DNS service. ```bash ha dns info ``` -------------------------------- ### Build Home Assistant CLI Source: https://github.com/home-assistant/cli/blob/master/CLAUDE.md Builds the Home Assistant CLI executable. Use this command to compile the Go project into a standalone binary. ```bash CGO_ENABLED=0 go build -ldflags="-s -w" -o "ha" ``` -------------------------------- ### Check Component Configuration Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Verify the configuration of a Home Assistant component. ```bash ha check ``` -------------------------------- ### Set up Development Environment for Home Assistant CLI Source: https://github.com/home-assistant/cli/blob/master/README.md Configure environment variables for the Home Assistant CLI to interact with a remote Supervisor instance during development. ```shell export SUPERVISOR_ENDPOINT=http://192.168.1.2 export SUPERVISOR_API_TOKEN=replace_this_with_remote_api_token go run main.go info ``` -------------------------------- ### Build Command Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Command to build the Home Assistant CLI executable with optimizations. ```bash # Build CGO_ENABLED=0 go build -ldflags="-s -w" -o "ha" ``` -------------------------------- ### Get Security Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieves general security information about the system. Use to check the overall security status. ```bash ha security info ``` -------------------------------- ### Get Observer Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve information about the network observer service. The observer monitors network traffic and devices. ```bash ha observer info ``` -------------------------------- ### Get Multicast Information Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Retrieve information about the Multicast DNS (mDNS) service. mDNS enables hostname discovery. ```bash ha multicast info ``` -------------------------------- ### Construct Full API URL Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Use URLHelper to construct complete API URLs by combining section and command paths. It automatically handles scheme detection and path normalization based on Viper configuration. ```go func URLHelper(section, command string) (string, error) ``` ```go url, err := client.URLHelper("backups", "new/full") // With endpoint="supervisor": "http://supervisor/backups/new/full" // With endpoint="http://192.168.1.100:8123": "http://192.168.1.100:8123/backups/new/full" ``` -------------------------------- ### Invalid Value Validation Message Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Example of a validation message shown to the user when an integer input is outside the allowed range. ```text Invalid value. Must be between 1 and 10. ``` -------------------------------- ### YAML Configuration File Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Illustrates the structure of the optional YAML configuration file for the Home Assistant CLI. ```yaml endpoint: supervisor api-token: your-token-here log-level: warn raw-json: false no-progress: false ``` -------------------------------- ### Configure Component Options Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Modify component options using flags. For example, `ha update --flag value`. ```bash ha update --flag value ``` -------------------------------- ### Docker Usage Configuration Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Shows how to run the Home Assistant CLI within a Docker container, passing configuration via environment variables. ```bash docker run -e SUPERVISOR_ENDPOINT=supervisor \ -e SUPERVISOR_TOKEN=my-token \ ha-cli core info ``` -------------------------------- ### Specify Custom Configuration File Location Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Demonstrates how to use the `--config` flag to specify a custom location for the Home Assistant CLI configuration file. ```bash ha --config /etc/homeassistant/cli.yaml core info ha --config ~/my-config.yaml supervisor logs ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Shows how to set environment variables to configure the Home Assistant CLI, mirroring the global flags. ```bash export SUPERVISOR_ENDPOINT=supervisor export SUPERVISOR_TOKEN=my-token export SUPERVISOR_LOG_LEVEL=debug export SUPERVISOR_RAW_JSON=true export SUPERVISOR_NO_PROGRESS=true ``` -------------------------------- ### Formatted API Response Error Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md This is how the API response error, shown in the previous JSON example, is typically displayed to the user in a simplified format. ```text Error: Add-on is already running ``` -------------------------------- ### Follow Component Logs Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Stream logs from a component in real-time. ```bash ha logs --follow ``` -------------------------------- ### Basic Error Handling in Go Client Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Demonstrates how to handle generic JSON POST requests and errors using the client. Prints errors to stderr and signals non-zero exit on failure. ```go resp, err := client.GenericJSONPost("backups", "new/full", options) resp, err = client.GenericJSONErrorHandling(resp, err) if err != nil { client.PrintError(err) // Prints to stderr with formatting ExitWithError = true // Signal non-zero exit return } if !client.ShowJSONResponse(resp) { ExitWithError = true // JSON display failed } ``` -------------------------------- ### Making a POST API Call with Data Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Demonstrates how to send data in the body of a POST request to the Home Assistant API. The `options` map should contain the data payload. ```go options := map[string]any{ "username": "john", "password": "secret", } resp, err := client.GenericJSONPost("auth", "reset", options) if err != nil { client.PrintError(err) return } client.ShowJSONResponse(resp) ``` -------------------------------- ### New Spinner Function Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/spinner.md Demonstrates creating a new Spinner instance with a character set and delay, and optionally configuring it with custom options like a final message or hidden cursor. ```go import "time" import "github.com/home-assistant/cli/spinner" // Simple spinner with default settings s := spinner.New(spinner.CharSets[0], 125*time.Millisecond) s.Writer = os.Stderr // Spinner with custom final message s := spinner.New(spinner.CharSets[1], 100*time.Millisecond, spinner.WithFinalMSG("Processing complete!\n")) // Spinner with hidden cursor s := spinner.New(spinner.CharSets[0], 125*time.Millisecond, spinner.WithHiddenCursor(true)) ``` -------------------------------- ### Create Backup for Specific Apps Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Creates a backup that includes only specified applications. Useful for targeted backups. ```bash ha backups new --app core_ssh --app core_mosquitto ``` -------------------------------- ### Create New Backup with Name Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Creates a new backup with a custom name. The name includes the current date for easy identification. ```bash ha backups new --name "backup-$(date +%Y%m%d)" ``` -------------------------------- ### Rebuild Component Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Rebuild a Home Assistant component. ```bash ha rebuild ``` -------------------------------- ### User Interaction: Ask for Confirmation Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Demonstrates how to prompt the user for confirmation before proceeding with an action. The 'tries' parameter limits the number of attempts. ```go // User interaction client.AskForConfirmation("prompt", tries) ``` -------------------------------- ### Display Results with ShowJSONResponse Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Example of using ShowJSONResponse to display the results of an API call in a user-friendly JSON format. This is typically called after successful error handling. ```go // Display results client.ShowJSONResponse(resp) ``` -------------------------------- ### Command Package Main Execution Source: https://github.com/home-assistant/cli/blob/master/_autodocs/module-overview.md Shows the main function for the command package, including deferred error handling and the execution of CLI commands. ```go import "github.com/home-assistant/cli/cmd" func main() { // Configure exit handler defer func() { if cmd.ExitWithError { os.Exit(1) } }() // Execute CLI cmd.Execute() } ``` -------------------------------- ### Home Assistant CLI Global Options Source: https://github.com/home-assistant/cli/blob/master/README.md Lists available global options for the Home Assistant CLI, which can also be set as environment variables. ```text --api-token string Home Assistant Supervisor API token --config string Optional config file (default is $HOME/.homeassistant.yaml) --endpoint string Endpoint for Home Assistant Supervisor (default is 'supervisor') -h, --help help for ha --log-level string Log level (defaults to Warn) --no-progress Disable the progress spinner --raw-json Output raw JSON from the API ``` -------------------------------- ### Specify Configuration File Path Source: https://github.com/home-assistant/cli/blob/master/_autodocs/configuration.md Use the --config flag to specify the path to your YAML configuration file. If not provided, the CLI defaults to searching for $HOME/.homeassistant.yaml. ```bash ha --config /etc/homeassistant/cli.yaml core info ha --config ~/my-ha-config.yaml supervisor info ``` -------------------------------- ### GenericJSONGetTimeout Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Executes a GET request to the Supervisor API with a custom timeout duration. This function is useful when specific operations require a timeout longer or shorter than the default. ```APIDOC ## GenericJSONGetTimeout ### Description Executes a GET request to the Supervisor API with a custom timeout duration. This function is useful when specific operations require a timeout longer or shorter than the default. ### Method GET ### Endpoint /{section}/{command} ### Parameters #### Path Parameters - **section** (string) - Required - API section path - **command** (string) - Required - API command path #### Query Parameters - **timeout** (time.Duration) - Required - Custom timeout for this request ### Request Example ```go resp, err := client.GenericJSONGetTimeout("backups", "info", client.BackupTimeout) ``` ### Response #### Success Response (200) - **response** (*resty.Response) - The HTTP response from the Supervisor. - **error** (error) - Any error that occurred during the request. #### Response Example (Response body depends on the specific API endpoint called) ``` -------------------------------- ### Progress Indication with Spinner Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Shows how to use the global `ProgressSpinner` for long-running operations in the CLI. ```go cmd.ProgressSpinner.Start() // ... perform operation ... cmd.ProgressSpinner.Stop() ``` -------------------------------- ### Set No Progress Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--no-progress` persistent flag for the root Cobra command. This flag disables the progress spinner, which is useful in non-interactive environments. ```go rootCmd.PersistentFlags().BoolVar(&noProgress, "no-progress", false, "Disable the progress spinner") ``` -------------------------------- ### User Interaction: Read Integer Source: https://github.com/home-assistant/cli/blob/master/_autodocs/INDEX.md Shows how to read an integer input from the user with specified prompts, attempt limits, and range constraints (min/max). ```go client.ReadInteger("prompt", tries, min, max) ``` -------------------------------- ### Restore From Backup Source: https://github.com/home-assistant/cli/blob/master/_autodocs/command-structure.md Restores the system from a specified backup. Replace 'backup-slug' with the backup's identifier. ```bash ha backups restore backup-slug ``` -------------------------------- ### Run Home Assistant CLI Tests Source: https://github.com/home-assistant/cli/blob/master/README.md Command to execute the test suite for the Home Assistant CLI project. ```bash go test ./... ``` -------------------------------- ### Run Tests for Home Assistant CLI Source: https://github.com/home-assistant/cli/blob/master/CLAUDE.md Executes all unit tests for the Home Assistant CLI project. Ensure all tests pass before contributing changes. ```bash go test ./... ``` -------------------------------- ### Set Log Level Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--log-level` persistent flag for the root Cobra command. This flag controls the verbosity of the CLI's logging output. ```go rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "", "Log level (defaults to Warn)") ``` -------------------------------- ### Set Endpoint Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--endpoint` persistent flag for the root Cobra command. This flag defines the target endpoint for the Home Assistant Supervisor API. ```go rootCmd.PersistentFlags().StringVar(&endPoint, "endpoint", "", "Endpoint for Home Assistant Supervisor (default is 'supervisor')") ``` -------------------------------- ### Handle CLI Exit Status Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Demonstrates how to check the global `ExitWithError` flag after `cmd.Execute()` to determine if the CLI encountered an error and should exit with a non-zero status code. ```go func main() { defer func() { if cmd.ExitWithError { os.Exit(1) } }() cmd.Execute() } ``` -------------------------------- ### Set API Token Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--api-token` persistent flag for the root Cobra command. This flag is used for authenticating with the Home Assistant Supervisor API. ```go rootCmd.PersistentFlags().StringVar(&apiToken, "api-token", "", "Home Assistant Supervisor API token") ``` -------------------------------- ### Get Base Request with Custom Timeout Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Use GetRequestTimeout to create a base Resty request object with a custom timeout. This allows for fine-grained control over request execution times. ```go func GetRequestTimeout(timeout time.Duration) *resty.Request ``` -------------------------------- ### Making a POST Request with Extended Timeout Source: https://github.com/home-assistant/cli/blob/master/_autodocs/README.md Shows how to make a POST request with a custom, extended timeout, useful for long-running operations like creating backups. ```go // Long operations use extended timeouts resp, err := client.GenericJSONPostTimeout( "backups", "new/full", options, client.BackupTimeout, // 3 hours ) ``` -------------------------------- ### Example: Limited Access Error Source: https://github.com/home-assistant/cli/blob/master/_autodocs/errors.md Shows the error when attempting to run a restricted command like 'ha auth reset' from a remote client. This command is only available on the HA OS terminal. ```bash $ ha auth reset --username john --password newpass Error: For security reasons, this command works only from the operating system terminal. ``` -------------------------------- ### Set Raw JSON Flag Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/cmd.md Example of setting the `--raw-json` persistent flag for the root Cobra command. When enabled, API responses are output as raw JSON without formatting. ```go rootCmd.PersistentFlags().BoolVar(&rawJSON, "raw-json", false, "Output raw JSON from the API") ``` -------------------------------- ### Get JSON Request Object Source: https://github.com/home-assistant/cli/blob/master/_autodocs/api-reference/client.md Use GetJSONRequest to obtain a Resty request object pre-configured for JSON API calls. It includes default settings for headers, authentication, and response types. ```go func GetJSONRequest() *resty.Request ``` ```go request := client.GetJSONRequest() request.SetPathParams(map[string]string{"id": "123"}) resp, err := request.Get(url) ```