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.
Set the
Use
field for your command to :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