区分 Cobra 帮助消息中的必需标志和可选标志

发布于 2025-01-11 11:42:04 字数 1245 浏览 0 评论 0原文

我创建了一个命令,如下所示:

cmd := &cobra.Command{
    Use:       "get",
    Short:     "Gets information",
    Long:      heredoc.Doc("Long description"),
    Example:   heredoc.Doc("example"),
    ValidArgs: []string{"arg1", "arg2", "arg3"},
    RunE: func(cmd *cobra.Command, args []string) error {
        return myCustomExecutionFunc()
    },
    SilenceErrors: true,
}

cmd.PersistentFlags().StringVarP(arg1, "arg1", "", "", "Arg1 definition")
cmd.MarkPersistentFlagRequired("arg1")
cmd.PersistentFlags().StringVarP(arg2, "arg2", "", "", "Arg2 definition")
cmd.MarkPersistentFlagRequired("arg2")
cmd.PersistentFlags().StringVarP(arg3, "arg3", "", "", "Arg3 definition")

现在,当使用 --help 运行命令时,我会收到如下帮助消息。

Flags:
arg1  Arg1 definition
arg3  Arg3 definition
arg2  Arg2 definition

我想将标志分组为持久(必需)和非持久(非必需),如下所示

Required Flags:
arg1  Arg1 definition
arg2  Arg2 definition

Optional Flags:
arg3  Arg3 definition 

Or something like below

Flags:
arg1  Required Arg1 definition
arg2  Required Arg2 definition
arg3  Optional Arg3definition

我知道我可以使用 SetHelpTemplate() 函数并设置我自己的字符串,该字符串将在帮助时显示实例化后,我想知道是否有本地眼镜蛇库或 pflag 方式来定义不同类别的标志。

I have created a command as follows:

cmd := &cobra.Command{
    Use:       "get",
    Short:     "Gets information",
    Long:      heredoc.Doc("Long description"),
    Example:   heredoc.Doc("example"),
    ValidArgs: []string{"arg1", "arg2", "arg3"},
    RunE: func(cmd *cobra.Command, args []string) error {
        return myCustomExecutionFunc()
    },
    SilenceErrors: true,
}

cmd.PersistentFlags().StringVarP(arg1, "arg1", "", "", "Arg1 definition")
cmd.MarkPersistentFlagRequired("arg1")
cmd.PersistentFlags().StringVarP(arg2, "arg2", "", "", "Arg2 definition")
cmd.MarkPersistentFlagRequired("arg2")
cmd.PersistentFlags().StringVarP(arg3, "arg3", "", "", "Arg3 definition")

Now when run the command with --help I get the help message as follows.

Flags:
arg1  Arg1 definition
arg3  Arg3 definition
arg2  Arg2 definition

I want to group the flags as persistent (required) and non-persistent (not required) as follows

Required Flags:
arg1  Arg1 definition
arg2  Arg2 definition

Optional Flags:
arg3  Arg3 definition 

Or something like below

Flags:
arg1  Required Arg1 definition
arg2  Required Arg2 definition
arg3  Optional Arg3definition

I know I can use the SetHelpTemplate() function and set my own string that will be shown when help is instantiated, I'm wondering if there is a native cobra library or pflag way to define different categories of flags.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文