Skip to content

Commit

Permalink
refactor: code cleanup (#1177)
Browse files Browse the repository at this point in the history
  • Loading branch information
chavacava authored Dec 8, 2024
1 parent 5c2aadf commit f6a3820
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 60 deletions.
7 changes: 4 additions & 3 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
}

Expand Down
6 changes: 3 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
26 changes: 14 additions & 12 deletions formatter/friendly.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"sort"
"strings"

"github.com/fatih/color"
"github.com/mgechev/revive/lint"
Expand Down Expand Up @@ -32,45 +33,46 @@ 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
totalWarnings := 0
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) printFriendlyFailure(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 {
Expand Down
8 changes: 4 additions & 4 deletions formatter/plain.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package formatter

import (
"bytes"
"fmt"
"strings"

"github.com/mgechev/revive/lint"
)
Expand All @@ -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
}
7 changes: 4 additions & 3 deletions formatter/stylish.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "", ""
}

Expand Down
8 changes: 4 additions & 4 deletions formatter/unix.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package formatter

import (
"bytes"
"fmt"
"strings"

"github.com/mgechev/revive/lint"
)
Expand All @@ -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
}
34 changes: 18 additions & 16 deletions lint/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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
}
6 changes: 3 additions & 3 deletions lint/linter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
)

Expand Down Expand Up @@ -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
}
}
Expand Down
6 changes: 3 additions & 3 deletions lint/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {},
Expand Down
5 changes: 0 additions & 5 deletions lint/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
6 changes: 2 additions & 4 deletions logging/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -38,7 +36,7 @@ func GetLogger() (*log.Logger, error) {
logger.SetFlags(0)
}

logger.Println("Logger initialised")
logger.Println("Logger initialized")

return logger, nil
}

0 comments on commit f6a3820

Please sign in to comment.