From 03c35a9dc2c4a503ecd4f11df52a554317d7eae2 Mon Sep 17 00:00:00 2001 From: chavacava Date: Sat, 7 Dec 2024 15:42:54 +0100 Subject: [PATCH 1/2] initial refactoring --- cli/main.go | 7 ++++--- config/config.go | 6 +++--- formatter/friendly.go | 26 ++++++++++++++------------ lint/file.go | 34 ++++++++++++++++++---------------- lint/linter.go | 6 +++--- lint/package.go | 6 +++--- lint/rule.go | 5 ----- logging/logger.go | 6 ++---- 8 files changed, 47 insertions(+), 49 deletions(-) diff --git a/cli/main.go b/cli/main.go index 992e52dc8..0b7d38dad 100644 --- a/cli/main.go +++ b/cli/main.go @@ -132,11 +132,12 @@ func buildDefaultConfigPath() string { homeDirFile = filepath.Join(homeDir, configFileName) } - if fileExist(configDirFile) { + switch { + case fileExist(configDirFile): result = configDirFile - } else if fileExist(homeDirFile) { + case fileExist(homeDirFile): result = homeDirFile - } else { + default: result = "" } diff --git a/config/config.go b/config/config.go index 5ff9aa352..465d435f4 100644 --- a/config/config.go +++ b/config/config.go @@ -242,15 +242,15 @@ func GetConfig(configPath string) (*lint.Config, error) { // GetFormatter yields the formatter for lint failures func GetFormatter(formatterName string) (lint.Formatter, error) { formatters := getFormatters() - fmtr := formatters["default"] + result := formatters["default"] if formatterName != "" { f, ok := formatters[formatterName] if !ok { return nil, fmt.Errorf("unknown formatter %v", formatterName) } - fmtr = f + result = f } - return fmtr, nil + return result, nil } func defaultConfig() *lint.Config { diff --git a/formatter/friendly.go b/formatter/friendly.go index bbbbcb6a5..ac2d718fb 100644 --- a/formatter/friendly.go +++ b/formatter/friendly.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "sort" + "strings" "github.com/fatih/color" "github.com/mgechev/revive/lint" @@ -32,7 +33,7 @@ func (*Friendly) Name() string { // Format formats the failures gotten from the lint. func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { - var buf bytes.Buffer + var buf strings.Builder errorMap := map[string]int{} warningMap := map[string]int{} totalErrors := 0 @@ -40,37 +41,38 @@ func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (str for failure := range failures { sev := severity(config, failure) f.printFriendlyFailure(&buf, failure, sev) - if sev == lint.SeverityWarning { + switch sev { + case lint.SeverityWarning: warningMap[failure.RuleName]++ totalWarnings++ - } - if sev == lint.SeverityError { + case lint.SeverityError: errorMap[failure.RuleName]++ totalErrors++ } } + f.printSummary(&buf, totalErrors, totalWarnings) f.printStatistics(&buf, color.RedString("Errors:"), errorMap) f.printStatistics(&buf, color.YellowString("Warnings:"), warningMap) return buf.String(), nil } -func (f *Friendly) printFriendlyFailure(w io.Writer, failure lint.Failure, severity lint.Severity) { - f.printHeaderRow(w, failure, severity) - f.printFilePosition(w, failure) - fmt.Fprintf(w, "\n\n") +func (f *Friendly) printFrisendlyFailure(sb *strings.Builder, failure lint.Failure, severity lint.Severity) { + f.printHeaderRow(sb, failure, severity) + f.printFilePosition(sb, failure) + sb.WriteString("\n\n") } -func (f *Friendly) printHeaderRow(w io.Writer, failure lint.Failure, severity lint.Severity) { +func (f *Friendly) printHeaderRow(sb *strings.Builder, failure lint.Failure, severity lint.Severity) { emoji := getWarningEmoji() if severity == lint.SeverityError { emoji = getErrorEmoji() } - fmt.Fprint(w, f.table([][]string{{emoji, ruleDescriptionURL(failure.RuleName), color.GreenString(failure.Failure)}})) + sb.WriteString(f.table([][]string{{emoji, ruleDescriptionURL(failure.RuleName), color.GreenString(failure.Failure)}})) } -func (*Friendly) printFilePosition(w io.Writer, failure lint.Failure) { - fmt.Fprintf(w, " %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column) +func (*Friendly) printFilePosition(sb *strings.Builder, failure lint.Failure) { + sb.WriteString(fmt.Sprintf(" %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column)) } type statEntry struct { diff --git a/lint/file.go b/lint/file.go index c695d63f5..861241b0c 100644 --- a/lint/file.go +++ b/lint/file.go @@ -191,13 +191,14 @@ func (f *File) disabledIntervals(rules []Rule, mustSpecifyDisableReason bool, fa handleRules := func(_, modifier string, isEnabled bool, line int, ruleNames []string) []DisabledInterval { var result []DisabledInterval for _, name := range ruleNames { - if modifier == "line" { + switch modifier { + case "line": handleConfig(isEnabled, line, name) handleConfig(!isEnabled, line, name) - } else if modifier == "next-line" { + case "next-line": handleConfig(isEnabled, line+1, name) handleConfig(!isEnabled, line+1, name) - } else { + default: handleConfig(isEnabled, line, name) } } @@ -260,21 +261,22 @@ func (File) filterFailures(failures []Failure, disabledIntervals disabledInterva intervals, ok := disabledIntervals[failure.RuleName] if !ok { result = append(result, failure) - } else { - include := true - for _, interval := range intervals { - intStart := interval.From.Line - intEnd := interval.To.Line - if (fStart >= intStart && fStart <= intEnd) || - (fEnd >= intStart && fEnd <= intEnd) { - include = false - break - } - } - if include { - result = append(result, failure) + continue + } + + include := true + for _, interval := range intervals { + intStart := interval.From.Line + intEnd := interval.To.Line + if (fStart >= intStart && fStart <= intEnd) || + (fEnd >= intStart && fEnd <= intEnd) { + include = false + break } } + if include { + result = append(result, failure) + } } return result } diff --git a/lint/linter.go b/lint/linter.go index 10f5cac36..03a6a9a95 100644 --- a/lint/linter.go +++ b/lint/linter.go @@ -54,8 +54,8 @@ func (l Linter) readFile(path string) (result []byte, err error) { } var ( - genHdr = []byte("// Code generated ") - genFtr = []byte(" DO NOT EDIT.") + generatedPrefix = []byte("// Code generated ") + generatedSuffix = []byte(" DO NOT EDIT.") defaultGoVersion = goversion.Must(goversion.NewVersion("1.0")) ) @@ -209,7 +209,7 @@ func isGenerated(src []byte) bool { sc := bufio.NewScanner(bytes.NewReader(src)) for sc.Scan() { b := sc.Bytes() - if bytes.HasPrefix(b, genHdr) && bytes.HasSuffix(b, genFtr) && len(b) >= len(genHdr)+len(genFtr) { + if bytes.HasPrefix(b, generatedPrefix) && bytes.HasSuffix(b, generatedSuffix) && len(b) >= len(generatedPrefix)+len(generatedSuffix) { return true } } diff --git a/lint/package.go b/lint/package.go index 41575f480..51e14a578 100644 --- a/lint/package.go +++ b/lint/package.go @@ -89,11 +89,11 @@ func (p *Package) TypeCheck() error { p.Lock() defer p.Unlock() - // If type checking has already been performed - // skip it. - if p.typesInfo != nil || p.typesPkg != nil { + alreadyTypeChecked := p.typesInfo != nil || p.typesPkg != nil + if alreadyTypeChecked { return nil } + config := &types.Config{ // By setting a no-op error reporter, the type checker does as much work as possible. Error: func(error) {}, diff --git a/lint/rule.go b/lint/rule.go index ccc66691c..6189b9f7d 100644 --- a/lint/rule.go +++ b/lint/rule.go @@ -17,11 +17,6 @@ type Rule interface { Apply(*File, Arguments) []Failure } -// AbstractRule defines an abstract rule. -type AbstractRule struct { - Failures []Failure -} - // ToFailurePosition returns the failure position. func ToFailurePosition(start, end token.Pos, file *File) FailurePosition { return FailurePosition{ diff --git a/logging/logger.go b/logging/logger.go index 24305b968..9c6bb41fa 100644 --- a/logging/logger.go +++ b/logging/logger.go @@ -19,15 +19,13 @@ func GetLogger() (*log.Logger, error) { var writer io.Writer var err error + writer = io.Discard // by default, suppress all logging output debugModeEnabled := os.Getenv("DEBUG") == "1" if debugModeEnabled { writer, err = os.Create("revive.log") if err != nil { return nil, err } - } else { - // Suppress all logging output if debug mode is disabled - writer = io.Discard } logger = log.New(writer, "", log.LstdFlags) @@ -38,7 +36,7 @@ func GetLogger() (*log.Logger, error) { logger.SetFlags(0) } - logger.Println("Logger initialised") + logger.Println("Logger initialized") return logger, nil } From ea9ec58937d273f26105af32e44c3aafa85531b6 Mon Sep 17 00:00:00 2001 From: chavacava Date: Sat, 7 Dec 2024 15:58:30 +0100 Subject: [PATCH 2/2] second batch --- formatter/friendly.go | 2 +- formatter/plain.go | 8 ++++---- formatter/stylish.go | 7 ++++--- formatter/unix.go | 8 ++++---- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/formatter/friendly.go b/formatter/friendly.go index ac2d718fb..342ce35a6 100644 --- a/formatter/friendly.go +++ b/formatter/friendly.go @@ -57,7 +57,7 @@ func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (str return buf.String(), nil } -func (f *Friendly) printFrisendlyFailure(sb *strings.Builder, failure lint.Failure, severity lint.Severity) { +func (f *Friendly) printFriendlyFailure(sb *strings.Builder, failure lint.Failure, severity lint.Severity) { f.printHeaderRow(sb, failure, severity) f.printFilePosition(sb, failure) sb.WriteString("\n\n") diff --git a/formatter/plain.go b/formatter/plain.go index c972432b5..351248742 100644 --- a/formatter/plain.go +++ b/formatter/plain.go @@ -1,8 +1,8 @@ package formatter import ( - "bytes" "fmt" + "strings" "github.com/mgechev/revive/lint" ) @@ -20,9 +20,9 @@ func (*Plain) Name() string { // Format formats the failures gotten from the lint. func (*Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { - var buf bytes.Buffer + var sb strings.Builder for failure := range failures { - fmt.Fprintf(&buf, "%v: %s %s\n", failure.Position.Start, failure.Failure, ruleDescriptionURL(failure.RuleName)) + sb.WriteString(fmt.Sprintf("%v: %s %s\n", failure.Position.Start, failure.Failure, ruleDescriptionURL(failure.RuleName))) } - return buf.String(), nil + return sb.String(), nil } diff --git a/formatter/stylish.go b/formatter/stylish.go index 957a6056d..bb3d7cd18 100644 --- a/formatter/stylish.go +++ b/formatter/stylish.go @@ -78,11 +78,12 @@ func (*Stylish) Format(failures <-chan lint.Failure, config lint.Config) (string suffix := fmt.Sprintf(" %d %s (%d errors) (%d warnings)", total, ps, totalErrors, total-totalErrors) - if total > 0 && totalErrors > 0 { + switch { + case total > 0 && totalErrors > 0: suffix = color.RedString("\n ✖" + suffix) - } else if total > 0 && totalErrors == 0 { + case total > 0 && totalErrors == 0: suffix = color.YellowString("\n ✖" + suffix) - } else { + default: suffix, output = "", "" } diff --git a/formatter/unix.go b/formatter/unix.go index e46f3c275..9ce8fee4d 100644 --- a/formatter/unix.go +++ b/formatter/unix.go @@ -1,8 +1,8 @@ package formatter import ( - "bytes" "fmt" + "strings" "github.com/mgechev/revive/lint" ) @@ -22,9 +22,9 @@ func (*Unix) Name() string { // Format formats the failures gotten from the lint. func (*Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { - var buf bytes.Buffer + var sb strings.Builder for failure := range failures { - fmt.Fprintf(&buf, "%v: [%s] %s\n", failure.Position.Start, failure.RuleName, failure.Failure) + sb.WriteString(fmt.Sprintf("%v: [%s] %s\n", failure.Position.Start, failure.RuleName, failure.Failure)) } - return buf.String(), nil + return sb.String(), nil }