github.com/puellanivis/breton@v0.2.16/lib/gnuflag/funcs.go (about) 1 package gnuflag 2 3 // setterFunc describes a function that takes a string from the command-line and performs some function that returns an error state. 4 type setterFunc func(string) error 5 6 // FuncValue describes a flag which will call a func(string) error when specified as a flag. 7 type funcValue struct { 8 name, value string 9 isBool bool 10 11 f setterFunc 12 } 13 14 // newBoolFunc returns a FuncValue that acts as a boolean flag. 15 func newBoolFunc(name string, fn func()) *funcValue { 16 return &funcValue{ 17 name: name, 18 isBool: true, 19 f: func(s string) error { fn(); return nil }, 20 } 21 } 22 23 // newFunc returns a FuncValue that acts as a normal flag. 24 func newFunc(name string, fn func(string) error) *funcValue { 25 return &funcValue{ 26 name: name, 27 isBool: false, 28 f: fn, 29 } 30 } 31 32 // String returns the last value that was `Set()` on this flag. 33 func (f *funcValue) String() string { 34 return f.value 35 } 36 37 // Set calls the function of the FuncValue and returns its error. 38 func (f *funcValue) Set(s string) error { 39 f.value = s 40 return f.f(s) 41 } 42 43 // Get returns the underlying `func(string) error` function. 44 func (f *funcValue) Get() interface{} { 45 return f.f 46 } 47 48 // IsBoolFlag implements the test for if a flag should act as a boolean flag. 49 func (f *funcValue) IsBoolFlag() bool { 50 return f.isBool 51 } 52 53 // BoolFunc defines a function flag with specified name, and usage string. 54 // It returns a pointer to the niladic function. 55 func (f *FlagSet) BoolFunc(name, usage string, value func(), options ...Option) func() { 56 fn := newBoolFunc(name, value) 57 if err := f.Var(fn, name, usage, options...); err != nil { 58 panic(err) 59 } 60 return value 61 } 62 63 // Func defines a function flag with specified name, and usage string. 64 // It returns a pointer to the SetterFunc. 65 func (f *FlagSet) Func(name, usage string, value func(string) error, options ...Option) func(string) error { 66 fn := newFunc(name, value) 67 if err := f.Var(fn, name, usage, options...); err != nil { 68 panic(err) 69 } 70 return value 71 } 72 73 // BoolFunc defines a function flag with specified name, and usage string. 74 // It returns a pointer to the niladic function. 75 func BoolFunc(name, usage string, value func(), options ...Option) func() { 76 return CommandLine.BoolFunc(name, usage, value, options...) 77 } 78 79 // Func defines a function flag with specified name, shortname, and usage string. 80 // It returns a pointer to the SetterFunc. 81 func Func(name, usage string, value func(string) error, options ...Option) func(string) error { 82 return CommandLine.Func(name, usage, value, options...) 83 }