varcompletionCmd=&cobra.Command{Use:"completion [bash|zsh|fish|powershell]",Short:"Generate completion script",Long:`To load completions:
Bash:
$ source <(yourprogram completion bash)
# To load completions for each session, execute once:
Linux:
$ yourprogram completion bash > /etc/bash_completion.d/yourprogram
MacOS:
$ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram
Zsh:
# If shell completion is not already enabled in your environment you will need
# to enable it. You can execute the following once:
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
# To load completions for each session, execute once:
$ yourprogram completion zsh > "${fpath[1]}/_yourprogram"
# You will need to start a new shell for this setup to take effect.
Fish:
$ yourprogram completion fish | source
# To load completions for each session, execute once:
$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
`,DisableFlagsInUseLine:true,ValidArgs:[]string{"bash","zsh","fish","powershell"},Args:cobra.ExactValidArgs(1),Run:func(cmd*cobra.Command,args[]string){switchargs[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().GenPowerShellCompletion(os.Stdout)}},}
validArgs[]string={"pod","node","service","replicationcontroller"}cmd:=&cobra.Command{Use:"get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",Short:"Display one or many resources",Long:get_long,Example:get_example,Run:func(cmd*cobra.Command,args[]string){err:=RunGet(f,out,cmd,args)util.CheckErr(err)},ValidArgs:validArgs,}
这里是模仿 kubectl 的 get 子命令,在执行该命令时效果如下:
1
2
$ kubectl get [tab][tab]node pod replicationcontroller service
$ kubectl get rc [tab][tab]backend frontend database
这里如果不声明 rc 为别名,则补全算法将无法补全后续的内容。
动态名称补全
如果需要补全的名称是动态生成的,例如 helm status [tab] 这里的 release 值,就需要用到 ValidArgsFunction 字段,将需要返回的内容以 function 的形式声明在 cobra.Command 中,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cmd:=&cobra.Command{Use:"status RELEASE_NAME",Short:"Display the status of the named release",Long:status_long,RunE:func(cmd*cobra.Command,args[]string){RunGet(args[0])},ValidArgsFunction:func(cmd*cobra.Command,args[]string,toCompletestring)([]string,cobra.ShellCompDirective){iflen(args)!=0{returnnil,cobra.ShellCompDirectiveNoFileComp}returngetReleasesFromCluster(toComplete),cobra.ShellCompDirectiveNoFileComp},}
// Indicates that the shell will perform its default behavior after completions// have been provided (this implies none of the other directives).ShellCompDirectiveDefault// Indicates an error occurred and completions should be ignored.ShellCompDirectiveError// Indicates that the shell should not add a space after the completion,// even if there is a single completion provided.ShellCompDirectiveNoSpace// Indicates that the shell should not provide file completion even when// no completion is provided.ShellCompDirectiveNoFileComp// Indicates that the returned completions should be used as file extension filters.// For example, to complete only files of the form *.json or *.yaml:// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()// is a shortcut to using this directive explicitly.//ShellCompDirectiveFilterFileExt// Indicates that only directory names should be provided in file completion.// For example:// return nil, ShellCompDirectiveFilterDirs// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.//// To request directory names within another directory, the returned completions// should specify a single directory name within which to search. For example,// to complete directories within "themes/":// return []string{"themes"}, ShellCompDirectiveFilterDirs//ShellCompDirectiveFilterDirs
注意
ValidArgs 和 ValidArgsFunction 同时只能存在一个。在使用 ValidArgsFunction 时,Cobra 将在解析了命令行中提供的所有 flag 和参数之后才会调用您的注册函数。
Flag 补全
指定必选 flag
大多时候,名字补全只会提示子命令的补全,但如果一些 flag 是必须的,也可以在用户按 TAB 键时进行自动补全,代码如下: