This document covers Cobra's shell completion functionality, including completion generation, customization, and the completion API for bash, zsh, fish, and PowerShell.
func (c *Command) GenBashCompletion(w io.Writer) error
func (c *Command) GenBashCompletionFile(filename string) error
func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error
func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error
func (c *Command) GenZshCompletion(w io.Writer) error
func (c *Command) GenZshCompletionFile(filename string) error
func (c *Command) GenZshCompletionNoDesc(w io.Writer) error
func (c *Command) GenZshCompletionFileNoDesc(filename string) error
func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error
func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error
func (c *Command) GenPowerShellCompletion(w io.Writer) error
func (c *Command) GenPowerShellCompletionFile(filename string) error
func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error
func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) errorGenerate completion scripts:
package main
import (
"github.com/spf13/cobra"
"os"
)
func main() {
rootCmd := &cobra.Command{Use: "myapp"}
// Add subcommands...
// Generate bash completion to stdout
rootCmd.GenBashCompletion(os.Stdout)
// Generate to file
rootCmd.GenBashCompletionFile("/usr/local/etc/bash_completion.d/myapp")
// Bash v2 with descriptions
rootCmd.GenBashCompletionFileV2("/usr/local/etc/bash_completion.d/myapp", true)
// Zsh with descriptions
rootCmd.GenZshCompletionFile("/usr/local/share/zsh/site-functions/_myapp")
// Fish with descriptions
rootCmd.GenFishCompletionFile("~/.config/fish/completions/myapp.fish", true)
// PowerShell with descriptions
rootCmd.GenPowerShellCompletionFileWithDesc("myapp.ps1")
}type Completion = stringA Completion is a string that can be used for completions. Two formats are supported:
"option1""option1\tThis is option 1"func CompletionWithDesc(choice string, description string) CompletionCreate a completion with description:
completions := []cobra.Completion{
cobra.CompletionWithDesc("json", "JSON format"),
cobra.CompletionWithDesc("yaml", "YAML format"),
cobra.CompletionWithDesc("xml", "XML format"),
}type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)CompletionFunc provides dynamic completion results. Parameters:
Returns:
cmd := &cobra.Command{
Use: "get",
Short: "Get resources",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
if len(args) == 0 {
// First argument: resource type
return []cobra.Completion{
cobra.CompletionWithDesc("pod", "Kubernetes pod"),
cobra.CompletionWithDesc("service", "Kubernetes service"),
cobra.CompletionWithDesc("deployment", "Kubernetes deployment"),
}, cobra.ShellCompDirectiveDefault
}
if len(args) == 1 {
// Second argument: resource name
// Query cluster for resource names based on args[0]
names := getResourceNames(args[0])
return names, cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective)Disables file completion for commands that should not trigger file completions:
cmd := &cobra.Command{
Use: "status",
ValidArgsFunction: cobra.NoFileCompletions,
}func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFuncCreates a completion function that always returns the same results:
fixedOptions := []cobra.Completion{"option1", "option2", "option3"}
cmd := &cobra.Command{
Use: "select",
ValidArgsFunction: cobra.FixedCompletions(fixedOptions, cobra.ShellCompDirectiveDefault),
}
// Or for flags
cmd.RegisterFlagCompletionFunc("format",
cobra.FixedCompletions(
[]cobra.Completion{"json", "yaml", "xml"},
cobra.ShellCompDirectiveDefault,
),
)type ShellCompDirective int
const (
ShellCompDirectiveDefault ShellCompDirective = 0
ShellCompDirectiveError
ShellCompDirectiveNoSpace
ShellCompDirectiveNoFileComp
ShellCompDirectiveFilterFileExt
ShellCompDirectiveFilterDirs
ShellCompDirectiveKeepOrder
)Directives control shell behavior after providing completions:
Directives are bit flags and can be combined:
return completions, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileCompNo file completion:
return []cobra.Completion{"option1", "option2"}, cobra.ShellCompDirectiveNoFileCompFilter files by extension:
return []cobra.Completion{".txt", ".log", ".md"}, cobra.ShellCompDirectiveFilterFileExtOnly directories:
return []cobra.Completion{}, cobra.ShellCompDirectiveFilterDirsKeep order, no space:
return orderedOptions, cobra.ShellCompDirectiveKeepOrder | cobra.ShellCompDirectiveNoSpacecmd := &cobra.Command{
Use: "format",
ValidArgs: []cobra.Completion{
cobra.CompletionWithDesc("json", "JSON format"),
cobra.CompletionWithDesc("yaml", "YAML format"),
cobra.CompletionWithDesc("xml", "XML format"),
},
}Or without descriptions:
cmd := &cobra.Command{
Use: "format",
ValidArgs: []cobra.Completion{"json", "yaml", "xml"},
}type CompletionOptions struct {
DisableDefaultCmd bool
DisableNoDescFlag bool
DisableDescriptions bool
HiddenDefaultCmd bool
DefaultShellCompDirective *ShellCompDirective
}
func (receiver *CompletionOptions) SetDefaultShellCompDirective(directive ShellCompDirective)
type SliceValue interface {
GetSlice() []string
}Configure completion behavior:
rootCmd := &cobra.Command{
Use: "myapp",
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: false, // Allow default "completion" command
DisableNoDescFlag: false, // Allow "--no-descriptions" flag
DisableDescriptions: false, // Show descriptions
HiddenDefaultCmd: false, // Don't hide completion command
},
}
// Or set default directive
rootCmd.CompletionOptions.SetDefaultShellCompDirective(cobra.ShellCompDirectiveNoFileComp)func (c *Command) InitDefaultCompletionCmd(args ...string)Cobra automatically adds a default 'completion' command unless:
Initialize manually if needed:
rootCmd.InitDefaultCompletionCmd()func GetActiveHelpConfig(cmd *Command) string
func AppendActiveHelp(compArray []Completion, activeHelpStr string) []CompletionActiveHelp provides help messages during completion.
GetActiveHelpConfig gets the ActiveHelp environment variable value for the command. The environment variable is <PROGRAM>_ACTIVE_HELP where <PROGRAM> is the root command name in uppercase with non-alphanumeric characters replaced by underscores. Returns "0" if global COBRA_ACTIVE_HELP is set to "0".
activeHelp := cobra.GetActiveHelpConfig(cmd)
if activeHelp != "0" {
// Active help is enabled
}AppendActiveHelp adds active help strings to the completion array. These strings are shown as help to the user during completion:
func myCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
completions := []cobra.Completion{"option1", "option2", "option3"}
// Add active help
completions = cobra.AppendActiveHelp(completions, "Select an option from the list")
completions = cobra.AppendActiveHelp(completions, "Use --verbose for detailed output")
return completions, cobra.ShellCompDirectiveDefault
}func CompDebug(msg string, printToStdErr bool)
func CompDebugln(msg string, printToStdErr bool)
func CompError(msg string)
func CompErrorln(msg string)Debug and error functions for completion scripts:
func customCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
cobra.CompDebugln("Starting custom completion", false)
results, err := fetchCompletions()
if err != nil {
cobra.CompError(fmt.Sprintf("Failed to fetch: %v", err))
return nil, cobra.ShellCompDirectiveError
}
return results, cobra.ShellCompDirectiveDefault
}Debug messages only appear when BASH_COMP_DEBUG_FILE environment variable is set to a log file path.
const (
ShellCompRequestCmd = "__complete"
ShellCompNoDescRequestCmd = "__completeNoDesc"
)Hidden command names used by shell completion scripts:
These are used internally by the completion system.
package main
import (
"github.com/spf13/cobra"
"strings"
)
func main() {
rootCmd := &cobra.Command{Use: "kubectl"}
getCmd := &cobra.Command{
Use: "get",
Short: "Get resources",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
if len(args) == 0 {
// Complete resource types
return []cobra.Completion{
cobra.CompletionWithDesc("pods", "Pod resources"),
cobra.CompletionWithDesc("services", "Service resources"),
cobra.CompletionWithDesc("deployments", "Deployment resources"),
}, cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
// Complete resource names based on type
resourceType := args[0]
names := getResourceNames(resourceType) // Your function
return names, cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
// Register flag completion
getCmd.Flags().StringP("namespace", "n", "default", "Namespace")
getCmd.RegisterFlagCompletionFunc("namespace", func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
namespaces := getNamespaces() // Your function
return namespaces, cobra.ShellCompDirectiveNoFileComp
})
rootCmd.AddCommand(getCmd)
rootCmd.Execute()
}
func getResourceNames(resourceType string) []cobra.Completion {
// Query your system for resource names
return []cobra.Completion{"name1", "name2", "name3"}
}
func getNamespaces() []cobra.Completion {
return []cobra.Completion{"default", "kube-system", "kube-public"}
}See the Flag Management document for flag-specific completion functions:
RegisterFlagCompletionFuncGetFlagCompletionFuncMarkFlagFilenameMarkFlagDirnameMarkFlagCustomAfter generating completion scripts, users typically install them:
Bash:
myapp completion bash > /usr/local/etc/bash_completion.d/myappZsh:
myapp completion zsh > /usr/local/share/zsh/site-functions/_myappFish:
myapp completion fish > ~/.config/fish/completions/myapp.fishPowerShell:
myapp completion powershell | Out-String | Invoke-Expression