如何解决Cobra在zsh环境下无空格触发动态自动补全的问题
问题根因
你当前的ValidArgsFunction触发逻辑完全错位:
当你输入core list hg pg<TAB>(无尾随空格)时,还处于第一个位置参数(hostgroup name)的输入过程中,此时args数组长度为0,你输入的pg是待补全的前缀,存储在入参toComplete中。而你现有逻辑仅在len(args) == 1(即第一个参数已输入完成、后面加了空格)时才返回补全结果,自然只能在加空格后触发补全。
修改方案
仅需调整Go代码中ValidArgsFunction的逻辑即可,无需修改zsh补全脚本:
- 将触发补全的条件改为
len(args) == 0(未输入第一个位置参数时) - 传入
toComplete作为前缀查询匹配的主机组列表
修改后的代码如下:
func ListCmdHG() *cobra.Command { cmd := &cobra.Command{ Use: "hg <hostgroup name> [(-o|--output=)json|yaml|text(default)]", Short: "Shows list HOSTs or VMs of specified hostgroup", Long: "Shows list HOSTs or VMs of specified hostgroup", Args: cobra.ExactArgs(1), ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { result := make([]string, 0) // 仅在第一个位置参数未输入完成时返回补全列表 if len(args) == 0 { // 传入当前输入的前缀toComplete,查询匹配的主机组列表 // 注意:如果原来的GetHostGroupList是传入hostgroup名返回下属VM,请替换为按前缀搜索hostgroup的方法 result = suggester.NewClient().GetHostGroupList(toComplete) } return result, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp }, Run: func(cmd *cobra.Command, args []string) { hg := args[0] vms, err := S.ListHG(hg) if err != nil { fmt.Println(err) os.Exit(0) } output := S.Formatte.ListVMPrint(hg, cmd.Flag("output").Value.String(), vms) fmt.Println(output) }, } cmd.PersistentFlags().StringP("output", "o", "text", "Format output") return cmd }
注意事项
如果你的GetHostGroupList方法目前的逻辑是传入已存在的hostgroup名称,返回该hostgroup下的VM列表,请替换为按前缀搜索匹配的hostgroup名称列表的方法,才能得到符合预期的补全结果。
内容的提问来源于stack exchange,提问作者simak92
相关产品推荐
相关产品推荐

