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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器