github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/commands/version.go (about) 1 package commands 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7 8 "github.com/spf13/cobra" 9 "github.com/spf13/pflag" 10 11 "github.com/elek/golangci-lint/pkg/config" 12 ) 13 14 type jsonVersion struct { 15 Version string `json:"version"` 16 Commit string `json:"commit"` 17 Date string `json:"date"` 18 } 19 20 func (e *Executor) initVersionConfiguration(cmd *cobra.Command) { 21 fs := cmd.Flags() 22 fs.SortFlags = false // sort them as they are defined here 23 initVersionFlagSet(fs, e.cfg) 24 } 25 26 func initVersionFlagSet(fs *pflag.FlagSet, cfg *config.Config) { 27 // Version config 28 vc := &cfg.Version 29 fs.StringVar(&vc.Format, "format", "", wh("The version's format can be: 'short', 'json'")) 30 } 31 32 func (e *Executor) initVersion() { 33 versionCmd := &cobra.Command{ 34 Use: "version", 35 Short: "Version", 36 RunE: func(cmd *cobra.Command, _ []string) error { 37 switch strings.ToLower(e.cfg.Version.Format) { 38 case "short": 39 fmt.Println(e.version) 40 case "json": 41 ver := jsonVersion{ 42 Version: e.version, 43 Commit: e.commit, 44 Date: e.date, 45 } 46 data, err := json.Marshal(&ver) 47 if err != nil { 48 return err 49 } 50 fmt.Println(string(data)) 51 default: 52 fmt.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) 53 } 54 return nil 55 }, 56 } 57 58 e.rootCmd.AddCommand(versionCmd) 59 e.initVersionConfiguration(versionCmd) 60 }