Support short and json formats for version cmd (#1315)

This commit is contained in:
Sergey Vilgelm 2020-08-20 08:57:41 -05:00 committed by GitHub
parent 8084559c42
commit a35fd6e91a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 50 additions and 2 deletions

View File

@ -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

View File

@ -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) {
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)
}

View File

@ -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
}