flags.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
  2. // Use of this source code is governed by the MIT-license that can be
  3. // found in the LICENSE file.
  4. package main
  5. import (
  6. "fmt"
  7. "os"
  8. "strings"
  9. "github.com/spf13/pflag"
  10. )
  11. var ErrNoCmd = fmt.Errorf("No CMD")
  12. type Command struct {
  13. Str string
  14. Aliases []string
  15. Desc string
  16. HandleFunc func(args []string)
  17. Usage string
  18. Options map[string]string
  19. Example string
  20. LongLived bool
  21. MayConnect bool
  22. }
  23. func (cmd Command) PrintUsage() {
  24. fmt.Fprintf(os.Stderr, "%s - %s\n", cmd.Str, cmd.Desc)
  25. fmt.Fprintf(os.Stderr, "\nUsage:\n %s %s\n", cmd.Str, strings.TrimSpace(cmd.Usage))
  26. if len(cmd.Options) > 0 {
  27. fmt.Fprint(os.Stderr, "\nOptions:\n")
  28. for f, desc := range cmd.Options {
  29. fmt.Fprintf(os.Stderr, " %-17s %s\n", f, desc)
  30. }
  31. }
  32. if cmd.Example != "" {
  33. fmt.Fprintf(os.Stderr, "\nExample:\n %s\n", strings.TrimSpace(cmd.Example))
  34. }
  35. fmt.Fprint(os.Stderr, "\n")
  36. }
  37. func parseFlags(args []string) (cmd Command, arguments []string) {
  38. var options []string
  39. var err error
  40. cmd, options, arguments, err = findCommand(args)
  41. if err != nil {
  42. pflag.Usage()
  43. os.Exit(1)
  44. }
  45. optionsSet().Parse(options)
  46. if len(arguments) == 0 {
  47. arguments = append(arguments, "")
  48. }
  49. switch arguments[0] {
  50. case "--help", "-help", "help", "-h":
  51. cmd.PrintUsage()
  52. os.Exit(1)
  53. }
  54. return
  55. }
  56. func findCommand(args []string) (cmd Command, pre, post []string, err error) {
  57. cmdMap := make(map[string]Command, len(commands))
  58. for _, c := range commands {
  59. cmdMap[c.Str] = c
  60. for _, alias := range c.Aliases {
  61. cmdMap[alias] = c
  62. }
  63. }
  64. for i, arg := range args {
  65. if cmd, ok := cmdMap[arg]; ok {
  66. return cmd, args[1:i], args[i+1:], nil
  67. }
  68. }
  69. err = ErrNoCmd
  70. return
  71. }