mirror of
https://github.com/mgechev/revive.git
synced 2025-01-10 03:17:11 +02:00
4bb48df5d2
* 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
47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package rule
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/mgechev/revive/internal/ifelse"
|
|
"github.com/mgechev/revive/lint"
|
|
)
|
|
|
|
// EarlyReturnRule finds opportunities to reduce nesting by inverting
|
|
// the condition of an "if" block.
|
|
type EarlyReturnRule struct{}
|
|
|
|
// Apply applies the rule to given file.
|
|
func (e *EarlyReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
|
return ifelse.Apply(e, file.AST, ifelse.TargetIf)
|
|
}
|
|
|
|
// Name returns the rule name.
|
|
func (*EarlyReturnRule) Name() string {
|
|
return "early-return"
|
|
}
|
|
|
|
// CheckIfElse evaluates the rule against an ifelse.Chain.
|
|
func (e *EarlyReturnRule) CheckIfElse(chain ifelse.Chain) (failMsg string) {
|
|
if !chain.Else.Deviates() {
|
|
// this rule only applies if the else-block deviates control flow
|
|
return
|
|
}
|
|
|
|
if chain.HasPriorNonDeviating && !chain.If.IsEmpty() {
|
|
// if we de-indent this block then a previous branch
|
|
// might flow into it, affecting program behaviour
|
|
return
|
|
}
|
|
|
|
if chain.If.Deviates() {
|
|
// avoid overlapping with superfluous-else
|
|
return
|
|
}
|
|
|
|
if chain.If.IsEmpty() {
|
|
return fmt.Sprintf("if c { } else { %[1]v } can be simplified to if !c { %[1]v }", chain.Else)
|
|
}
|
|
return fmt.Sprintf("if c { ... } else { %[1]v } can be simplified to if !c { %[1]v } ...", chain.Else)
|
|
}
|