douan3414 2019-02-08 00:03
浏览 71
已采纳

帮助模板中的眼镜蛇更改用法行

I want to be able to set the Usage line to specify that an argument NEEDS to be passed if the help function is invoked on the cobra command in Go.

This is what the regular help flag outputs:

Cancel the order specified by the order id by submitting a cancel order.
Optionally, an account ID may be supplied as well for extra measure.

Usage:
  gbutil orders cancel [flags]

Flags:
  -a, --account_id string   the account id that the order belongs to
  -h, --help                help for cancel

Global Flags:
      --config string   config file (default is $HOME/.gbutil.yaml)

I want:

Cancel the order specified by the order id by submitting a cancel order.
Optionally, an account ID may be supplied as well for extra measure.

Usage:
  gbutil orders cancel <order_id> [flags]

Flags:
  -a, --account_id string   the account id that the order belongs to
  -h, --help                help for cancel

Global Flags:
      --config string   config file (default is $HOME/.gbutil.yaml)

I have tried using SetUsageTemplate in the init() function but then it deletes part of the flags:

orderscancelCmd.SetUsageTemplate(strings.Replace(orderscancelCmd.UsageString(), "gbutil orders cancel [flags]", "gbutil orders cancel <order_id> [flags]", 1))

This results in:

Cancel the order specified by the order id by submitting a cancel order.
Optionally, an account ID may be supplied as well for extra measure.

Usage:
  gbutil orders cancel <order_id> [flags]

Flags:
  -a, --account_id string   the account id that the order belongs to

where I lose the -h flag and the additional information about Global Flags.

I can get it to work if they don't provide an arg by doing:

        if err := cobra.ExactArgs(1)(cmd, args); err != nil {
            fmt.Println(strings.Replace(cmd.UsageString(), "gbutil orders cancel [flags]", "gbutil orders cancel <order_id> [flags]", 1))
            return
        }

but then the -h flag outputs the wrong usage line still.

Is there a way to do this? Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dszsajhd237437 2019-02-10 14:50
    关注

    To change how usage name look. You can pass it in cobra.Command.Use parameter. So for you it probably will look like this:

    var cmdCancel = &cobra.Command{
        Use:   "cancel <order_id>",
        Args: cobra.ExactArgs(1), // make sure that only one arg can be passed
        // Your logic here
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用