2018-06-26 22:21:03 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"go/ast"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DeepExitRule lints program exit at functions other than main or init.
|
|
|
|
type DeepExitRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
2018-09-23 00:27:22 +02:00
|
|
|
func (r *DeepExitRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
2018-06-26 22:21:03 +02:00
|
|
|
var failures []lint.Failure
|
|
|
|
onFailure := func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
}
|
|
|
|
|
2022-03-02 09:24:55 +02:00
|
|
|
exitFunctions := map[string]map[string]bool{
|
2021-05-31 21:54:58 +02:00
|
|
|
"os": {"Exit": true},
|
|
|
|
"syscall": {"Exit": true},
|
|
|
|
"log": {
|
2018-06-26 22:21:03 +02:00
|
|
|
"Fatal": true,
|
|
|
|
"Fatalf": true,
|
|
|
|
"Fatalln": true,
|
|
|
|
"Panic": true,
|
|
|
|
"Panicf": true,
|
|
|
|
"Panicln": true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2020-01-08 00:46:21 +02:00
|
|
|
w := lintDeepExit{onFailure, exitFunctions, file.IsTest()}
|
2018-06-26 22:21:03 +02:00
|
|
|
ast.Walk(w, file.AST)
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
|
|
|
func (r *DeepExitRule) Name() string {
|
|
|
|
return "deep-exit"
|
|
|
|
}
|
|
|
|
|
|
|
|
type lintDeepExit struct {
|
|
|
|
onFailure func(lint.Failure)
|
|
|
|
exitFunctions map[string]map[string]bool
|
2020-01-08 00:46:21 +02:00
|
|
|
isTestFile bool
|
2018-06-26 22:21:03 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w lintDeepExit) Visit(node ast.Node) ast.Visitor {
|
2020-01-08 00:46:21 +02:00
|
|
|
if fd, ok := node.(*ast.FuncDecl); ok {
|
|
|
|
if w.mustIgnore(fd) {
|
|
|
|
return nil // skip analysis of this function
|
|
|
|
}
|
2018-06-26 22:21:03 +02:00
|
|
|
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
se, ok := node.(*ast.ExprStmt)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
ce, ok := se.X.(*ast.CallExpr)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
fc, ok := ce.Fun.(*ast.SelectorExpr)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
id, ok := fc.X.(*ast.Ident)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
fn := fc.Sel.Name
|
|
|
|
pkg := id.Name
|
|
|
|
if w.exitFunctions[pkg] != nil && w.exitFunctions[pkg][fn] { // it's a call to an exit function
|
|
|
|
w.onFailure(lint.Failure{
|
|
|
|
Confidence: 1,
|
|
|
|
Node: ce,
|
|
|
|
Category: "bad practice",
|
|
|
|
Failure: fmt.Sprintf("calls to %s.%s only in main() or init() functions", pkg, fn),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
2020-01-08 00:46:21 +02:00
|
|
|
func (w *lintDeepExit) mustIgnore(fd *ast.FuncDecl) bool {
|
2018-06-26 22:21:03 +02:00
|
|
|
fn := fd.Name.Name
|
2020-01-08 00:46:21 +02:00
|
|
|
|
|
|
|
return fn == "init" || fn == "main" || (w.isTestFile && fn == "TestMain")
|
2018-06-26 22:21:03 +02:00
|
|
|
}
|