diff --git a/kit/cli/viper.go b/kit/cli/viper.go index 2d453a51b2..621ed89aad 100644 --- a/kit/cli/viper.go +++ b/kit/cli/viper.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + "time" ) // Opt is a single command-line option @@ -72,6 +73,20 @@ func NewCommand(p *Program) *cobra.Command { cmd.Flags().IntVar(o.DestP.(*int), o.Flag, o.Default.(int), o.Desc) viper.BindPFlag(o.Flag, cmd.Flags().Lookup(o.Flag)) *o.DestP.(*int) = viper.GetInt(o.Flag) + case *bool: + if o.Default == nil { + o.Default = false + } + cmd.Flags().BoolVar(o.DestP.(*bool), o.Flag, o.Default.(bool), o.Desc) + viper.BindPFlag(o.Flag, cmd.Flags().Lookup(o.Flag)) + *o.DestP.(*bool) = viper.GetBool(o.Flag) + case *time.Duration: + if o.Default == nil { + o.Default = time.Duration(0) + } + cmd.Flags().DurationVar(o.DestP.(*time.Duration), o.Flag, o.Default.(time.Duration), o.Desc) + viper.BindPFlag(o.Flag, cmd.Flags().Lookup(o.Flag)) + *o.DestP.(*time.Duration) = viper.GetDuration(o.Flag) default: // if you get a panic here, sorry about that! // anyway, go ahead and make a PR and add another type. diff --git a/kit/cli/viper_test.go b/kit/cli/viper_test.go index 2061f563c8..2526d8fdde 100644 --- a/kit/cli/viper_test.go +++ b/kit/cli/viper_test.go @@ -3,17 +3,22 @@ package cli import ( "fmt" "os" + "time" ) func ExampleNewCommand() { var monitorHost string var number int + var sleep bool + var duration time.Duration cmd := NewCommand(&Program{ Run: func() error { fmt.Println(monitorHost) for i := 0; i < number; i++ { fmt.Printf("%d\n", i) } + fmt.Println(sleep) + fmt.Println(duration) return nil }, Name: "myprogram", @@ -30,6 +35,18 @@ func ExampleNewCommand() { Default: 2, Desc: "number of times to loop", }, + { + DestP: &sleep, + Flag: "sleep", + Default: true, + Desc: "whether to sleep", + }, + { + DestP: &duration, + Flag: "duration", + Default: time.Minute, + Desc: "how long to sleep", + }, }, }) @@ -40,4 +57,6 @@ func ExampleNewCommand() { // http://localhost:8086 // 0 // 1 + // true + // 1m0s }