dev: remove unrelated flags from config and linters command (#4284)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Mateus Oliveira 2024-02-03 16:11:24 -03:00 committed by GitHub
parent 4ea9468cd6
commit a727aa5780
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 91 additions and 62 deletions

View File

@ -2649,7 +2649,7 @@ linters:
- test - test
- unused - unused
# Run only fast linters from enabled linters set (first run won't be fast) # Enable only fast linters from enabled linters set (first run won't be fast)
# Default: false # Default: false
fast: true fast: true

View File

@ -5,8 +5,10 @@ import (
"os" "os"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/exitcodes" "github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/fsutils"
) )
@ -14,7 +16,7 @@ import (
func (e *Executor) initConfig() { func (e *Executor) initConfig() {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "config", Use: "config",
Short: "Config", Short: "Config file information",
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Help() return cmd.Help()
@ -29,7 +31,12 @@ func (e *Executor) initConfig() {
ValidArgsFunction: cobra.NoFileCompletions, ValidArgsFunction: cobra.NoFileCompletions,
Run: e.executePathCmd, Run: e.executePathCmd,
} }
e.initRunConfiguration(pathCmd) // allow --config
fs := pathCmd.Flags()
fs.SortFlags = false // sort them as they are defined here
initConfigFileFlagSet(fs, &e.cfg.Run)
cmd.AddCommand(pathCmd) cmd.AddCommand(pathCmd)
} }
@ -59,3 +66,8 @@ func (e *Executor) executePathCmd(_ *cobra.Command, _ []string) {
fmt.Println(usedConfigFile) fmt.Println(usedConfigFile)
} }
func initConfigFileFlagSet(fs *pflag.FlagSet, cfg *config.Run) {
fs.StringVarP(&cfg.Config, "config", "c", "", wh("Read config from file path `PATH`"))
fs.BoolVar(&cfg.NoConfig, "no-config", false, wh("Don't read config file"))
}

View File

@ -2,10 +2,13 @@ package commands
import ( import (
"fmt" "fmt"
"strings"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/linter"
) )
@ -17,8 +20,25 @@ func (e *Executor) initLinters() {
ValidArgsFunction: cobra.NoFileCompletions, ValidArgsFunction: cobra.NoFileCompletions,
RunE: e.executeLinters, RunE: e.executeLinters,
} }
fs := e.lintersCmd.Flags()
fs.SortFlags = false // sort them as they are defined here
initConfigFileFlagSet(fs, &e.cfg.Run)
e.initLintersFlagSet(fs, &e.cfg.Linters)
e.rootCmd.AddCommand(e.lintersCmd) e.rootCmd.AddCommand(e.lintersCmd)
e.initRunConfiguration(e.lintersCmd) }
func (e *Executor) initLintersFlagSet(fs *pflag.FlagSet, cfg *config.Linters) {
fs.StringSliceVarP(&cfg.Disable, "disable", "D", nil, wh("Disable specific linter"))
fs.BoolVar(&cfg.DisableAll, "disable-all", false, wh("Disable all linters"))
fs.StringSliceVarP(&cfg.Enable, "enable", "E", nil, wh("Enable specific linter"))
fs.BoolVar(&cfg.EnableAll, "enable-all", false, wh("Enable all linters"))
fs.BoolVar(&cfg.Fast, "fast", false, wh("Enable only fast linters from enabled linters set (first run won't be fast)"))
fs.StringSliceVarP(&cfg.Presets, "presets", "p", nil,
wh(fmt.Sprintf("Enable presets (%s) of linters. Run 'golangci-lint help linters' to see "+
"them. This option implies option --disable-all", strings.Join(e.DBManager.AllPresets(), "|"))))
} }
// executeLinters runs the 'linters' CLI command, which displays the supported linters. // executeLinters runs the 'linters' CLI command, which displays the supported linters.
@ -28,18 +48,9 @@ func (e *Executor) executeLinters(_ *cobra.Command, _ []string) error {
return fmt.Errorf("can't get enabled linters: %w", err) return fmt.Errorf("can't get enabled linters: %w", err)
} }
color.Green("Enabled by your configuration linters:\n")
var enabledLinters []*linter.Config var enabledLinters []*linter.Config
for _, lc := range enabledLintersMap {
if lc.Internal {
continue
}
enabledLinters = append(enabledLinters, lc)
}
printLinterConfigs(enabledLinters)
var disabledLCs []*linter.Config var disabledLCs []*linter.Config
for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() {
if lc.Internal { if lc.Internal {
continue continue
@ -47,9 +58,13 @@ func (e *Executor) executeLinters(_ *cobra.Command, _ []string) error {
if enabledLintersMap[lc.Name()] == nil { if enabledLintersMap[lc.Name()] == nil {
disabledLCs = append(disabledLCs, lc) disabledLCs = append(disabledLCs, lc)
} else {
enabledLinters = append(enabledLinters, lc)
} }
} }
color.Green("Enabled by your configuration linters:\n")
printLinterConfigs(enabledLinters)
color.Red("\nDisabled by your configuration linters:\n") color.Red("\nDisabled by your configuration linters:\n")
printLinterConfigs(disabledLCs) printLinterConfigs(disabledLCs)

View File

@ -29,6 +29,8 @@ import (
const defaultFileMode = 0644 const defaultFileMode = 0644
const defaultTimeout = time.Minute
const ( const (
// envFailOnWarnings value: "1" // envFailOnWarnings value: "1"
envFailOnWarnings = "FAIL_ON_WARNINGS" envFailOnWarnings = "FAIL_ON_WARNINGS"
@ -36,35 +38,8 @@ const (
envMemLogEvery = "GL_MEM_LOG_EVERY" envMemLogEvery = "GL_MEM_LOG_EVERY"
) )
func getDefaultIssueExcludeHelp() string {
parts := []string{color.GreenString("Use or not use default excludes:")}
for _, ep := range config.DefaultExcludePatterns {
parts = append(parts,
fmt.Sprintf(" # %s %s: %s", ep.ID, ep.Linter, ep.Why),
fmt.Sprintf(" - %s", color.YellowString(ep.Pattern)),
"",
)
}
return strings.Join(parts, "\n")
}
func getDefaultDirectoryExcludeHelp() string {
parts := []string{color.GreenString("Use or not use default excluded directories:")}
for _, dir := range packages.StdExcludeDirRegexps {
parts = append(parts, fmt.Sprintf(" - %s", color.YellowString(dir)))
}
parts = append(parts, "")
return strings.Join(parts, "\n")
}
func wh(text string) string {
return color.GreenString(text)
}
const defaultTimeout = time.Minute
//nolint:funlen,gomnd //nolint:funlen,gomnd
func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, isFinalInit bool) { func (e *Executor) initFlagSet(fs *pflag.FlagSet, cfg *config.Config, isFinalInit bool) {
hideFlag := func(name string) { hideFlag := func(name string) {
if err := fs.MarkHidden(name); err != nil { if err := fs.MarkHidden(name); err != nil {
panic(err) panic(err)
@ -79,6 +54,10 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is
} }
} }
// Config file config
rc := &cfg.Run
initConfigFileFlagSet(fs, rc)
// Output config // Output config
oc := &cfg.Output oc := &cfg.Output
fs.StringVar(&oc.Format, "out-format", fs.StringVar(&oc.Format, "out-format",
@ -98,7 +77,6 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is
} }
// Run config // Run config
rc := &cfg.Run
fs.StringVar(&rc.ModulesDownloadMode, "modules-download-mode", "", fs.StringVar(&rc.ModulesDownloadMode, "modules-download-mode", "",
wh("Modules download mode. If not empty, passed as -mod=<mode> to go tools")) wh("Modules download mode. If not empty, passed as -mod=<mode> to go tools"))
fs.IntVar(&rc.ExitCodeIfIssuesFound, "issues-exit-code", fs.IntVar(&rc.ExitCodeIfIssuesFound, "issues-exit-code",
@ -115,8 +93,6 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is
fs.BoolVar(&rc.AnalyzeTests, "tests", true, wh("Analyze tests (*_test.go)")) fs.BoolVar(&rc.AnalyzeTests, "tests", true, wh("Analyze tests (*_test.go)"))
fs.BoolVar(&rc.PrintResourcesUsage, "print-resources-usage", false, fs.BoolVar(&rc.PrintResourcesUsage, "print-resources-usage", false,
wh("Print avg and max memory usage of golangci-lint and total time")) wh("Print avg and max memory usage of golangci-lint and total time"))
fs.StringVarP(&rc.Config, "config", "c", "", wh("Read config from file path `PATH`"))
fs.BoolVar(&rc.NoConfig, "no-config", false, wh("Don't read config"))
fs.StringSliceVar(&rc.SkipDirs, "skip-dirs", nil, wh("Regexps of directories to skip")) fs.StringSliceVar(&rc.SkipDirs, "skip-dirs", nil, wh("Regexps of directories to skip"))
fs.BoolVar(&rc.UseDefaultSkipDirs, "skip-dirs-use-default", true, getDefaultDirectoryExcludeHelp()) fs.BoolVar(&rc.UseDefaultSkipDirs, "skip-dirs-use-default", true, getDefaultDirectoryExcludeHelp())
fs.StringSliceVar(&rc.SkipFiles, "skip-files", nil, wh("Regexps of files to skip")) fs.StringSliceVar(&rc.SkipFiles, "skip-files", nil, wh("Regexps of files to skip"))
@ -200,15 +176,7 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is
// Linters config // Linters config
lc := &cfg.Linters lc := &cfg.Linters
fs.StringSliceVarP(&lc.Enable, "enable", "E", nil, wh("Enable specific linter")) e.initLintersFlagSet(fs, lc)
fs.StringSliceVarP(&lc.Disable, "disable", "D", nil, wh("Disable specific linter"))
fs.BoolVar(&lc.EnableAll, "enable-all", false, wh("Enable all linters"))
fs.BoolVar(&lc.DisableAll, "disable-all", false, wh("Disable all linters"))
fs.StringSliceVarP(&lc.Presets, "presets", "p", nil,
wh(fmt.Sprintf("Enable presets (%s) of linters. Run 'golangci-lint help linters' to see "+
"them. This option implies option --disable-all", strings.Join(m.AllPresets(), "|"))))
fs.BoolVar(&lc.Fast, "fast", false, wh("Run only fast linters from enabled linters set (first run won't be fast)"))
// Issues config // Issues config
ic := &cfg.Issues ic := &cfg.Issues
@ -241,7 +209,7 @@ func initFlagSet(fs *pflag.FlagSet, cfg *config.Config, m *lintersdb.Manager, is
func (e *Executor) initRunConfiguration(cmd *cobra.Command) { func (e *Executor) initRunConfiguration(cmd *cobra.Command) {
fs := cmd.Flags() fs := cmd.Flags()
fs.SortFlags = false // sort them as they are defined here fs.SortFlags = false // sort them as they are defined here
initFlagSet(fs, e.cfg, e.DBManager, true) e.initFlagSet(fs, e.cfg, true)
} }
func (e *Executor) getConfigForCommandLine() (*config.Config, error) { func (e *Executor) getConfigForCommandLine() (*config.Config, error) {
@ -254,7 +222,7 @@ func (e *Executor) getConfigForCommandLine() (*config.Config, error) {
// `changed` variable inside string slice vars will be shared. // `changed` variable inside string slice vars will be shared.
// Use another config variable here, not e.cfg, to not // Use another config variable here, not e.cfg, to not
// affect main parsing by this parsing of only config option. // affect main parsing by this parsing of only config option.
initFlagSet(fs, &cfg, e.DBManager, false) e.initFlagSet(fs, &cfg, false)
initVersionFlagSet(fs, &cfg) initVersionFlagSet(fs, &cfg)
// Parse max options, even force version option: don't want // Parse max options, even force version option: don't want
@ -639,3 +607,28 @@ func watchResources(ctx context.Context, done chan struct{}, logger logutils.Log
logger.Infof("Execution took %s", time.Since(startedAt)) logger.Infof("Execution took %s", time.Since(startedAt))
close(done) close(done)
} }
func getDefaultIssueExcludeHelp() string {
parts := []string{color.GreenString("Use or not use default excludes:")}
for _, ep := range config.DefaultExcludePatterns {
parts = append(parts,
fmt.Sprintf(" # %s %s: %s", ep.ID, ep.Linter, ep.Why),
fmt.Sprintf(" - %s", color.YellowString(ep.Pattern)),
"",
)
}
return strings.Join(parts, "\n")
}
func getDefaultDirectoryExcludeHelp() string {
parts := []string{color.GreenString("Use or not use default excluded directories:")}
for _, dir := range packages.StdExcludeDirRegexps {
parts = append(parts, fmt.Sprintf(" - %s", color.YellowString(dir)))
}
parts = append(parts, "")
return strings.Join(parts, "\n")
}
func wh(text string) string {
return color.GreenString(text)
}

View File

@ -163,12 +163,13 @@ func (b *RunnerBuilder) Runner() *Runner {
b.tb.Fatal("--no-config and -c cannot be used at the same time") b.tb.Fatal("--no-config and -c cannot be used at the same time")
} }
arguments := []string{ var arguments []string
"--internal-cmd-test",
}
if b.allowParallelRunners { if b.command == "run" {
arguments = append(arguments, "--allow-parallel-runners") arguments = append(arguments, "--internal-cmd-test")
if b.allowParallelRunners {
arguments = append(arguments, "--allow-parallel-runners")
}
} }
if b.noConfig { if b.noConfig {

View File

@ -28,11 +28,19 @@ func TestRunnerBuilder_Runner(t *testing.T) {
}, },
}, },
{ {
desc: "with command", desc: "with non run command",
builder: NewRunnerBuilder(t).WithCommand("example"), builder: NewRunnerBuilder(t).WithCommand("example"),
expected: &Runner{ expected: &Runner{
env: []string(nil), env: []string(nil),
command: "example", command: "example",
},
},
{
desc: "with run command",
builder: NewRunnerBuilder(t).WithCommand("run"),
expected: &Runner{
env: []string(nil),
command: "run",
args: []string{ args: []string{
"--internal-cmd-test", "--internal-cmd-test",
"--allow-parallel-runners", "--allow-parallel-runners",