diff options
Diffstat (limited to 'src/flag/flag.go')
-rw-r--r-- | src/flag/flag.go | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/src/flag/flag.go b/src/flag/flag.go index 286bba6873..a8485f034f 100644 --- a/src/flag/flag.go +++ b/src/flag/flag.go @@ -278,6 +278,12 @@ func (d *durationValue) Get() interface{} { return time.Duration(*d) } func (d *durationValue) String() string { return (*time.Duration)(d).String() } +type funcValue func(string) error + +func (f funcValue) Set(s string) error { return f(s) } + +func (f funcValue) String() string { return "" } + // Value is the interface to the dynamic value stored in a flag. // (The default value is represented as a string.) // @@ -296,7 +302,7 @@ type Value interface { // Getter is an interface that allows the contents of a Value to be retrieved. // It wraps the Value interface, rather than being part of it, because it // appeared after Go 1 and its compatibility rules. All Value types provided -// by this package satisfy the Getter interface. +// by this package satisfy the Getter interface, except the type used by Func. type Getter interface { Value Get() interface{} @@ -830,6 +836,20 @@ func Duration(name string, value time.Duration, usage string) *time.Duration { return CommandLine.Duration(name, value, usage) } +// Func defines a flag with the specified name and usage string. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func (f *FlagSet) Func(name, usage string, fn func(string) error) { + f.Var(funcValue(fn), name, usage) +} + +// Func defines a flag with the specified name and usage string. +// Each time the flag is seen, fn is called with the value of the flag. +// If fn returns a non-nil error, it will be treated as a flag value parsing error. +func Func(name, usage string, fn func(string) error) { + CommandLine.Func(name, usage, fn) +} + // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the |