1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-23 22:04:49 +02:00

refactor: code cleanup (#1177)

This commit is contained in:
chavacava
2024-12-08 11:08:54 +01:00
committed by GitHub
parent 5c2aadfa91
commit f6a38208af
11 changed files with 59 additions and 60 deletions

View File

@@ -132,11 +132,12 @@ func buildDefaultConfigPath() string {
homeDirFile = filepath.Join(homeDir, configFileName) homeDirFile = filepath.Join(homeDir, configFileName)
} }
if fileExist(configDirFile) { switch {
case fileExist(configDirFile):
result = configDirFile result = configDirFile
} else if fileExist(homeDirFile) { case fileExist(homeDirFile):
result = homeDirFile result = homeDirFile
} else { default:
result = "" result = ""
} }

View File

@@ -242,15 +242,15 @@ func GetConfig(configPath string) (*lint.Config, error) {
// GetFormatter yields the formatter for lint failures // GetFormatter yields the formatter for lint failures
func GetFormatter(formatterName string) (lint.Formatter, error) { func GetFormatter(formatterName string) (lint.Formatter, error) {
formatters := getFormatters() formatters := getFormatters()
fmtr := formatters["default"] result := formatters["default"]
if formatterName != "" { if formatterName != "" {
f, ok := formatters[formatterName] f, ok := formatters[formatterName]
if !ok { if !ok {
return nil, fmt.Errorf("unknown formatter %v", formatterName) return nil, fmt.Errorf("unknown formatter %v", formatterName)
} }
fmtr = f result = f
} }
return fmtr, nil return result, nil
} }
func defaultConfig() *lint.Config { func defaultConfig() *lint.Config {

View File

@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"io" "io"
"sort" "sort"
"strings"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/mgechev/revive/lint" "github.com/mgechev/revive/lint"
@@ -32,7 +33,7 @@ func (*Friendly) Name() string {
// Format formats the failures gotten from the lint. // Format formats the failures gotten from the lint.
func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (string, error) { 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{} errorMap := map[string]int{}
warningMap := map[string]int{} warningMap := map[string]int{}
totalErrors := 0 totalErrors := 0
@@ -40,37 +41,38 @@ func (f *Friendly) Format(failures <-chan lint.Failure, config lint.Config) (str
for failure := range failures { for failure := range failures {
sev := severity(config, failure) sev := severity(config, failure)
f.printFriendlyFailure(&buf, failure, sev) f.printFriendlyFailure(&buf, failure, sev)
if sev == lint.SeverityWarning { switch sev {
case lint.SeverityWarning:
warningMap[failure.RuleName]++ warningMap[failure.RuleName]++
totalWarnings++ totalWarnings++
} case lint.SeverityError:
if sev == lint.SeverityError {
errorMap[failure.RuleName]++ errorMap[failure.RuleName]++
totalErrors++ totalErrors++
} }
} }
f.printSummary(&buf, totalErrors, totalWarnings) f.printSummary(&buf, totalErrors, totalWarnings)
f.printStatistics(&buf, color.RedString("Errors:"), errorMap) f.printStatistics(&buf, color.RedString("Errors:"), errorMap)
f.printStatistics(&buf, color.YellowString("Warnings:"), warningMap) f.printStatistics(&buf, color.YellowString("Warnings:"), warningMap)
return buf.String(), nil return buf.String(), nil
} }
func (f *Friendly) printFriendlyFailure(w io.Writer, failure lint.Failure, severity lint.Severity) { func (f *Friendly) printFriendlyFailure(sb *strings.Builder, failure lint.Failure, severity lint.Severity) {
f.printHeaderRow(w, failure, severity) f.printHeaderRow(sb, failure, severity)
f.printFilePosition(w, failure) f.printFilePosition(sb, failure)
fmt.Fprintf(w, "\n\n") 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() emoji := getWarningEmoji()
if severity == lint.SeverityError { if severity == lint.SeverityError {
emoji = getErrorEmoji() 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) { func (*Friendly) printFilePosition(sb *strings.Builder, failure lint.Failure) {
fmt.Fprintf(w, " %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column) sb.WriteString(fmt.Sprintf(" %s:%d:%d", failure.GetFilename(), failure.Position.Start.Line, failure.Position.Start.Column))
} }
type statEntry struct { type statEntry struct {

View File

@@ -1,8 +1,8 @@
package formatter package formatter
import ( import (
"bytes"
"fmt" "fmt"
"strings"
"github.com/mgechev/revive/lint" "github.com/mgechev/revive/lint"
) )
@@ -20,9 +20,9 @@ func (*Plain) Name() string {
// Format formats the failures gotten from the lint. // Format formats the failures gotten from the lint.
func (*Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { func (*Plain) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) {
var buf bytes.Buffer var sb strings.Builder
for failure := range failures { 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
} }

View File

@@ -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) 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) suffix = color.RedString("\n ✖" + suffix)
} else if total > 0 && totalErrors == 0 { case total > 0 && totalErrors == 0:
suffix = color.YellowString("\n ✖" + suffix) suffix = color.YellowString("\n ✖" + suffix)
} else { default:
suffix, output = "", "" suffix, output = "", ""
} }

View File

@@ -1,8 +1,8 @@
package formatter package formatter
import ( import (
"bytes"
"fmt" "fmt"
"strings"
"github.com/mgechev/revive/lint" "github.com/mgechev/revive/lint"
) )
@@ -22,9 +22,9 @@ func (*Unix) Name() string {
// Format formats the failures gotten from the lint. // Format formats the failures gotten from the lint.
func (*Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) { func (*Unix) Format(failures <-chan lint.Failure, _ lint.Config) (string, error) {
var buf bytes.Buffer var sb strings.Builder
for failure := range failures { 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
} }

View File

@@ -191,13 +191,14 @@ func (f *File) disabledIntervals(rules []Rule, mustSpecifyDisableReason bool, fa
handleRules := func(_, modifier string, isEnabled bool, line int, ruleNames []string) []DisabledInterval { handleRules := func(_, modifier string, isEnabled bool, line int, ruleNames []string) []DisabledInterval {
var result []DisabledInterval var result []DisabledInterval
for _, name := range ruleNames { for _, name := range ruleNames {
if modifier == "line" { switch modifier {
case "line":
handleConfig(isEnabled, line, name) handleConfig(isEnabled, line, name)
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)
handleConfig(!isEnabled, line+1, name) handleConfig(!isEnabled, line+1, name)
} else { default:
handleConfig(isEnabled, line, name) handleConfig(isEnabled, line, name)
} }
} }
@@ -260,21 +261,22 @@ func (File) filterFailures(failures []Failure, disabledIntervals disabledInterva
intervals, ok := disabledIntervals[failure.RuleName] intervals, ok := disabledIntervals[failure.RuleName]
if !ok { if !ok {
result = append(result, failure) result = append(result, failure)
} else { continue
include := true }
for _, interval := range intervals {
intStart := interval.From.Line include := true
intEnd := interval.To.Line for _, interval := range intervals {
if (fStart >= intStart && fStart <= intEnd) || intStart := interval.From.Line
(fEnd >= intStart && fEnd <= intEnd) { intEnd := interval.To.Line
include = false if (fStart >= intStart && fStart <= intEnd) ||
break (fEnd >= intStart && fEnd <= intEnd) {
} include = false
} break
if include {
result = append(result, failure)
} }
} }
if include {
result = append(result, failure)
}
} }
return result return result
} }

View File

@@ -54,8 +54,8 @@ func (l Linter) readFile(path string) (result []byte, err error) {
} }
var ( var (
genHdr = []byte("// Code generated ") generatedPrefix = []byte("// Code generated ")
genFtr = []byte(" DO NOT EDIT.") generatedSuffix = []byte(" DO NOT EDIT.")
defaultGoVersion = goversion.Must(goversion.NewVersion("1.0")) defaultGoVersion = goversion.Must(goversion.NewVersion("1.0"))
) )
@@ -209,7 +209,7 @@ func isGenerated(src []byte) bool {
sc := bufio.NewScanner(bytes.NewReader(src)) sc := bufio.NewScanner(bytes.NewReader(src))
for sc.Scan() { for sc.Scan() {
b := sc.Bytes() 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 return true
} }
} }

View File

@@ -89,11 +89,11 @@ func (p *Package) TypeCheck() error {
p.Lock() p.Lock()
defer p.Unlock() defer p.Unlock()
// If type checking has already been performed alreadyTypeChecked := p.typesInfo != nil || p.typesPkg != nil
// skip it. if alreadyTypeChecked {
if p.typesInfo != nil || p.typesPkg != nil {
return nil return nil
} }
config := &types.Config{ config := &types.Config{
// By setting a no-op error reporter, the type checker does as much work as possible. // By setting a no-op error reporter, the type checker does as much work as possible.
Error: func(error) {}, Error: func(error) {},

View File

@@ -17,11 +17,6 @@ type Rule interface {
Apply(*File, Arguments) []Failure Apply(*File, Arguments) []Failure
} }
// AbstractRule defines an abstract rule.
type AbstractRule struct {
Failures []Failure
}
// ToFailurePosition returns the failure position. // ToFailurePosition returns the failure position.
func ToFailurePosition(start, end token.Pos, file *File) FailurePosition { func ToFailurePosition(start, end token.Pos, file *File) FailurePosition {
return FailurePosition{ return FailurePosition{

View File

@@ -19,15 +19,13 @@ func GetLogger() (*log.Logger, error) {
var writer io.Writer var writer io.Writer
var err error var err error
writer = io.Discard // by default, suppress all logging output
debugModeEnabled := os.Getenv("DEBUG") == "1" debugModeEnabled := os.Getenv("DEBUG") == "1"
if debugModeEnabled { if debugModeEnabled {
writer, err = os.Create("revive.log") writer, err = os.Create("revive.log")
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else {
// Suppress all logging output if debug mode is disabled
writer = io.Discard
} }
logger = log.New(writer, "", log.LstdFlags) logger = log.New(writer, "", log.LstdFlags)
@@ -38,7 +36,7 @@ func GetLogger() (*log.Logger, error) {
logger.SetFlags(0) logger.SetFlags(0)
} }
logger.Println("Logger initialised") logger.Println("Logger initialized")
return logger, nil return logger, nil
} }