diff --git a/pkg/commands/run.go b/pkg/commands/run.go index 92f0b175..3cd4381c 100644 --- a/pkg/commands/run.go +++ b/pkg/commands/run.go @@ -234,6 +234,7 @@ func (e *Executor) getConfigForCommandLine() (*config.Config, error) { // Use another config variable here, not e.cfg, to not // affect main parsing by this parsing of only config option. initFlagSet(fs, &cfg, e.DBManager, false) + initVersionFlagSet(fs, &cfg) // Parse max options, even force version option: don't want // to get access to Executor here: it's error-prone to use diff --git a/pkg/commands/version.go b/pkg/commands/version.go index fdb5aa88..3918d6b7 100644 --- a/pkg/commands/version.go +++ b/pkg/commands/version.go @@ -1,17 +1,59 @@ package commands import ( + "encoding/json" + "strings" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/golangci/golangci-lint/pkg/config" ) +type jsonVersion struct { + Version string `json:"version"` + Commit string `json:"commit"` + Date string `json:"date"` +} + +func (e *Executor) initVersionConfiguration(cmd *cobra.Command) { + fs := cmd.Flags() + fs.SortFlags = false // sort them as they are defined here + initVersionFlagSet(fs, e.cfg) +} + +func initVersionFlagSet(fs *pflag.FlagSet, cfg *config.Config) { + // Version config + vc := &cfg.Version + fs.StringVar(&vc.Format, "format", "", wh("The version's format can be: 'short', 'json'")) +} + func (e *Executor) initVersion() { versionCmd := &cobra.Command{ Use: "version", Short: "Version", - Run: func(cmd *cobra.Command, _ []string) { - cmd.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) + RunE: func(cmd *cobra.Command, _ []string) error { + switch strings.ToLower(e.cfg.Version.Format) { + case "short": + cmd.Println(e.version) + case "json": + ver := jsonVersion{ + Version: e.version, + Commit: e.commit, + Date: e.date, + } + data, err := json.Marshal(&ver) + if err != nil { + return err + } + cmd.Println(string(data)) + default: + cmd.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) + } + return nil }, } e.rootCmd.AddCommand(versionCmd) + e.initVersionConfiguration(versionCmd) } diff --git a/pkg/config/config.go b/pkg/config/config.go index 22004bc1..bf7641f2 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -521,6 +521,10 @@ type Severity struct { Rules []SeverityRule `mapstructure:"rules"` } +type Version struct { + Format string `mapstructure:"format"` +} + type Config struct { Run Run @@ -539,6 +543,7 @@ type Config struct { Linters Linters Issues Issues Severity Severity + Version Version InternalTest bool // Option is used only for testing golangci-lint code, don't use it }