func.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package pflag
  2. // -- func Value
  3. type funcValue func(string) error
  4. func (f funcValue) Set(s string) error { return f(s) }
  5. func (f funcValue) Type() string { return "func" }
  6. func (f funcValue) String() string { return "" } // same behavior as stdlib 'flag' package
  7. // Func defines a func flag with specified name, callback function and usage string.
  8. //
  9. // The callback function will be called every time "--{name}={value}" (or equivalent) is
  10. // parsed on the command line, with "{value}" as an argument.
  11. func (f *FlagSet) Func(name string, usage string, fn func(string) error) {
  12. f.FuncP(name, "", usage, fn)
  13. }
  14. // FuncP is like Func, but accepts a shorthand letter that can be used after a single dash.
  15. func (f *FlagSet) FuncP(name string, shorthand string, usage string, fn func(string) error) {
  16. var val Value = funcValue(fn)
  17. f.VarP(val, name, shorthand, usage)
  18. }
  19. // Func defines a func flag with specified name, callback function and usage string.
  20. //
  21. // The callback function will be called every time "--{name}={value}" (or equivalent) is
  22. // parsed on the command line, with "{value}" as an argument.
  23. func Func(name string, usage string, fn func(string) error) {
  24. CommandLine.FuncP(name, "", usage, fn)
  25. }
  26. // FuncP is like Func, but accepts a shorthand letter that can be used after a single dash.
  27. func FuncP(name, shorthand string, usage string, fn func(string) error) {
  28. CommandLine.FuncP(name, shorthand, usage, fn)
  29. }