verflag.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package version
  2. import (
  3. "fmt"
  4. "github.com/spf13/pflag"
  5. "os"
  6. "strconv"
  7. )
  8. type versionValue int
  9. const (
  10. VersionFalse versionValue = 0
  11. VersionTrue versionValue = 1
  12. VersionRaw versionValue = 2
  13. )
  14. const strRawVersion string = "raw"
  15. func (v *versionValue) IsBoolFlag() bool {
  16. return true
  17. }
  18. func (v *versionValue) Get() interface{} {
  19. return v
  20. }
  21. func (v *versionValue) Set(s string) error {
  22. if s == strRawVersion {
  23. *v = VersionRaw
  24. return nil
  25. }
  26. boolVal, err := strconv.ParseBool(s)
  27. if boolVal {
  28. *v = VersionTrue
  29. } else {
  30. *v = VersionFalse
  31. }
  32. return err
  33. }
  34. func (v *versionValue) String() string {
  35. if *v == VersionRaw {
  36. return strRawVersion
  37. }
  38. return fmt.Sprintf("%v", bool(*v == VersionTrue))
  39. }
  40. func (v *versionValue) Type() string {
  41. return "version"
  42. }
  43. func VersionVar(p *versionValue, name string, value versionValue, usage string) {
  44. *p = value
  45. pflag.Var(p, name, usage)
  46. // "--version" will be treated as "--version=true"
  47. pflag.Lookup(name).NoOptDefVal = "true"
  48. }
  49. // Version wraps the VersionVar function.
  50. func Version(name string, value versionValue, usage string) *versionValue {
  51. p := new(versionValue)
  52. VersionVar(p, name, value, usage)
  53. return p
  54. }
  55. const versionFlagName = "version"
  56. var versionFlag = Version(versionFlagName, VersionFalse, "Print version information and quit.")
  57. // AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the
  58. // same value as the global flags.
  59. func AddFlags(fs *pflag.FlagSet) {
  60. fs.AddFlag(pflag.Lookup(versionFlagName))
  61. }
  62. // PrintAndExitIfRequested will check if the -version flag was passed
  63. // and, if so, print the version and exit.
  64. func PrintAndExitIfRequested() {
  65. if *versionFlag == VersionRaw {
  66. fmt.Printf("%#v\n", Get())
  67. os.Exit(0)
  68. } else if *versionFlag == VersionTrue {
  69. fmt.Printf("%s\n", Get())
  70. os.Exit(0)
  71. }
  72. }