Merge pull request #783 from influxdata/jgm-viper-bool
kit/cli: Add boolean and duration flag typespull/10616/head
commit
37c8fbcd37
|
@ -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.
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue