1
0
mirror of https://github.com/mgechev/revive.git synced 2024-12-12 10:44:59 +02:00

refactor (rule/cyclomatic): replace AST walker by iteration over declarations (#1161)

Co-authored-by: chavacava <salvador.cavadini@gmail.com>
This commit is contained in:
chavacava 2024-12-04 17:42:29 +01:00 committed by GitHub
parent 98a6c97664
commit 4b137822ea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -38,18 +38,24 @@ 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
for _, decl := range file.AST.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
walker := lintCyclomatic{
file: file,
complexity: r.maxComplexity,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
c := complexity(fn)
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, r.maxComplexity),
Node: fn,
})
}
}
ast.Walk(walker, fileAst)
return failures
}
@ -58,35 +64,6 @@ 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 {
fn, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
c := complexity(fn)
if c > w.complexity {
w.onFailure(lint.Failure{
Confidence: 1,
Category: "maintenance",
Failure: fmt.Sprintf("function %s has cyclomatic complexity %d (> max enabled %d)",
funcName(fn), c, w.complexity),
Node: fn,
})
}
}
return nil
}
// funcName returns the name representation of a function or method:
// "(Type).Name" for methods or simply "Name" for functions.
func funcName(fn *ast.FuncDecl) string {