Skip to content

Commit

Permalink
refactor: fix linting issues (#1188)
Browse files Browse the repository at this point in the history
* refactor: fix thelper issues

test/utils_test.go:19:6   thelper  test helper function should start from t.Helper()
test/utils_test.go:42:6   thelper  test helper function should start from t.Helper()
test/utils_test.go:63:6   thelper  test helper function should start from t.Helper()
test/utils_test.go:146:6  thelper  test helper function should start from t.Helper()

* refactor: fix govet issues

rule/error_strings.go:50:21  govet  printf: non-constant format string in call to fmt.Errorf

* refactor: fix gosimple issue

rule/bare_return.go:52:9  gosimple  S1016: should convert w (type lintBareReturnRule) to bareReturnFinder instead of using struct literal

* refactor: fix errorlint issues

lint/filefilter.go:70:86    errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
lint/filefilter.go:113:104  errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
lint/filefilter.go:125:89   errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
lint/linter.go:166:72       errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
lint/linter.go:171:73       errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
config/config.go:174:57     errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors
config/config.go:179:64     errorlint  non-wrapping format verb for fmt.Errorf. Use `%w` to format errors

* refactor: fix revive issue about comment spacing

cli/main.go:31:2 revive comment-spacings: no space between comment delimiter and comment text

* refactor: fix revive issue about unused-receiver

revivelib/core_test.go:77:7                     revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _
revivelib/core_test.go:81:7                     revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _
rule/context_as_argument.go:76:7                revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _
rule/var_naming.go:73:7                         revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _
rule/modifies_value_receiver.go:59:7            revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _
rule/filename_format.go:43:7                    revive       unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _

* refactor: fix revive issues about unused-parameter

revivelib/core_test.go:81:24                    revive       unused-parameter: parameter 'file' seems to be unused, consider removing or renaming it as _
revivelib/core_test.go:81:41                    revive       unused-parameter: parameter 'arguments' seems to be unused, consider removing or renaming it as _

* refactor: fix gocritic issues about commentedOutCode

test/utils_test.go:119:5                       gocritic  commentedOutCode: may want to remove commented-out code
rule/unreachable_code.go:65:3                  gocritic  commentedOutCode: may want to remove commented-out code
  • Loading branch information
ccoVeille authored Dec 12, 2024
1 parent 4dd63ef commit 3421eae
Show file tree
Hide file tree
Showing 13 changed files with 29 additions and 21 deletions.
2 changes: 1 addition & 1 deletion cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ var (
commit = defaultCommit
date = defaultDate
builtBy = defaultBuilder
//AppFs is used to operations related with user config files
// AppFs is used to operations related with user config files
AppFs = afero.NewOsFs()
)

Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,12 @@ func parseConfig(path string, config *lint.Config) error {
}
err = toml.Unmarshal(file, config)
if err != nil {
return fmt.Errorf("cannot parse the config file: %v", err)
return fmt.Errorf("cannot parse the config file: %w", err)
}
for k, r := range config.Rules {
err := r.Initialize()
if err != nil {
return fmt.Errorf("error in config of rule [%s] : [%v]", k, err)
return fmt.Errorf("error in config of rule [%s] : [%w]", k, err)
}
config.Rules[k] = r
}
Expand Down
14 changes: 8 additions & 6 deletions lint/filefilter.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,21 @@ func (ff *FileFilter) MatchFileName(name string) bool {
return ff.rx.MatchString(name)
}

var fileFilterInvalidGlobRegexp = regexp.MustCompile(`[^/]\*\*[^/]`)
var escapeRegexSymbols = ".+{}()[]^$"
var (
fileFilterInvalidGlobRegexp = regexp.MustCompile(`[^/]\*\*[^/]`)
escapeRegexSymbols = ".+{}()[]^$"
)

func (ff *FileFilter) prepareRegexp() error {
var err error
var src = ff.raw
src := ff.raw
if src == "TEST" {
src = "~_test\\.go"
}
if strings.HasPrefix(src, "~") {
ff.rx, err = regexp.Compile(src[1:])
if err != nil {
return fmt.Errorf("invalid file filter [%s], regexp compile error: [%v]", ff.raw, err)
return fmt.Errorf("invalid file filter [%s], regexp compile error: [%w]", ff.raw, err)
}
return nil
}
Expand Down Expand Up @@ -110,7 +112,7 @@ func (ff *FileFilter) prepareRegexp() error {
rxBuild.WriteByte('$')
ff.rx, err = regexp.Compile(rxBuild.String())
if err != nil {
return fmt.Errorf("invalid file filter [%s], regexp compile error after glob expand: [%v]", ff.raw, err)
return fmt.Errorf("invalid file filter [%s], regexp compile error after glob expand: [%w]", ff.raw, err)
}
return nil
}
Expand All @@ -122,7 +124,7 @@ func (ff *FileFilter) prepareRegexp() error {
fillRx = "^" + fillRx + "$"
ff.rx, err = regexp.Compile(fillRx)
if err != nil {
return fmt.Errorf("invalid file filter [%s], regexp compile full path: [%v]", ff.raw, err)
return fmt.Errorf("invalid file filter [%s], regexp compile full path: [%w]", ff.raw, err)
}
return nil
}
4 changes: 2 additions & 2 deletions lint/linter.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,12 @@ func detectGoMod(dir string) (rootDir string, ver *goversion.Version, err error)

mod, err := os.ReadFile(modFileName)
if err != nil {
return "", nil, fmt.Errorf("failed to read %q, got %v", modFileName, err)
return "", nil, fmt.Errorf("failed to read %q, got %w", modFileName, err)
}

modAst, err := modfile.ParseLax(modFileName, mod, nil)
if err != nil {
return "", nil, fmt.Errorf("failed to parse %q, got %v", modFileName, err)
return "", nil, fmt.Errorf("failed to parse %q, got %w", modFileName, err)
}

if modAst.Go == nil {
Expand Down
4 changes: 2 additions & 2 deletions revivelib/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ func TestReviveFormat(t *testing.T) {

type mockRule struct{}

func (r *mockRule) Name() string {
func (*mockRule) Name() string {
return "mock-rule"
}

func (r *mockRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
func (*mockRule) Apply(_ *lint.File, _ lint.Arguments) []lint.Failure {
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion rule/bare_return.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (w lintBareReturnRule) checkFunc(results *ast.FieldList, body *ast.BlockStm
return // nothing to do
}

brf := bareReturnFinder{w.onFailure}
brf := bareReturnFinder(w)
ast.Walk(brf, body)
}

Expand Down
2 changes: 1 addition & 1 deletion rule/context_as_argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (r *ContextAsArgumentRule) configure(arguments lint.Arguments) error {
return nil
}

func (r *ContextAsArgumentRule) getAllowTypesFromArguments(args lint.Arguments) (map[string]struct{}, error) {
func (*ContextAsArgumentRule) getAllowTypesFromArguments(args lint.Arguments) (map[string]struct{}, error) {
allowTypesBefore := []string{}
if len(args) >= 1 {
argKV, ok := args[0].(map[string]any)
Expand Down
2 changes: 1 addition & 1 deletion rule/error_strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (r *ErrorStringsRule) configure(arguments lint.Arguments) error {
}
}
if len(invalidCustomFunctions) != 0 {
return fmt.Errorf("found invalid custom function: " + strings.Join(invalidCustomFunctions, ","))
return fmt.Errorf("found invalid custom function: %s", strings.Join(invalidCustomFunctions, ","))
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion rule/filename_format.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (r *FilenameFormatRule) Apply(file *lint.File, arguments lint.Arguments) []
}}
}

func (r *FilenameFormatRule) getMsgForNonASCIIChars(str string) string {
func (*FilenameFormatRule) getMsgForNonASCIIChars(str string) string {
result := ""
for _, c := range str {
if c <= unicode.MaxASCII {
Expand Down
2 changes: 1 addition & 1 deletion rule/modifies_value_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (*ModifiesValRecRule) Name() string {
return "modifies-value-receiver"
}

func (r *ModifiesValRecRule) skipType(t ast.Expr, pkg *lint.Package) bool {
func (*ModifiesValRecRule) skipType(t ast.Expr, pkg *lint.Package) bool {
rt := pkg.TypeOf(t)
if rt == nil {
return false
Expand Down
1 change: 0 additions & 1 deletion rule/unreachable_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ func (w lintUnreachableCode) Visit(node ast.Node) ast.Visitor {
}
loop:
for i, stmt := range blk.List[:len(blk.List)-1] {
// println("iterating ", len(blk.List))
next := blk.List[i+1]
if _, ok := next.(*ast.LabeledStmt); ok {
continue // skip if next statement is labeled
Expand Down
2 changes: 1 addition & 1 deletion rule/var_naming.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (r *VarNamingRule) configure(arguments lint.Arguments) error {
return nil
}

func (r *VarNamingRule) applyPackageCheckRules(walker *lintNames) {
func (*VarNamingRule) applyPackageCheckRules(walker *lintNames) {
// Package names need slightly different handling than other names.
if strings.Contains(walker.fileAst.Name.Name, "_") && !strings.HasSuffix(walker.fileAst.Name.Name, "_test") {
walker.onFailure(lint.Failure{
Expand Down
9 changes: 8 additions & 1 deletion test/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
)

func testRule(t *testing.T, filename string, rule lint.Rule, config ...*lint.RuleConfig) {
t.Helper()

baseDir := filepath.Join("..", "testdata", filepath.Dir(filename))
filename = filepath.Base(filename) + ".go"
fullFilePath := filepath.Join(baseDir, filename)
Expand All @@ -40,6 +42,8 @@ func testRule(t *testing.T, filename string, rule lint.Rule, config ...*lint.Rul
}

func assertSuccess(t *testing.T, baseDir string, fi os.FileInfo, rules []lint.Rule, config map[string]lint.RuleConfig) error {
t.Helper()

l := lint.New(os.ReadFile, 0)

filePath := filepath.Join(baseDir, fi.Name())
Expand All @@ -61,6 +65,8 @@ func assertSuccess(t *testing.T, baseDir string, fi os.FileInfo, rules []lint.Ru
}

func assertFailures(t *testing.T, baseDir string, fi os.FileInfo, src []byte, rules []lint.Rule, config map[string]lint.RuleConfig) error {
t.Helper()

l := lint.New(os.ReadFile, 0)

ins := parseInstructions(t, filepath.Join(baseDir, fi.Name()), src)
Expand Down Expand Up @@ -110,7 +116,6 @@ func assertFailures(t *testing.T, baseDir string, fi os.FileInfo, src []byte, ru
copy(failures[i:], failures[i+1:])
failures = failures[:len(failures)-1]

// t.Logf("/%v/ matched at %s:%d", in.Match, fi.Name(), in.Line)
ok = true
break
}
Expand Down Expand Up @@ -144,6 +149,8 @@ type JSONInstruction struct {
// parseInstructions parses instructions from the comments in a Go source file.
// It returns nil if none were parsed.
func parseInstructions(t *testing.T, filename string, src []byte) []instruction {
t.Helper()

fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, src, parser.ParseComments)
if err != nil {
Expand Down

0 comments on commit 3421eae

Please sign in to comment.