Named Positional Arguments in Cobra

7.7k Views Asked by At

I have the following Cobra sub-command:

package stripeCommands

import (
    "fmt"
    "cmd/cliConstants"
    "github.com/spf13/cobra"
    "log"
)

var (
    deleteCustomerCommand = &cobra.Command{
        Use:        "delete",
        Short:      "Delete Stripe customer(s) by ids.",
        Args:       cobra.MinimumNArgs(1),
        ArgAliases: []string{"stripe_customer_id"},
        PreRun: func(cmd *cobra.Command, args []string) {

        },
        Run: func(cmd *cobra.Command, args []string) {
            log.Printf("IDs: %v", args)
        },
    }
)

func init() {
    flags := deleteCustomerCommand.Flags()

    // -k|--stripe-api-key|STRIPE_API_KEY
    flags.StringP(cliConstants.CLIFlagStripeAPIKey, "k", "",
        fmt.Sprintf("The Stripe API key. [env: %s]", cliConstants.EnvVarStripeAPIKey))
}

The idea is to call this via ./my-app stripe customers delete -k $STRIPE_API_KEY $CUSTOMER_ID_1 $CUSTOMER_ID_2.

While cobra.MinimumNArgs(1) does ensure I get at least one positional argument, I can't find a way to make this show up in the help documentation:

Error: requires at least 1 arg(s), only received 0
Usage:
  my-app stripe customers delete [flags]

Flags:
  -h, --help                    help for delete
  -k, --stripe-api-key string   The Stripe API key. [env: stripe_api_key]

2021/09/13 12:00:39 Failed to execute command: requires at least 1 arg(s), only received 0

Is there a way to tell Cobra to display positional args in the help like:

Usage:
  my-app stripe customers delete [flags] customer_id [...customer_id]

Right now the help documentation is not very helpful in displaying to the user what they should pass as positional arguments.

1

There are 1 best solutions below

0
On

Set the Use field for your command to :

    deleteCustomerCommand = &cobra.Command{
        Use: "delete [flags] customer_id [...customer_id]",
        ...

The complete details of how it is used can be found in the code for cmd.UseLine() :
https://github.com/spf13/cobra/blob/v1.2.1/command.go#L1245