[英]cobra failing to mark flag as required
I have the following flag addition in a cobra.Cmd
我在眼镜蛇中添加了以下标志
cobra.Cmd
myCmd.PersistentFlags().StringP(applicationLongFlag, applicationShortFlag, applicationDefaultValue, applicationFlagHelpMsg)
Where在哪里
applicationLongFlag = "application"
applicationShortFlag = "a"
applicationDefaultValue = ""
applicationFlagHelpMsg = "The application name"
This works as expected, however when trying to make the above flag as required the process fails这可以按预期工作,但是当尝试根据需要制作上述标志时,该过程会失败
if err := myCmd.MarkFlagRequired(applicationShortFlag); err != nil {
return errors.Wrapf(err, "error marking %s as required flag", applicationShortFlag)
}
error marking a as required flag: no such flag -a
-a
/ --application
works as expected and it is also printed in my help -a
/ --application
按预期工作,它也打印在我的帮助中
▶ go run myprog.go mycommand --help
Usage:
myprog.go mycommand [flags]
Flags:
-a, --application string The application name
Why is it failing to be set as required?为什么没有按要求设置?
I think you should use MarkPersistentFlagRequired
instead of MarkFlagRequired
as you are trying to mark a persistent flag.我认为您在尝试标记持久标志时应该使用
MarkPersistentFlagRequired
而不是MarkFlagRequired
。 You can only use name
of the flag and not the shorthand
.您只能使用标志的
name
而不是shorthand
。
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
rootCmd := &cobra.Command{
Use: "root",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Mark using `MarkPersistentFlagRequired` ")
},
}
rootCmd.PersistentFlags().StringP("test", "t", "", "test required")
// Change this
if err := rootCmd.MarkPersistentFlagRequired("test"); err != nil {
fmt.Println(err.Error())
return
}
rootCmd.Execute()
}
⇒ go run main.go
Error: required flag(s) "test" not set
Usage:
root [flags]
Flags:
-h, --help help for root
-t, --test string test required
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.