1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-24 08:32:22 +02:00
revive/rule/indent-error-flow.go

77 lines
1.8 KiB
Go
Raw Normal View History

2018-01-22 04:04:41 +02:00
package rule
2017-08-28 01:57:16 +02:00
import (
"go/ast"
"go/token"
2018-01-25 01:44:03 +02:00
"github.com/mgechev/revive/lint"
2017-08-28 01:57:16 +02:00
)
2018-05-27 01:14:36 +02:00
// IndentErrorFlowRule lints given else constructs.
type IndentErrorFlowRule struct{}
2017-08-28 01:57:16 +02:00
// Apply applies the rule to given file.
2018-05-27 01:14:36 +02:00
func (r *IndentErrorFlowRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
2018-01-25 01:44:03 +02:00
var failures []lint.Failure
2017-11-20 05:38:28 +02:00
2018-01-25 01:44:03 +02:00
onFailure := func(failure lint.Failure) {
2017-11-20 03:58:28 +02:00
failures = append(failures, failure)
2017-11-20 05:38:28 +02:00
}
w := lintElse{make(map[*ast.IfStmt]bool), onFailure}
2018-01-22 04:48:51 +02:00
ast.Walk(w, file.AST)
2017-11-20 03:58:28 +02:00
return failures
2017-08-28 01:57:16 +02:00
}
2017-11-20 03:18:16 +02:00
// Name returns the rule name.
2018-05-27 01:14:36 +02:00
func (r *IndentErrorFlowRule) Name() string {
return "indent-error-flow"
}
2017-11-20 05:38:28 +02:00
type lintElse struct {
ignore map[*ast.IfStmt]bool
2018-01-25 01:44:03 +02:00
onFailure func(lint.Failure)
2017-11-20 05:38:28 +02:00
}
2017-08-28 01:57:16 +02:00
2017-11-20 05:38:28 +02:00
func (w lintElse) Visit(node ast.Node) ast.Visitor {
ifStmt, ok := node.(*ast.IfStmt)
if !ok || ifStmt.Else == nil {
return w
}
if w.ignore[ifStmt] {
return w
}
if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok {
w.ignore[elseif] = true
return w
}
if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok {
// only care about elses without conditions
return w
}
if len(ifStmt.Body.List) == 0 {
return w
}
shortDecl := false // does the if statement have a ":=" initialization statement?
if ifStmt.Init != nil {
if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE {
shortDecl = true
2017-11-20 03:18:16 +02:00
}
2017-11-20 05:38:28 +02:00
}
lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1]
if _, ok := lastStmt.(*ast.ReturnStmt); ok {
extra := ""
if shortDecl {
extra = " (move short variable declaration to its own line if necessary)"
2017-08-28 01:57:16 +02:00
}
2018-01-25 01:44:03 +02:00
w.onFailure(lint.Failure{
2018-01-25 20:35:27 +02:00
Confidence: 1,
Node: ifStmt.Else,
Category: "indent",
URL: "#indent-error-flow",
Failure: "if block ends with a return statement, so drop this else and outdent its block" + extra,
2017-11-20 05:38:28 +02:00
})
2017-08-28 01:57:16 +02:00
}
2017-11-20 05:38:28 +02:00
return w
2017-08-28 01:57:16 +02:00
}