github.com/searKing/golang/go@v1.2.117/version/verflag/verflag.go (about) 1 // Copyright 2021 The searKing Author. 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 5 // Package verflag defines utility functions to handle command line flags 6 // related to version. 7 package verflag 8 9 import ( 10 "flag" 11 "fmt" 12 "os" 13 "strconv" 14 15 "github.com/searKing/golang/go/version" 16 ) 17 18 type versionValue int 19 20 const ( 21 VersionFalse versionValue = 0 22 VersionTrue versionValue = 1 23 VersionRaw versionValue = 2 24 ) 25 26 const strRawVersion string = "raw" 27 28 func (v *versionValue) IsBoolFlag() bool { 29 return true 30 } 31 32 func (v *versionValue) Get() any { 33 return versionValue(*v) 34 } 35 36 func (v *versionValue) Set(s string) error { 37 if s == strRawVersion { 38 *v = VersionRaw 39 return nil 40 } 41 boolVal, err := strconv.ParseBool(s) 42 if boolVal { 43 *v = VersionTrue 44 } else { 45 *v = VersionFalse 46 } 47 return err 48 } 49 50 func (v *versionValue) String() string { 51 if *v == VersionRaw { 52 return strRawVersion 53 } 54 return fmt.Sprintf("%v", bool(*v == VersionTrue)) 55 } 56 57 // Type The type of the flag as required by the pflag.Value interface 58 func (v *versionValue) Type() string { 59 return "version" 60 } 61 62 func VersionVar(p *versionValue, name string, value versionValue, usage string) { 63 *p = value 64 flag.Var(p, name, usage) 65 // "--version" will be treated as "--version=true" 66 flag.Lookup(name).DefValue = "true" 67 } 68 69 func Version(name string, value versionValue, usage string) *versionValue { 70 p := new(versionValue) 71 VersionVar(p, name, value, usage) 72 return p 73 } 74 75 const versionFlagName = "version" 76 77 var ( 78 versionFlag = Version(versionFlagName, VersionFalse, "Print version information and quit") 79 ) 80 81 // AddFlags registers this package's flags on arbitrary FlagSets, such that they point to the 82 // same value as the global flags. 83 func AddFlags(fs *flag.FlagSet) { 84 fs.Var(versionFlag, versionFlagName, "Print version information and quit") 85 } 86 87 // PrintAndExitIfRequested will check if the -version flag was passed 88 // and, if so, print the version and exit. 89 func PrintAndExitIfRequested() { 90 if *versionFlag == VersionRaw { 91 fmt.Printf("%#v\n", version.Get()) 92 os.Exit(0) 93 } else if *versionFlag == VersionTrue { 94 fmt.Printf("%s %s\n", version.ServiceName, version.Get()) 95 os.Exit(0) 96 } 97 }