Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cobra change usage line in help template

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!

like image 434
Robert M. Avatar asked Feb 08 '19 00:02

Robert M.


1 Answers

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
} 
like image 197
ttomalak Avatar answered Nov 03 '22 09:11

ttomalak