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

时间:2019-02-08 00:03:18

标签: go command-line go-cobra

我希望能够设置Usage行以指定如果在Go中的cobra命令上调用了帮助功能,则需要传递参数NEEDS。

这是常规帮助标志的输出:

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)

我想要:

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)

我尝试在SetUsageTemplate函数中使用init(),但随后删除了部分标志:

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

结果是:

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标志和有关Global Flags的其他信息。

如果他们没有提供arg,我可以使它工作:

        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
        }

,但是-h标志仍然输出错误的用法行。

有没有办法做到这一点?预先感谢!

1 个答案:

答案 0 :(得分:1)

更改用法名称的外观。您可以在cobra.Command.Use参数中传递它。所以对您来说,它可能看起来像这样:

var cmdCancel = &cobra.Command{
    Use:   "cancel <order_id>",
    Args: cobra.ExactArgs(1), // make sure that only one arg can be passed
    // Your logic here
}