Skip to content
The Chat Archive
claude-sonnet-4-20250514· Anthropic LMArena Human Preference 140K

GoLang cobra. How to use autocompletion

  1. User

    GoLang cobra. How to use autocompletion

  2. Assistant

    Cobra provides built-in support for shell autocompletion through its completion commands. Here's how to set it up:

    Adding Completion to Your CLI

    First, add the completion command to your root command:

    package main
    
    import (
        "github.com/spf13/cobra"
    )
    
    var rootCmd = &cobra.Command{
        Use:   "myapp",
        Short: "My CLI application",
    }
    
    func init() {
        // Add the completion command
        rootCmd.AddCommand(completionCmd)
    }
    
    var completionCmd = &cobra.Command{
        Use:   "completion [bash|zsh|fish|powershell]",
        Short: "Generate completion script",
        Long: `To load completions:
    
    Bash:
      $ source <(myapp completion bash)
    
    Zsh:
      $ source <(myapp completion zsh)
    
    Fish:
      $ myapp completion fish | source
    
    PowerShell:
      PS> myapp completion powershell | Out-String | Invoke-Expression
    `,
        DisableFlagsInUseLine: true,
        ValidArgs:             []string{"bash", "zsh", "fish", "powershell"},
        Args:                  cobra.ExactValidArgs(1),
        Run: func(cmd *cobra.Command, args []string) {
            switch args[0] {
            case "bash":
                cmd.Root().GenBashCompletion(os.Stdout)
            case "zsh":
                cmd.Root().GenZshCompletion(os.Stdout)
            case "fish":
                cmd.Root().GenFishCompletion(os.Stdout, true)
            case "powershell":
                cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
            }
        },
    }
    

    Installing Completions

    Users can then install completions by running:

    # For bash
    source <(myapp completion bash)
    
    # For zsh  
    source <(myapp completion zsh)
    
    # For fish
    myapp completion fish | source
    

    Custom Completions

    You can also add custom completion logic for specific commands or flags:

    var exampleCmd = &cobra.Command{
        Use:   "example",
        Short: "Example command with custom completion",
        ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
            // Return custom completions
            return []string{"option1", "option2", "option3"}, cobra.ShellCompDirectiveDefault
        },
    }
    
    // For flag completions
    cmd.RegisterFlagCompletionFunc("config", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
        return []string{"config1.yaml", "config2.yaml"}, cobra.ShellCompDirectiveDefault
    })
    

    The completion system will automatically handle subcommands, flags, and any custom completion functions you define.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.