Merge pull request #17102 from influxdata/sgc/cli

feat(cli): Extend flag support to pflag.Value types
pull/17108/head
Stuart Carnie 2020-03-05 08:58:08 -07:00 committed by GitHub
commit b686a30bd8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 0 deletions

View File

@ -150,6 +150,17 @@ func BindOptions(cmd *cobra.Command, opts []Opt) {
}
mustBindPFlag(o.Flag, flagset)
*destP = viper.GetStringSlice(envVar)
case pflag.Value:
if hasShort {
flagset.VarP(destP, o.Flag, string(o.Short), o.Desc)
} else {
flagset.Var(destP, o.Flag, o.Desc)
}
if o.Default != nil {
destP.Set(o.Default.(string))
}
mustBindPFlag(o.Flag, flagset)
destP.Set(viper.GetString(envVar))
default:
// if you get a panic here, sorry about that!
// anyway, go ahead and make a PR and add another type.

View File

@ -6,12 +6,36 @@ import (
"time"
)
type customFlag bool
func (c customFlag) String() string {
if c == true {
return "on"
}
return "off"
}
func (c *customFlag) Set(s string) error {
if s == "on" {
*c = true
} else {
*c = false
}
return nil
}
func (c *customFlag) Type() string {
return "fancy-bool"
}
func ExampleNewCommand() {
var monitorHost string
var number int
var sleep bool
var duration time.Duration
var stringSlice []string
var fancyBool customFlag
cmd := NewCommand(&Program{
Run: func() error {
fmt.Println(monitorHost)
@ -21,6 +45,7 @@ func ExampleNewCommand() {
fmt.Println(sleep)
fmt.Println(duration)
fmt.Println(stringSlice)
fmt.Println(fancyBool)
return nil
},
Name: "myprogram",
@ -55,6 +80,12 @@ func ExampleNewCommand() {
Default: []string{"foo", "bar"},
Desc: "things come in lists",
},
{
DestP: &fancyBool,
Flag: "fancy-bool",
Default: "on",
Desc: "things that implement pflag.Value",
},
},
})
@ -68,4 +99,5 @@ func ExampleNewCommand() {
// true
// 1m0s
// [foo bar]
// on
}