Cobra 库中是否有内置工具(如果有,我该如何使用它?)来要求标志是多个值之一,并在标志不是允许值之一时抛出错误?我没有在 Github 页面上看到这个。
最佳答案
Cobra 允许您通过 pflag.(*FlagSet).Var() 定义自定义值类型以用作标志。方法(来自 Cobra 使用的 https://github.com/spf13/pflag 包)。您必须创建一个实现 pflag.Value 的新类型接口(interface):
type Value interface {
String() string
Set(string) error
Type() string
}
示例类型定义:
type myEnum string
const (
myEnumFoo myEnum = "foo"
myEnumBar myEnum = "bar"
myEnumMoo myEnum = "moo"
)
// String is used both by fmt.Print and by Cobra in help text
func (e *myEnum) String() string {
return string(*e)
}
// Set must have pointer receiver so it doesn't change the value of a copy
func (e *myEnum) Set(v string) error {
switch v {
case "foo", "bar", "moo":
*e = myEnum(v)
return nil
default:
return errors.New(`must be one of "foo", "bar", or "moo"`)
}
}
// Type is only used in help text
func (e *myEnum) Type() string {
return "myEnum"
}
注册示例:
func init() {
var flagMyEnum = myEnumFoo
var myCmd = &cobra.Command{
Use: "mycmd",
Short: "A brief description of your command",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("myenum value:", flagMyEnum)
},
}
rootCmd.AddCommand(myCmd)
myCmd.Flags().Var(&flagMyEnum, "myenum", `my custom enum. allowed: "foo", "bar", "moo"`)
}
示例用法:(注意下面控制台输出中的第一行)
$ go run . mycmd --myenum raz
Error: invalid argument "raz" for "--myenum" flag: must be one of "foo", "bar", or "moo"
Usage:
main mycmd [flags]
Flags:
-h, --help help for mycmd
--myenum myEnum my custom enum. allowed: "foo", "bar", "moo" (default foo)
exit status 1
$ go run . mycmd --myenum bar
myenum value: bar
要为此添加自动完成功能,有点隐藏的文档页面 cobra/shell_completions.md#completions-for-flags有很大的帮助。对于我们的示例,您将添加如下内容:
func init() {
// ...
myCmd.Flags().Var(&flagMyEnum, "myenum", `my custom enum. allowed: "foo", "bar", "moo"`)
myCmd.RegisterFlagCompletionFunc("myenum", myEnumCompletion)
}
// myEnumCompletion should probably live next to the myEnum definition
func myEnumCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return []string{
"foo\thelp text for foo",
"bar\thelp text for bar",
"moo\thelp text for moo",
}, cobra.ShellCompDirectiveDefault
}
示例用法:
$ go build -o main .
$ source <(main completion bash)
$ main mycmd --myenum <TAB><TAB>
bar (help text for bar)
foo (help text for foo)
moo (help text for moo)
关于go - Cobra 允许的标志值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50824554/
我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_
我正在使用DMOZ的listofurltopics,其中包含一些具有包含下划线的主机名的url。例如:608609TheOuterHeaven610InformationandimagegalleryofMcFarlane'sactionfiguresforTrigun,Akira,TenchiMuyoandotherJapaneseSci-Fianimations.611Top/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures612虽然此url可以在网络浏览器中使用(或者至少在我的浏览器中可以使用:
我想将“US”之类的国家代码转换为表情符号标志,即将“US”字符串转换为Ruby中适当的Unicode。Here'sanequivalentexampleforJava 最佳答案 使用tr将字母字符转换为其区域指示符号:'US'.tr('A-Z',"\u{1F1E6}-\u{1F1FF}")#=>"??"当然你也可以直接使用Unicode字符:'US'.tr('A-Z','?-?')#=>"??" 关于ruby-从Ruby中的国家代码获取表情符号标志,我们在StackOverflow上找
我读过这个:Let’sstartwithasimpleRubyprogram.We’llwriteamethodthatreturnsacheery,personalizedgreeting.defsay_goodnight(name)result="Goodnight,"+namereturnresultend我的理解是,方法是定义在类中的函数或子程序,可以关联到类(类方法)或对象(实例方法)。那么,如果它不是在类中定义的,怎么可能是方法呢? 最佳答案 当你在Ruby中以这种方式在全局范围内定义一个函数时,它在技术上变成了Obje
在Railcasts上,我注意到一个非常有趣的功能“转到符号”窗口。它像Command-T一样工作,但显示当前文件中可用的类和方法。如何在vim中获取它? 最佳答案 尝试:helptags有各种程序和脚本可以生成标记文件。此外,标记文件格式非常简单,因此很容易将sed(1)或类似的脚本组合在一起,无论您使用何种语言,它们都可以生成标记文件。轻松获取标记文件(除了下载生成器之外)的关键在于格式化样式而不是实际解析语法。 关于ruby-on-rails-Textmate'Gotosymbol
在DavidFlanagan的TheRubyProgrammingLanguage中;松本幸弘theystatethatthevariableprefixes($,@,@@)areonepricewepayforbeingabletoomitparenthesesaroundmethodinvocations.谁可以给我解释一下这个? 最佳答案 这是我不成熟的意见。如果我错了,请纠正我。假设实例变量没有@前缀,那么我们如何声明一个实例变量?classMyClassdefinitialize#Herefooisaninstanceva
#!/usr/bin/envrubyrequire'optparse'options={}OptionParser.newdo|opts|opts.on("--languageLANGUAGE",["Ruby","JavaScript"])do|language|options[:language]=languageendend.parse!puts"Language:#{options[:language]}"如果我用./bin/example--languageRu运行它,它将输出:Language:Ruby我想禁用此自动完成/最接近的匹配行为,并在未提供确切名称时引发Option
我已经设法制作了一个仅用于注册和登录的应用程序。目前,我允许用户通过邮件帐户激活(按照本教程:https://www.railstutorial.org/book/account_activation_password_reset和“railsgeneratecontrollerAccountActivations--no-test-framework')但我希望管理员能够激活或停用用户。在我的用户模型中,我设法定义了两种方法:defactivate_account!update_attribute:is_active,trueenddefdeactivate_account!upda
我正在制作一个应用程序,我需要用户使用所见即所得的编辑器输入描述。我不能信任用户输入,所以我只需要允许a、em、ul、li标签。我如何轻松剥离其他的? 最佳答案 https://github.com/rgrove/sanitize/ 关于ruby-on-rails-允许用户只输入特定的标签,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7390075/
如何在我的模型中验证:title以便只接受字母a-z、A-z和0-9?validates:title,:format=>{with:REGULAREXPRESSION,:message=>'nospecialcharacters,onlylettersandnumbers'}正则表达式应该是什么? 最佳答案 正则表达式为/^[a-zA-Z0-9]*$/您基本上定义了三个允许的符号范围,首先是a-z,然后是A-Z,最后是0-9。最后的星号定义需要匹配零个或多个前面所述的字符,这意味着允许使用空标题。如果您需要至少一个字符,请使用+而不