Cobra Shell 补全完整指南:从默认 completion 命令到自定义动态补全(以 traitor 项目为例)
Cobra Shell 补全完整指南:从默认 completion 命令到自定义动态补全(以 traitor 项目为例)
Cobra 是 Go 生态中最流行的命令行框架之一,其内置的 shell 补全(shell completion)能力可以让你的 CLI 程序在 Bash、Zsh、fish 和 PowerShell 四种 shell 下获得开箱即用的 Tab 补全体验。本指南以 traitor(一个基于 Cobra 构建的 Linux 权限提升框架)仓库中 vendored 的 Cobra 官方文档 shell_completions.md 为核心骨架,系统讲解补全的启用方式、默认 completion 命令的定制、名词(nouns)与 flag 值的静态/动态补全、ShellCompDirective 指令语义以及各 shell 的差异与限制;阅读后你将能够为自己的 Cobra 程序接入完整的 Tab 补全,并能用 __complete 隐藏命令与调试函数定位补全逻辑问题。
Cobra 补全机制概览
Cobra 可以为一个程序同时生成四种 shell 的补全脚本,目前支持的 shell 为:
- Bash
- Zsh
- fish
- PowerShell
与它自动提供 help 命令的方式类似,Cobra 会自动为你的程序提供一个功能完整的 completion 命令。你不需要写任何代码,只要程序是基于 Cobra 构建、且根命令带有子命令,就会自动获得 completion 这个子命令。这一点在源码中有明确实现:initDefaultCompletionCmd()(completions.go)会在满足以下三个条件时自动挂载默认补全命令:
- 程序没有通过
CompletionOptions.DisableDefaultCmd显式禁用该功能; - 根命令存在子命令(
c.HasSubCommands()); - 程序中尚未存在名为
completion的命令或别名。
以 traitor 项目为例,其根命令定义在 internal/cmd/root.go,通过 AddCommand 挂载了 list、backdoor、setuid 等子命令(见 internal/cmd/list.go、internal/cmd/backdoor.go、internal/cmd/setuid.go),因此编译出的 traitor 二进制天然带有 completion 命令,可直接执行 traitor completion bash、traitor completion zsh、traitor completion fish、traitor completion powershell 来生成补全脚本。
为四种 shell 启用补全
Cobra 默认补全命令会为每种 shell 生成对应的补全脚本,并打印出各自的加载说明。以程序名 <prog> 为例,各 shell 的启用方式如下。
Bash
# 当前会话立即生效
$ source <(<prog> completion bash)
# 为每个新会话加载,只需执行一次:
# Linux:
$ <prog> completion bash > /etc/bash_completion.d/<prog>
# macOS:
$ <prog> completion bash > $(brew --prefix)/etc/bash_completion.d/<prog>
生成的 bash 补全脚本依赖 bash_completion 包,建议在补全命令的 help 文本中提示用户如何安装它。
Zsh
# 如果环境中尚未启用 shell 补全,先执行一次:
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
# 为每个新会话加载,只需执行一次:
$ <prog> completion zsh > "${fpath[1]}/_<prog>"
# 需要启动一个新的 shell 才能生效
fish
# 当前会话立即生效
$ <prog> completion fish | source
# 为每个新会话加载,只需执行一次:
$ <prog> completion fish > ~/.config/fish/completions/<prog>.fish
PowerShell
# 当前会话立即生效
PS> <prog> completion powershell | Out-String | Invoke-Expression
# 为每个新会话加载,执行一次:
PS> <prog> completion powershell > <prog>.ps1
# 然后从你的 PowerShell profile 中 source 该文件
对照 traitor 的实际命令行结构,可以这样落地:
traitor completion bash | source
traitor completion zsh > "${fpath[1]}/_traitor"
traitor completion fish > ~/.config/fish/completions/traitor.fish
traitor completion powershell > traitor.ps1
启用后,输入 traitor l 后按 Tab 会补全出 list 子命令,输入 traitor - 后按 Tab 会列出 -a(--any)、-p(--with-password)、-e(--exploit)、-k(--skip)等由 root.go 通过 PersistentFlags() 注册的全局 flag——这些都是 Cobra 依据命令树与 flag 定义自动生成的,无需额外编码。
创建你自己的 completion 命令
如果你不希望使用默认的 completion 命令,可以自己实现一个,它会优先于默认命令生效(这也为那些已经自带 completion 命令的程序提供了向后兼容)。在使用 cobra-cli 生成器创建项目后,可以通过 cobra-cli add completion 生成骨架,再修改 cmd/completion.go 为如下形态(把补全脚本写入 stdout 能获得最大的使用灵活性):
var completionCmd = &cobra.Command{
Use: "completion [bash|zsh|fish|powershell]",
Short: "Generate completion script",
Long: fmt.Sprintf(`To load completions:
Bash:
$ source <(%[1]s completion bash)
# To load completions for each session, execute once:
# Linux:
$ %[1]s completion bash > /etc/bash_completion.d/%[1]s
# macOS:
$ %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s
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:
$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"
# You will need to start a new shell for this setup to take effect.
fish:
$ %[1]s completion fish | source
# To load completions for each session, execute once:
$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish
PowerShell:
PS> %[1]s completion powershell | Out-String | Invoke-Expression
# To load completions for every new session, run:
PS> %[1]s completion powershell > %[1]s.ps1
# and source this file from your PowerShell profile.
`, cmd.Root().Name()),
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)
}
},
}
注意几个关键细节:
ValidArgs: []string{"bash", "zsh", "fish", "powershell"}配合Args: cobra.ExactValidArgs(1)限制了补全候选与参数数量;- 这里用
ValidArgs做的是静态名词补全(详见下文),而DisableFlagsInUseLine: true保证用法行里不会混入 flag; - 重要警告:cobra 生成器可能向 stdout 输出额外信息(例如加载配置文件时的提示),这会破坏自动补全脚本,必须移除。
这个例子中调用的 GenBashCompletion、GenZshCompletion、GenFishCompletion、GenPowerShellCompletionWithDesc 都是 Cobra 提供的生成器函数,分别对应 bash_completions.go、zsh_completions.go、fish_completions.go、powershell_completions.go 等源码文件中的实现。
定制默认 completion 命令
如果你保留默认的 completion 命令,Cobra 提供 CompletionOptions 结构体来定制其行为。该结构体定义在 completions.go,包含四个字段,必须设置在根命令上。
禁用默认 completion 命令
rootCmd.CompletionOptions.DisableDefaultCmd = true
设置后,Cobra 将不再自动提供 completion 命令。如前面所述,initDefaultCompletionCmd 首先检查的即是该开关。
隐藏 --no-descriptions flag
默认情况下,补全子命令会提供一个 --no-descriptions 布尔 flag,用于关闭补全描述。若不想暴露给用户:
rootCmd.CompletionOptions.DisableNoDescFlag = true
完全禁用补全描述
rootCmd.CompletionOptions.DisableDescriptions = true
该选项影响所有支持描述的 shell(Bash V2、Zsh、fish、PowerShell)。此外还有一个 HiddenDefaultCmd 字段用于把默认 completion 命令设为隐藏。
自定义补全:名词(nouns)
生成的补全脚本会自动处理命令与 flag 的补全,但要让补全更强大,需要为程序的名词(即位置参数)和 flag 值提供候选信息。Cobra 支持静态与动态两种方式。
静态名词补全:ValidArgs
通过 ValidArgs 字段提供预定义的候选列表。例如想让 kubectl get [tab][tab] 显示合法名词,可以这样写(简化自 kubectl get 的代码):
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) {
cobra.CheckErr(RunGet(f, out, cmd, args))
},
ValidArgs: validArgs,
}
注意 ValidArgs 是设置在 get 子命令上的,效果如下:
$ kubectl get [tab][tab]
node pod replicationcontroller service
名词别名:ArgAliases
如果名词存在别名,可用 ArgAliases 与 ValidArgs 并列定义:
argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
cmd := &cobra.Command{
...
ValidArgs: validArgs,
ArgAliases: argAliases
}
别名不会出现在 Tab 补全的候选列表里,但会被补全算法接受为合法名词——前提是用户手动输入了别名:
$ kubectl get rc [tab][tab]
backend frontend database
若不把 rc 声明为别名,补全算法就不知道在 rc 之后该展示 replication controller 列表。
动态名词补全:ValidArgsFunction
有些场景无法预知候选列表,必须在执行时动态获取。此时用 ValidArgsFunction 字段注册一个 Go 函数,Cobra 在需要名词候选时会调用它。注意:同一个命令上 ValidArgs 与 ValidArgsFunction 只能二选一。下面是简化自 helm status 的代码:
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, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
},
}
其中 getReleasesFromCluster() 是获取集群中当前 Helm release 列表的 Go 函数。假设集群上有 harbor、notary、rook、thanos 四个 release,效果为:
$ helm status [tab][tab]
harbor notary rook thanos
注意示例中返回了 cobra.ShellCompDirectiveNoFileComp——这是下面要讲的 ShellCompDirective 指令之一。另外重要的一点:使用 ValidArgsFunction 时,Cobra 会先解析命令行中已提供的所有 flag 和参数,再调用你注册的函数,因此你不需要自己解析这些参数。例如用户输入 helm status --namespace my-rook-ns [tab][tab] 时,Cobra 会像调用 RunE 一样先解析 --namespace flag,再调用你的 ValidArgsFunction。
ShellCompDirective 指令详解
ShellCompDirective 是一个位字段(bit field),用于控制 shell 在收到补全结果后的行为,可用按位或运算符组合,例如 cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp。其完整定义见 completions.go:
// 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
各指令语义小结:
| 指令 | 含义 |
|---|---|
ShellCompDirectiveDefault |
补全后让 shell 执行默认行为(隐含不使用其他指令) |
ShellCompDirectiveError |
发生错误,补全结果应被忽略 |
ShellCompDirectiveNoSpace |
即使只有一个补全结果,shell 也不要自动追加空格 |
ShellCompDirectiveNoFileComp |
即使没有补全结果,shell 也不要提供文件补全 |
ShellCompDirectiveFilterFileExt |
返回的候选作为文件扩展名过滤器(如只补全 *.json/*.yaml);flag 场景可用 MarkFlagFilename()/MarkPersistentFlagFilename() 快捷实现 |
ShellCompDirectiveFilterDirs |
文件补全只提供目录名;若要限定在某个目录内搜索,返回该单个目录名(如 {"themes"}) |
调试动态补全
Cobra 通过一个隐藏命令实现动态补全。当用户按下 Tab 时,补全脚本会调用程序内的 __complete 隐藏命令来请求候选。要调试你的 Go 补全代码,可以直接调用该隐藏命令:
$ helm __complete status har<ENTER>
harbor
:4
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
重要:如果待补全的名词为空(用户尚未输入任何字符),必须给 __complete 传一个空参数:
$ helm __complete status ""<ENTER>
harbor
notary
rook
thanos
:4
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
可以看到候选列表之后输出一行 :<directive值>,这是补全脚本解析指令的依据;stdout 上的每个候选会被脚本当作补全选项,而 stderr 上的提示信息(Completion ended with directive: ...)会被脚本忽略。
直接调用 __complete 允许你挂上 Go 调试器排查问题,也可以在代码中加打印输出。但绝对不要在补全代码里向 stdout 打印普通信息,因为它们会被补全脚本误认为是补全候选。Cobra 为此提供了专门的调试函数(实现见 completions.go):
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
// is set to a file path) and optionally prints to stderr.
cobra.CompDebug(msg string, printToStdErr bool) {
cobra.CompDebugln(msg string, printToStdErr bool)
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
// is set to a file path) and to stderr.
cobra.CompError(msg string)
cobra.CompErrorln(msg string)
CompDebug 系列只在环境变量 BASH_COMP_DEBUG_FILE 指向某个文件路径时才会写入调试日志,并且可选地同步打印到 stderr;CompError 系列则固定打印到 stderr。这两个通道都不会污染 stdout 上的补全候选流。
自定义补全:flag
将 flag 标记为必填
大多数情况下补全只展示子命令;但如果某个 flag 是子命令运行所必需的,你可能希望在用户按 Tab 时让它出现。用 MarkFlagRequired 标记:
cmd.MarkFlagRequired("pod")
cmd.MarkFlagRequired("container")
效果:
$ kubectl exec [tab][tab]
-c --container= -p --pod=
该方法通过给 flag 设置 BashCompOneRequiredFlag 注解实现,见 shell_completions.go,同时它也会让命令在缺少该 flag 时报错。对应地还有 MarkPersistentFlagRequired 可作用于持久化 flag。
动态 flag 补全:RegisterFlagCompletionFunc
与名词类似,Cobra 也支持为 flag 定义动态补全:用 command.RegisterFlagCompletionFunc() 注册一个 Go 函数,Cobra 在需要该 flag 的候选时调用它:
flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
})
注意 RegisterFlagCompletionFunc() 要在该 flag 所属的命令上调用。效果:
$ helm status --output [tab][tab]
json table yaml
从源码看(completions.go),该函数要求 flag 必须已存在(否则返回 flag 'xxx' does not exist 错误),且每个 flag 只能注册一次。调试方式与名词相同:
$ helm __complete status --output ""
json
table
yaml
:4
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
同样地,不要在补全代码中向 stdout 打印普通痕迹,请使用上面提到的 CompDebug/CompError 系列。
为接受文件名的 flag 限定扩展名
两种等价写法:
flagName := "output"
cmd.MarkFlagFilename(flagName, "yaml", "json")
或
flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
MarkFlagFilename 本质上是把 BashCompFilenameExt 注解写入 flag(见 shell_completions.go),另有 MarkPersistentFlagFilename 对应持久化 flag。
将 flag 补全限定为目录名
flagName := "output"
cmd.MarkFlagDirname(flagName)
或
flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return nil, cobra.ShellCompDirectiveFilterDirs
})
要限定在另一个目录内的目录名,组合使用 RegisterFlagCompletionFunc 与 ShellCompDirectiveFilterDirs,返回单个目录名作为搜索范围:
flagName := "output"
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
})
补全描述(Descriptions)
Cobra 支持为补全项附加描述,各 shell 均支持(bash 仅在 completion V2 下可用)。对命令和 flag,Cobra 会基于 usage 信息自动提供描述。例如 zsh 下:
$ helm s[tab]
search -- search for a keyword in charts
show -- show information of a chart
status -- displays the status of the named release
fish 下:
$ helm s[tab]
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
你也可以为自己的补全项添加描述:在每个补全项后追加 \t 分隔的描述文本。这一技巧适用于 ValidArgs、ValidArgsFunction 和 RegisterFlagCompletionFunc() 返回的所有补全项:
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
}}
或
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
顺带一提,默认 completion 命令本身就用到了这种机制:从 completions.go 可以看到它通过 ValidArgsFunction: NoFileCompletions 来阻止对 completion 命令做文件补全。
各 shell 的差异与限制
Bash 补全
依赖:生成的 bash 补全脚本依赖 bash_completion 包,应在补全命令的帮助文本中提示安装方法。
别名:可以为程序配置 bash 别名,别名同样获得补全支持:
alias aliasname=origcommand
complete -o default -F __start_origcommand aliasname
# and now when you run `aliasname` completion will make
# suggestions as it did for `origcommand`.
$ aliasname <tab><tab>
completion firstcommand secondcommand
Legacy 动态补全:出于向后兼容,Cobra 仍支持旧的 bash legacy 动态补全方案,详见 bash_completions.md。
Bash completion V2:Cobra 提供两个版本的 bash 补全。原版通过 GenBashCompletion() 或 GenBashCompletionFile() 使用;新版通过 GenBashCompletionV2() 或 GenBashCompletionFileV2() 使用(源码见 bash_completionsV2.go)。V2 版本不支持 legacy 动态补全,只与本文描述的 Go 动态补全方案配合。除非你的程序已经在用 legacy 方案,否则推荐使用 V2,它有以下优势:
- 支持补全描述(与其他 shell 一致);
- 补全脚本不足 300 行(V1 会生成数千行,例如
kubectl的 bash V1 补全脚本超过 13K 行); - 与其他 shell 对齐的补全体验更流畅。
调用 GenBashCompletionV2 系列函数时必须传入是否带描述的布尔参数,Cobra 会基于 usage 信息自动提供描述,你可以把这个选项开放给用户:
# With descriptions
$ helm s[tab][tab]
search (search for a keyword in charts) status (display the status of the named release)
show (show information of a chart)
# Without descriptions
$ helm s[tab][tab]
search show status
注意:Cobra 的默认 completion 命令使用的就是 bash completion V2(见 completions.go 中 GenBashCompletionV2 的调用)。如果因某些原因必须使用 V1,则需要自行实现 completion 命令。
Zsh 补全
Cobra 支持从根 cobra.Command 生成原生 zsh 补全。生成的脚本应放入 $fpath 中的某个目录,并命名为 _<你的程序名>,之后需要启动新的 shell 才能生效。
zsh 支持补全描述,Cobra 会基于 usage 信息自动提供;如需完全禁用描述,可使用 GenZshCompletionNoDesc() 或 GenZshCompletionFileNoDesc()(见 zsh_completions.go),同样可以做成用户可配置的选项:
# With descriptions
$ helm s[tab]
search -- search for a keyword in charts
show -- show information of a chart
status -- displays the status of the named release
# Without descriptions
$ helm s[tab]
search show status
注:由于向后兼容的要求,zsh 与 fish 禁用描述的 API 是不同的。
限制:
- 用 Bash 脚本实现的 legacy 自定义补全(包括
BashCompCustomflag 注解)在 zsh 下不被支持、会被忽略,应改用跨 shell 可移植的ValidArgsFunction与RegisterFlagCompletionFunc(); MarkFlagCustom()在 zsh 下不被支持、会被忽略,应改用RegisterFlagCompletionFunc()。
自 Cobra 1.1 起,zsh 补全行为已标准化以对齐其他 shell,API 保持向后兼容但行为略有变化,详见 zsh_completions.md。
fish 补全
Cobra 支持从根 cobra.Command 生成原生 fish 补全,使用 command.GenFishCompletion() 或 command.GenFishCompletionFile()(见 fish_completions.go),必须传入是否带描述的布尔参数,Cobra 会基于 usage 信息自动提供描述:
# With descriptions
$ helm s[tab]
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
# Without descriptions
$ helm s[tab]
search show status
限制:
- Bash 脚本 legacy 自定义补全(含
BashCompCustom注解)不被支持、会被忽略; MarkFlagCustom()不被支持、会被忽略,应改用RegisterFlagCompletionFunc();- 以下 flag 补全注解不被支持、会被忽略:
BashCompFilenameExt(按扩展名过滤)、BashCompSubdirsInDir(按目录过滤); - 对应的函数同样不被支持:
MarkFlagFilename()、MarkPersistentFlagFilename()、MarkFlagDirname()、MarkPersistentFlagDirname(); - 对应的指令同样不被支持:
ShellCompDirectiveFilterFileExt、ShellCompDirectiveFilterDirs。
PowerShell 补全
Cobra 支持从根 cobra.Command 生成原生 PowerShell 补全,使用 command.GenPowerShellCompletion() 或 command.GenPowerShellCompletionFile();如需描述则用 command.GenPowerShellCompletionWithDesc() 和 command.GenPowerShellCompletionFileWithDesc()。
脚本支持 PowerShell 的三种补全模式:
TabCompleteNext(默认的 Windows 风格,每次按键显示下一个候选)Complete(行为类似 bash)MenuComplete(行为类似 zsh)
通过 Set-PSReadLineKeyHandler -Key Tab -Function <mode> 切换模式。描述仅在 Complete 或 MenuComplete 模式下显示:
# With descriptions and Mode 'Complete'
$ helm s[tab]
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
$ helm s[tab]
search show status
search for a keyword in charts
# Without descriptions
$ helm s[tab]
search show status
用户需要 PowerShell 5.0 及以上版本(Windows 10 自带,Windows 7/8.1 可单独下载)。将补全脚本写入文件后,从 PowerShell profile(由 $Profile 环境变量引用)中 source 该文件,可查看 Get-Help about_Profiles 了解更多。
限制(与 fish 基本一致):
- Bash 脚本 legacy 自定义补全(含
BashCompCustom注解)不被支持、会被忽略; MarkFlagCustom()不被支持、会被忽略,应改用RegisterFlagCompletionFunc();BashCompFilenameExt、BashCompSubdirsInDir注解不被支持、会被忽略;MarkFlagFilename()、MarkPersistentFlagFilename()、MarkFlagDirname()、MarkPersistentFlagDirname()不被支持、会被忽略;ShellCompDirectiveFilterFileExt、ShellCompDirectiveFilterDirs指令不被支持、会被忽略。
在 traitor 项目中落地点
traitor 的命令行完全基于 Cobra 构建(go.mod 中依赖 github.com/spf13/cobra v1.5.0),其入口 cmd/traitor/main.go 调用 cmd.Execute(),而根命令与子命令树定义在 internal/cmd/root.go。从源码结构可以推断:
- 根命令通过
PersistentFlags()注册了-a/--any、-p/--with-password、-e/--exploit、-k/--skip四个全局 flag(root.go),这些 flag 的候选会自动纳入补全; - 子命令
list(internal/cmd/list.go)、backdoor install/uninstall(internal/cmd/backdoor.go)、setuid(internal/cmd/setuid.go)均会被补全脚本覆盖; setuid子命令的本地 flag-s/--shell与-c/--cmd(setuid.go)也会自动获得补全;- 由于根命令存在子命令且未禁用该功能,Cobra 会自动挂载默认
completion命令(对应 initDefaultCompletionCmd 的逻辑)。
若未来要为 -e/--exploit 这样的 flag 提供"已知 exploit 名称"的动态候选(例如从 pkg/exploits 的注册表读取),只需在 root.go 中调用 rootCmd.RegisterFlagCompletionFunc("exploit", ...),即可让用户在输入 traitor -e [tab][tab] 时看到所有可用 exploit 名称——这正是本文所述 flag 动态补全能力的典型落地场景。
总结
Cobra 的 shell 补全体系分为四个层次:默认 completion 命令(开箱即用,四种 shell 全覆盖)、CompletionOptions 定制(禁用命令/flag/描述)、名词补全(静态 ValidArgs/ArgAliases 与动态 ValidArgsFunction 二选一)、flag 补全(MarkFlagRequired、RegisterFlagCompletionFunc、MarkFlagFilename/MarkFlagDirname)。动态补全统一通过隐藏的 __complete 命令驱动,配合 ShellCompDirective 位字段控制 shell 行为,用 CompDebug/CompError 系列在 BASH_COMP_DEBUG_FILE 指定的文件中留痕排查。编写跨 shell 补全逻辑时,优先使用 ValidArgsFunction 与 RegisterFlagCompletionFunc() 这对可移植 API,并留意 fish/PowerShell 对文件扩展名与目录过滤指令的差异,即可让你的 Go CLI 在主流 shell 下获得一致而强大的 Tab 补全体验。