gpt4 book ai didi

go - Cobra 更改帮助模板中的用法行

转载 作者:IT王子 更新时间:2023-10-29 01:37:42 24 4
gpt4 key购买 nike

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

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

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)

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

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 标志仍然输出错误的用法行。

有没有办法做到这一点?提前致谢!

最佳答案

更改用法名称的外观。您可以在 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
}

关于go - Cobra 更改帮助模板中的用法行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54584221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com