1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-28 08:49:11 +02:00
revive/rule/indent-error-flow.go
Miles Delahunty 4bb48df5d2
refactor: extract shared code for linting if-else chains (#821)
* refactor: extract shared code for linting if-else chains

The rules "early-return", "indent-error-flow" and
"superfluous-else" have a similar structure. This
moves the common logic for classifying if-else chains
to a common package.

A few side benefits:
- "early-return" now handles os.Exit/log.Panicf/etc
- "superfluous-else" now handles (builtin) panic
- "superfluous-else" and "indent-error-flow" now handle if/else
  chains with 2+ "if" branches

* internal/ifelse: style fixes, renames, spelling
2023-05-17 13:51:35 +02:00

41 lines
1.0 KiB
Go

package rule
import (
"github.com/mgechev/revive/internal/ifelse"
"github.com/mgechev/revive/lint"
)
// IndentErrorFlowRule lints given else constructs.
type IndentErrorFlowRule struct{}
// Apply applies the rule to given file.
func (e *IndentErrorFlowRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
return ifelse.Apply(e, file.AST, ifelse.TargetElse)
}
// Name returns the rule name.
func (*IndentErrorFlowRule) Name() string {
return "indent-error-flow"
}
// CheckIfElse evaluates the rule against an ifelse.Chain.
func (e *IndentErrorFlowRule) CheckIfElse(chain ifelse.Chain) (failMsg string) {
if !chain.If.Deviates() {
// this rule only applies if the if-block deviates control flow
return
}
if chain.HasPriorNonDeviating {
// if we de-indent the "else" block then a previous branch
// might flow into it, affecting program behaviour
return
}
if !chain.If.Returns() {
// avoid overlapping with superfluous-else
return
}
return "if block ends with a return statement, so drop this else and outdent its block"
}