我有以下Cobra子命令:
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))
}
这个想法是通过./my-app stripe customers delete -k $STRIPE_API_KEY $CUSTOMER_ID_1 $CUSTOMER_ID_2
调用它。
虽然cobra.MinimumNArgs(1)
确实确保我至少得到一个位置参数,但我找不到一种在帮助文档中显示这一点的方法:
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
有没有办法告诉Cobra在帮助中显示位置参数,比如:
Usage:
my-app stripe customers delete [flags] customer_id [...customer_id]
现在帮助文档在向用户显示他们应该作为位置参数传递的内容方面不是很有帮助。
设置命令的Use
字段为:
deleteCustomerCommand = &cobra.Command{
Use: "delete [flags] customer_id [...customer_id]",
...
关于如何使用它的完整细节可以在cmd.UseLine()
的代码中找到:
https://github.com/spf13/cobra/blob/v1.2.1/command.go#L1245