dev: clean commands (#3007)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Ville Skyttä 2022-07-23 01:55:25 +03:00 committed by GitHub
parent 9cb17e4f8f
commit a768760ce7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 80 additions and 107 deletions

View File

@ -8,7 +8,6 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/golangci/golangci-lint/internal/cache" "github.com/golangci/golangci-lint/internal/cache"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/fsutils" "github.com/golangci/golangci-lint/pkg/fsutils"
"github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/logutils"
) )
@ -17,57 +16,48 @@ func (e *Executor) initCache() {
cacheCmd := &cobra.Command{ cacheCmd := &cobra.Command{
Use: "cache", Use: "cache",
Short: "Cache control and information", Short: "Cache control and information",
Run: func(cmd *cobra.Command, args []string) { Args: cobra.NoArgs,
if len(args) != 0 { RunE: func(cmd *cobra.Command, _ []string) error {
e.log.Fatalf("Usage: golangci-lint cache") return cmd.Help()
}
if err := cmd.Help(); err != nil {
e.log.Fatalf("Can't run cache: %s", err)
}
}, },
} }
e.rootCmd.AddCommand(cacheCmd) e.rootCmd.AddCommand(cacheCmd)
cacheCmd.AddCommand(&cobra.Command{ cacheCmd.AddCommand(&cobra.Command{
Use: "clean", Use: "clean",
Short: "Clean cache", Short: "Clean cache",
Run: e.executeCleanCache, Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: e.executeCleanCache,
}) })
cacheCmd.AddCommand(&cobra.Command{ cacheCmd.AddCommand(&cobra.Command{
Use: "status", Use: "status",
Short: "Show cache status", Short: "Show cache status",
Run: e.executeCacheStatus, Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
Run: e.executeCacheStatus,
}) })
// TODO: add trim command? // TODO: add trim command?
} }
func (e *Executor) executeCleanCache(_ *cobra.Command, args []string) { func (e *Executor) executeCleanCache(_ *cobra.Command, _ []string) error {
if len(args) != 0 {
e.log.Fatalf("Usage: golangci-lint cache clean")
}
cacheDir := cache.DefaultDir() cacheDir := cache.DefaultDir()
if err := os.RemoveAll(cacheDir); err != nil { if err := os.RemoveAll(cacheDir); err != nil {
e.log.Fatalf("Failed to remove dir %s: %s", cacheDir, err) return fmt.Errorf("failed to remove dir %s: %w", cacheDir, err)
} }
os.Exit(exitcodes.Success) return nil
} }
func (e *Executor) executeCacheStatus(_ *cobra.Command, args []string) { func (e *Executor) executeCacheStatus(_ *cobra.Command, _ []string) {
if len(args) != 0 {
e.log.Fatalf("Usage: golangci-lint cache status")
}
cacheDir := cache.DefaultDir() cacheDir := cache.DefaultDir()
fmt.Fprintf(logutils.StdOut, "Dir: %s\n", cacheDir) fmt.Fprintf(logutils.StdOut, "Dir: %s\n", cacheDir)
cacheSizeBytes, err := dirSizeBytes(cacheDir) cacheSizeBytes, err := dirSizeBytes(cacheDir)
if err == nil { if err == nil {
fmt.Fprintf(logutils.StdOut, "Size: %s\n", fsutils.PrettifyBytesCount(cacheSizeBytes)) fmt.Fprintf(logutils.StdOut, "Size: %s\n", fsutils.PrettifyBytesCount(cacheSizeBytes))
} }
os.Exit(exitcodes.Success)
} }
func dirSizeBytes(path string) (int64, error) { func dirSizeBytes(path string) (int64, error) {

View File

@ -15,21 +15,19 @@ func (e *Executor) initConfig() {
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "config", Use: "config",
Short: "Config", Short: "Config",
Run: func(cmd *cobra.Command, args []string) { Args: cobra.NoArgs,
if len(args) != 0 { RunE: func(cmd *cobra.Command, _ []string) error {
e.log.Fatalf("Usage: golangci-lint config") return cmd.Help()
}
if err := cmd.Help(); err != nil {
e.log.Fatalf("Can't run help: %s", err)
}
}, },
} }
e.rootCmd.AddCommand(cmd) e.rootCmd.AddCommand(cmd)
pathCmd := &cobra.Command{ pathCmd := &cobra.Command{
Use: "path", Use: "path",
Short: "Print used config path", Short: "Print used config path",
Run: e.executePathCmd, Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
Run: e.executePathCmd,
} }
e.initRunConfiguration(pathCmd) // allow --config e.initRunConfiguration(pathCmd) // allow --config
cmd.AddCommand(pathCmd) cmd.AddCommand(pathCmd)
@ -52,11 +50,7 @@ func (e *Executor) getUsedConfig() string {
return prettyUsedConfigFile return prettyUsedConfigFile
} }
func (e *Executor) executePathCmd(_ *cobra.Command, args []string) { func (e *Executor) executePathCmd(_ *cobra.Command, _ []string) {
if len(args) != 0 {
e.log.Fatalf("Usage: golangci-lint config path")
}
usedConfigFile := e.getUsedConfig() usedConfigFile := e.getUsedConfig()
if usedConfigFile == "" { if usedConfigFile == "" {
e.log.Warnf("No config file detected") e.log.Warnf("No config file detected")
@ -64,5 +58,4 @@ func (e *Executor) executePathCmd(_ *cobra.Command, args []string) {
} }
fmt.Println(usedConfigFile) fmt.Println(usedConfigFile)
os.Exit(exitcodes.Success)
} }

View File

@ -2,14 +2,12 @@ package commands
import ( import (
"fmt" "fmt"
"os"
"sort" "sort"
"strings" "strings"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/linter"
"github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/logutils"
) )
@ -18,21 +16,19 @@ func (e *Executor) initHelp() {
helpCmd := &cobra.Command{ helpCmd := &cobra.Command{
Use: "help", Use: "help",
Short: "Help", Short: "Help",
Run: func(cmd *cobra.Command, args []string) { Args: cobra.NoArgs,
if len(args) != 0 { RunE: func(cmd *cobra.Command, _ []string) error {
e.log.Fatalf("Usage: golangci-lint help") return cmd.Help()
}
if err := cmd.Help(); err != nil {
e.log.Fatalf("Can't run help: %s", err)
}
}, },
} }
e.rootCmd.SetHelpCommand(helpCmd) e.rootCmd.SetHelpCommand(helpCmd)
lintersHelpCmd := &cobra.Command{ lintersHelpCmd := &cobra.Command{
Use: "linters", Use: "linters",
Short: "Help about linters", Short: "Help about linters",
Run: e.executeLintersHelp, Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
Run: e.executeLintersHelp,
} }
helpCmd.AddCommand(lintersHelpCmd) helpCmd.AddCommand(lintersHelpCmd)
} }
@ -64,11 +60,7 @@ func printLinterConfigs(lcs []*linter.Config) {
} }
} }
func (e *Executor) executeLintersHelp(_ *cobra.Command, args []string) { func (e *Executor) executeLintersHelp(_ *cobra.Command, _ []string) {
if len(args) != 0 {
e.log.Fatalf("Usage: golangci-lint help linters")
}
var enabledLCs, disabledLCs []*linter.Config var enabledLCs, disabledLCs []*linter.Config
for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() { for _, lc := range e.DBManager.GetAllSupportedLinterConfigs() {
if lc.EnabledByDefault { if lc.EnabledByDefault {
@ -93,6 +85,4 @@ func (e *Executor) executeLintersHelp(_ *cobra.Command, args []string) {
sort.Strings(linterNames) sort.Strings(linterNames)
fmt.Fprintf(logutils.StdOut, "%s: %s\n", color.YellowString(p), strings.Join(linterNames, ", ")) fmt.Fprintf(logutils.StdOut, "%s: %s\n", color.YellowString(p), strings.Join(linterNames, ", "))
} }
os.Exit(exitcodes.Success)
} }

View File

@ -1,35 +1,31 @@
package commands package commands
import ( import (
"log" "fmt"
"os"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/lint/linter" "github.com/golangci/golangci-lint/pkg/lint/linter"
) )
func (e *Executor) initLinters() { func (e *Executor) initLinters() {
e.lintersCmd = &cobra.Command{ e.lintersCmd = &cobra.Command{
Use: "linters", Use: "linters",
Short: "List current linters configuration", Short: "List current linters configuration",
Run: e.executeLinters, Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: e.executeLinters,
} }
e.rootCmd.AddCommand(e.lintersCmd) e.rootCmd.AddCommand(e.lintersCmd)
e.initRunConfiguration(e.lintersCmd) e.initRunConfiguration(e.lintersCmd)
} }
// executeLinters runs the 'linters' CLI command, which displays the supported linters. // executeLinters runs the 'linters' CLI command, which displays the supported linters.
func (e *Executor) executeLinters(_ *cobra.Command, args []string) { func (e *Executor) executeLinters(_ *cobra.Command, _ []string) error {
if len(args) != 0 {
e.log.Fatalf("Usage: golangci-lint linters")
}
enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap() enabledLintersMap, err := e.EnabledLintersSet.GetEnabledLintersMap()
if err != nil { if err != nil {
log.Fatalf("Can't get enabled linters: %s", err) return fmt.Errorf("can't get enabled linters: %w", err)
} }
color.Green("Enabled by your configuration linters:\n") color.Green("Enabled by your configuration linters:\n")
@ -49,5 +45,5 @@ func (e *Executor) executeLinters(_ *cobra.Command, args []string) {
color.Red("\nDisabled by your configuration linters:\n") color.Red("\nDisabled by your configuration linters:\n")
printLinterConfigs(disabledLCs) printLinterConfigs(disabledLCs)
os.Exit(exitcodes.Success) return nil
} }

View File

@ -12,14 +12,13 @@ import (
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/golangci/golangci-lint/pkg/config" "github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/logutils" "github.com/golangci/golangci-lint/pkg/logutils"
) )
func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) { func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) error {
if e.cfg.Run.PrintVersion { if e.cfg.Run.PrintVersion {
fmt.Fprintf(logutils.StdOut, "golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) _, _ = fmt.Fprintf(logutils.StdOut, "golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date)
os.Exit(exitcodes.Success) return nil
} }
runtime.GOMAXPROCS(e.cfg.Run.Concurrency) runtime.GOMAXPROCS(e.cfg.Run.Concurrency)
@ -27,10 +26,10 @@ func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) {
if e.cfg.Run.CPUProfilePath != "" { if e.cfg.Run.CPUProfilePath != "" {
f, err := os.Create(e.cfg.Run.CPUProfilePath) f, err := os.Create(e.cfg.Run.CPUProfilePath)
if err != nil { if err != nil {
e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.CPUProfilePath, err) return fmt.Errorf("can't create file %s: %w", e.cfg.Run.CPUProfilePath, err)
} }
if err := pprof.StartCPUProfile(f); err != nil { if err := pprof.StartCPUProfile(f); err != nil {
e.log.Fatalf("Can't start CPU profiling: %s", err) return fmt.Errorf("can't start CPU profiling: %w", err)
} }
} }
@ -43,22 +42,25 @@ func (e *Executor) persistentPreRun(_ *cobra.Command, _ []string) {
if e.cfg.Run.TracePath != "" { if e.cfg.Run.TracePath != "" {
f, err := os.Create(e.cfg.Run.TracePath) f, err := os.Create(e.cfg.Run.TracePath)
if err != nil { if err != nil {
e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.TracePath, err) return fmt.Errorf("can't create file %s: %w", e.cfg.Run.TracePath, err)
} }
if err = trace.Start(f); err != nil { if err = trace.Start(f); err != nil {
e.log.Fatalf("Can't start tracing: %s", err) return fmt.Errorf("can't start tracing: %w", err)
} }
} }
return nil
} }
func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) { func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) error {
if e.cfg.Run.CPUProfilePath != "" { if e.cfg.Run.CPUProfilePath != "" {
pprof.StopCPUProfile() pprof.StopCPUProfile()
} }
if e.cfg.Run.MemProfilePath != "" { if e.cfg.Run.MemProfilePath != "" {
f, err := os.Create(e.cfg.Run.MemProfilePath) f, err := os.Create(e.cfg.Run.MemProfilePath)
if err != nil { if err != nil {
e.log.Fatalf("Can't create file %s: %s", e.cfg.Run.MemProfilePath, err) return fmt.Errorf("can't create file %s: %w", e.cfg.Run.MemProfilePath, err)
} }
var ms runtime.MemStats var ms runtime.MemStats
@ -66,15 +68,18 @@ func (e *Executor) persistentPostRun(_ *cobra.Command, _ []string) {
printMemStats(&ms, e.log) printMemStats(&ms, e.log)
if err := pprof.WriteHeapProfile(f); err != nil { if err := pprof.WriteHeapProfile(f); err != nil {
e.log.Fatalf("Can't write heap profile: %s", err) return fmt.Errorf("cCan't write heap profile: %w", err)
} }
f.Close() _ = f.Close()
} }
if e.cfg.Run.TracePath != "" { if e.cfg.Run.TracePath != "" {
trace.Stop() trace.Stop()
} }
os.Exit(e.exitCode) os.Exit(e.exitCode)
return nil
} }
func printMemStats(ms *runtime.MemStats, logger logutils.Log) { func printMemStats(ms *runtime.MemStats, logger logutils.Log) {
@ -120,16 +125,12 @@ func (e *Executor) initRoot() {
Use: "golangci-lint", Use: "golangci-lint",
Short: "golangci-lint is a smart linters runner.", Short: "golangci-lint is a smart linters runner.",
Long: `Smart, fast linters runner. Run it in cloud for every GitHub pull request on https://golangci.com`, Long: `Smart, fast linters runner. Run it in cloud for every GitHub pull request on https://golangci.com`,
Run: func(cmd *cobra.Command, args []string) { Args: cobra.NoArgs,
if len(args) != 0 { RunE: func(cmd *cobra.Command, _ []string) error {
e.log.Fatalf("Usage: golangci-lint") return cmd.Help()
}
if err := cmd.Help(); err != nil {
e.log.Fatalf("Can't run help: %s", err)
}
}, },
PersistentPreRun: e.persistentPreRun, PersistentPreRunE: e.persistentPreRun,
PersistentPostRun: e.persistentPostRun, PersistentPostRunE: e.persistentPostRun,
} }
initRootFlagSet(rootCmd.PersistentFlags(), e.cfg, e.needVersionOption()) initRootFlagSet(rootCmd.PersistentFlags(), e.cfg, e.needVersionOption())

View File

@ -279,10 +279,11 @@ func (e *Executor) initRun() {
Use: "run", Use: "run",
Short: "Run the linters", Short: "Run the linters",
Run: e.executeRun, Run: e.executeRun,
PreRun: func(_ *cobra.Command, _ []string) { PreRunE: func(_ *cobra.Command, _ []string) error {
if ok := e.acquireFileLock(); !ok { if ok := e.acquireFileLock(); !ok {
e.log.Fatalf("Parallel golangci-lint is running") return fmt.Errorf("parallel golangci-lint is running")
} }
return nil
}, },
PostRun: func(_ *cobra.Command, _ []string) { PostRun: func(_ *cobra.Command, _ []string) {
e.releaseFileLock() e.releaseFileLock()

View File

@ -3,6 +3,7 @@ package commands
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"os"
"strings" "strings"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -31,27 +32,28 @@ func initVersionFlagSet(fs *pflag.FlagSet, cfg *config.Config) {
func (e *Executor) initVersion() { func (e *Executor) initVersion() {
versionCmd := &cobra.Command{ versionCmd := &cobra.Command{
Use: "version", Use: "version",
Short: "Version", Short: "Version",
Args: cobra.NoArgs,
ValidArgsFunction: cobra.NoFileCompletions,
RunE: func(cmd *cobra.Command, _ []string) error { RunE: func(cmd *cobra.Command, _ []string) error {
switch strings.ToLower(e.cfg.Version.Format) { switch strings.ToLower(e.cfg.Version.Format) {
case "short": case "short":
fmt.Println(e.version) fmt.Println(e.version)
return nil
case "json": case "json":
ver := jsonVersion{ ver := jsonVersion{
Version: e.version, Version: e.version,
Commit: e.commit, Commit: e.commit,
Date: e.date, Date: e.date,
} }
data, err := json.Marshal(&ver) return json.NewEncoder(os.Stdout).Encode(&ver)
if err != nil {
return err
}
fmt.Println(string(data))
default: default:
fmt.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date) fmt.Printf("golangci-lint has version %s built from %s on %s\n", e.version, e.commit, e.date)
return nil
} }
return nil
}, },
} }