bool_func.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package pflag
  2. // -- func Value
  3. type boolfuncValue func(string) error
  4. func (f boolfuncValue) Set(s string) error { return f(s) }
  5. func (f boolfuncValue) Type() string { return "boolfunc" }
  6. func (f boolfuncValue) String() string { return "" } // same behavior as stdlib 'flag' package
  7. func (f boolfuncValue) IsBoolFlag() bool { return true }
  8. // BoolFunc defines a func flag with specified name, callback function and usage string.
  9. //
  10. // The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed
  11. // on the command line.
  12. func (f *FlagSet) BoolFunc(name string, usage string, fn func(string) error) {
  13. f.BoolFuncP(name, "", usage, fn)
  14. }
  15. // BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash.
  16. func (f *FlagSet) BoolFuncP(name, shorthand string, usage string, fn func(string) error) {
  17. var val Value = boolfuncValue(fn)
  18. flag := f.VarPF(val, name, shorthand, usage)
  19. flag.NoOptDefVal = "true"
  20. }
  21. // BoolFunc defines a func flag with specified name, callback function and usage string.
  22. //
  23. // The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed
  24. // on the command line.
  25. func BoolFunc(name string, usage string, fn func(string) error) {
  26. CommandLine.BoolFuncP(name, "", usage, fn)
  27. }
  28. // BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash.
  29. func BoolFuncP(name, shorthand string, usage string, fn func(string) error) {
  30. CommandLine.BoolFuncP(name, shorthand, usage, fn)
  31. }