utils.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package cli
  2. import (
  3. "errors"
  4. "flag"
  5. "fmt"
  6. "io"
  7. )
  8. type GlobalOpts struct {
  9. ConfigPath string
  10. Debug bool
  11. ConfigStanza string
  12. }
  13. func (o GlobalOpts) String() string {
  14. return "--config --debug --account"
  15. }
  16. type Command interface {
  17. Func([]string) error
  18. Help(io.Writer, *flag.FlagSet)
  19. }
  20. type CommandMap map[string]Command
  21. type ProgramInfo struct {
  22. Name string
  23. Opts GlobalOpts
  24. Commands CommandMap
  25. }
  26. func Usage(w io.Writer, info ProgramInfo) {
  27. fmt.Fprintf(w, "USAGE: %s [%s] SUBCOMMAND [subcommand opts]\n", info.Name, info.Opts)
  28. fmt.Fprintf(w, "\nSUBCOMMANDS:\n")
  29. for command := range info.Commands {
  30. fmt.Fprintf(w, "\t%s\n", command)
  31. }
  32. }
  33. type Pair struct {
  34. Set, Unset bool
  35. }
  36. type PairFlag struct {
  37. *Pair
  38. }
  39. func NewPairFlag() PairFlag {
  40. return PairFlag{
  41. &Pair{false, false},
  42. }
  43. }
  44. func (p Pair) String() string {
  45. switch p {
  46. case Pair{true, false}:
  47. return "set"
  48. case Pair{false, true}:
  49. return "unset"
  50. default:
  51. return "undef"
  52. }
  53. }
  54. func (pf PairFlag) String() string {
  55. return fmt.Sprint(pf.Pair)
  56. }
  57. func (pf PairFlag) Set(s string) error {
  58. if s == "set" {
  59. v := Pair{true, false}
  60. *pf.Pair = v
  61. return nil
  62. }
  63. if s == "unset" {
  64. v := Pair{false, true}
  65. *pf.Pair = v
  66. return nil
  67. }
  68. return ErrAllowedPairFlagValues
  69. }
  70. var ErrAllowedPairFlagValues = errors.New("only `set` or `unset` are allowed")