cmd.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2017 The Xorm Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import (
  6. "fmt"
  7. "os"
  8. "strings"
  9. )
  10. // A Command is an implementation of a go command
  11. // like go build or go fix.
  12. type Command struct {
  13. // Run runs the command.
  14. // The args are the arguments after the command name.
  15. Run func(cmd *Command, args []string)
  16. // UsageLine is the one-line usage message.
  17. // The first word in the line is taken to be the command name.
  18. UsageLine string
  19. // Short is the short description shown in the 'go help' output.
  20. Short string
  21. // Long is the long message shown in the 'go help <this-command>' output.
  22. Long string
  23. // Flag is a set of flags specific to this command.
  24. Flags map[string]bool
  25. }
  26. // Name returns the command's name: the first word in the usage line.
  27. func (c *Command) Name() string {
  28. name := c.UsageLine
  29. i := strings.Index(name, " ")
  30. if i >= 0 {
  31. name = name[:i]
  32. }
  33. return name
  34. }
  35. func (c *Command) Usage() {
  36. fmt.Fprintf(os.Stderr, "usage: %s\n\n", c.UsageLine)
  37. fmt.Fprintf(os.Stderr, "%s\n", strings.TrimSpace(c.Long))
  38. os.Exit(2)
  39. }
  40. // Runnable reports whether the command can be run; otherwise
  41. // it is a documentation pseudo-command such as importpath.
  42. func (c *Command) Runnable() bool {
  43. return c.Run != nil
  44. }
  45. // checkFlags checks if the flag exists with correct format.
  46. func checkFlags(flags map[string]bool, args []string, print func(string)) int {
  47. num := 0 // Number of valid flags, use to cut out.
  48. for i, f := range args {
  49. // Check flag prefix '-'.
  50. if !strings.HasPrefix(f, "-") {
  51. // Not a flag, finish check process.
  52. break
  53. }
  54. // Check if it a valid flag.
  55. if v, ok := flags[f]; ok {
  56. flags[f] = !v
  57. if !v {
  58. print(f)
  59. } else {
  60. fmt.Println("DISABLE: " + f)
  61. }
  62. } else {
  63. fmt.Printf("[ERRO] Unknown flag: %s.\n", f)
  64. return -1
  65. }
  66. num = i + 1
  67. }
  68. return num
  69. }