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
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?