From 8f20f9e44d9799cc2b51bfb2f6ab857f492aa27d Mon Sep 17 00:00:00 2001 From: Filipe Brandenburger Date: Fri, 16 Jan 2015 10:43:36 -0800 Subject: Add support for custom boolean flags through IsBoolFlag() This is consistent with Go's native flag parsing module and can be used to implement custom boolean/tri-state flags. Signed-off-by: Filipe Brandenburger --- bool.go | 9 +++++++++ flag.go | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/bool.go b/bool.go index 60beb54..617971a 100644 --- a/bool.go +++ b/bool.go @@ -5,6 +5,13 @@ import ( "strconv" ) +// optional interface to indicate boolean flags that can be +// supplied without "=value" text +type boolFlag interface { + Value + IsBoolFlag() bool +} + // -- bool Value type boolValue bool @@ -21,6 +28,8 @@ func (b *boolValue) Set(s string) error { func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) } +func (b *boolValue) IsBoolFlag() bool { return true } + // BoolVar defines a bool flag with specified name, default value, and usage string. // The argument p points to a bool variable in which to store the value of the flag. func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { diff --git a/flag.go b/flag.go index 1e574d7..f383058 100644 --- a/flag.go +++ b/flag.go @@ -438,7 +438,7 @@ func (f *FlagSet) parseArgs(args []string) error { return f.failf("unknown flag: --%s", name) } if len(split) == 1 { - if _, ok := flag.Value.(*boolValue); !ok { + if bv, ok := flag.Value.(boolFlag); !ok || !bv.IsBoolFlag() { return f.failf("flag needs an argument: %s", s) } f.setFlag(flag, "true", s) @@ -459,7 +459,7 @@ func (f *FlagSet) parseArgs(args []string) error { } return f.failf("unknown shorthand flag: %q in -%s", c, shorthands) } - if _, ok := flag.Value.(*boolValue); ok { + if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() { f.setFlag(flag, "true", s) continue } -- cgit v1.2.3