Skip to content

Commit

Permalink
refactor (rule/cyclomatic): replace AST walker by iteration over decl…
Browse files Browse the repository at this point in the history
…arations (#1161)

Co-authored-by: chavacava <salvador.cavadini@gmail.com>
  • Loading branch information
chavacava and chavacava authored Dec 4, 2024
1 parent 98a6c97 commit 4b13782
Showing 1 changed file with 10 additions and 33 deletions.
43 changes: 10 additions & 33 deletions rule/cyclomatic.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,53 +38,30 @@ func (r *CyclomaticRule) Apply(file *lint.File, arguments lint.Arguments) []lint
r.configureOnce.Do(func() { r.configure(arguments) })

var failures []lint.Failure
fileAst := file.AST

walker := lintCyclomatic{
file: file,
complexity: r.maxComplexity,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}

ast.Walk(walker, fileAst)

return failures
}

// Name returns the rule name.
func (*CyclomaticRule) Name() string {
return "cyclomatic"
}

type lintCyclomatic struct {
file *lint.File
complexity int
onFailure func(lint.Failure)
}

func (w lintCyclomatic) Visit(_ ast.Node) ast.Visitor {
f := w.file
for _, decl := range f.AST.Decls {
for _, decl := range file.AST.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}

c := complexity(fn)
if c > w.complexity {
w.onFailure(lint.Failure{
if c > r.maxComplexity {
failures = append(failures, lint.Failure{
Confidence: 1,
Category: "maintenance",
Failure: fmt.Sprintf("function %s has cyclomatic complexity %d (> max enabled %d)",
funcName(fn), c, w.complexity),
funcName(fn), c, r.maxComplexity),
Node: fn,
})
}
}

return nil
return failures
}

// Name returns the rule name.
func (*CyclomaticRule) Name() string {
return "cyclomatic"
}

// funcName returns the name representation of a function or method:
Expand Down

0 comments on commit 4b13782

Please sign in to comment.