英文:
Determine if flags were actually passed in (sub)command invocation in golang's cobra/viper
问题
我有一个cobra
命令:
var mycommandCmd = &cobra.Command{
Use: "mycommand",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
viper.BindPFlags(cmd.Flags())
还有一个子命令:
var mysubcommandCmd = &cobra.Command{
Use: "mysubcommand",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
viper.BindPFlags(cmd.Flags())
当然,我将它们绑定在一起:
mycommandCmd.AddCommand(mysubcommandCmd)
我还为它们设置了一些标志:
mycommandCmd.PersistentFlags().BoolP("foo", "", true, "Whether to foo")
mysubcommandCmd.Flags().BoolP("foobar", "", true, "Whether to foobar")
我的问题是:
假设最终的go
二进制文件名为prog
,是否有一种(cobra
/ viper
)内置的方法来检查在调用子命令时是否传递了任何标志?
也就是说,我如何以编程方式区分这两种情况:
prog mycommand mysubcommand --foobar
和
prog mycommand mysubcommand
当然,检查默认标志值是行不通的(而且在标志数量上不可扩展)。
英文:
I have a cobra
command
var mycommandCmd = &cobra.Command{
Use: "mycommand",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
viper.BindPFlags(cmd.Flags())
and a subcommand
var mysubcommandCmd = &cobra.Command{
Use: "mysubcommand",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
viper.BindPFlags(cmd.Flags())
which I of course bind together
mycommandCmd.AddCommand(mysubcommandCmd)
I also have some flags for both of them
mycommandCmd.PersistentFlags().BoolP("foo", "", true, "Whether to foo")
mysubcommandCmd.Flags().BoolP("foobar", "", true, "Whether to foobar")
My question is the following:
Assuming the end go
binary is named prog
, is there a (cobra
/ viper
) built in way of checking of whether any flags were actually passed during subcommand invocation?
i.e. how can I programmatically distinguish between this
prog mycommand mysubcommand --foobar
and this
prog mycommand mysubcommand
Checking against the default flag values will not work of course (and does not scale against the flag number)
答案1
得分: 2
你可以这样做:
isSet := cmd.Flags().Lookup("foobar").Changed
这将返回标志是否被设置,或者是否使用了默认值。
英文:
You can do:
isSet:=cmd.Flags().Lookup("foobar").Changed
That should return if the flag was set, or if the default value was used.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论