-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy patherror_strings.go
193 lines (174 loc) · 4.45 KB
/
error_strings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package rule
import (
"fmt"
"go/ast"
"go/token"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/mgechev/revive/lint"
)
// ErrorStringsRule lints error strings.
type ErrorStringsRule struct {
errorFunctions map[string]map[string]struct{}
}
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *ErrorStringsRule) Configure(arguments lint.Arguments) error {
r.errorFunctions = map[string]map[string]struct{}{
"fmt": {
"Errorf": {},
},
"errors": {
"Errorf": {},
"WithMessage": {},
"Wrap": {},
"New": {},
"WithMessagef": {},
"Wrapf": {},
},
}
var invalidCustomFunctions []string
for _, argument := range arguments {
if functionName, ok := argument.(string); ok {
fields := strings.Split(strings.TrimSpace(functionName), ".")
if len(fields) != 2 || len(fields[0]) == 0 || len(fields[1]) == 0 {
invalidCustomFunctions = append(invalidCustomFunctions, functionName)
continue
}
r.errorFunctions[fields[0]] = map[string]struct{}{fields[1]: {}}
}
}
if len(invalidCustomFunctions) != 0 {
return fmt.Errorf("found invalid custom function: %s", strings.Join(invalidCustomFunctions, ","))
}
return nil
}
// Apply applies the rule to given file.
func (r *ErrorStringsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
fileAst := file.AST
walker := lintErrorStrings{
file: file,
fileAst: fileAst,
errorFunctions: r.errorFunctions,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, fileAst)
return failures
}
// Name returns the rule name.
func (*ErrorStringsRule) Name() string {
return "error-strings"
}
type lintErrorStrings struct {
file *lint.File
fileAst *ast.File
errorFunctions map[string]map[string]struct{}
onFailure func(lint.Failure)
}
// Visit browses the AST
func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
ce, ok := n.(*ast.CallExpr)
if !ok {
return w
}
if len(ce.Args) < 1 {
return w
}
// expression matches the known pkg.function
ok = w.match(ce)
if !ok {
return w
}
str, ok := w.getMessage(ce)
if !ok {
return w
}
s, _ := strconv.Unquote(str.Value) // can assume well-formed Go
if s == "" {
return w
}
clean, conf := lintErrorString(s)
if clean {
return w
}
w.onFailure(lint.Failure{
Node: str,
Confidence: conf,
Category: lint.FailureCategoryErrors,
Failure: "error strings should not be capitalized or end with punctuation or a newline",
})
return w
}
// match returns true if the expression corresponds to the known pkg.function
// i.e.: errors.Wrap
func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
sel, ok := expr.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
// retrieve the package
id, ok := sel.X.(*ast.Ident)
if !ok {
return false
}
functions, ok := w.errorFunctions[id.Name]
if !ok {
return false
}
// retrieve the function
_, ok = functions[sel.Sel.Name]
return ok
}
// getMessage returns the message depending on its position
// returns false if the cast is unsuccessful
func (w lintErrorStrings) getMessage(expr *ast.CallExpr) (s *ast.BasicLit, success bool) {
str, ok := w.checkArg(expr, 0)
if ok {
return str, true
}
if len(expr.Args) < 2 {
return s, false
}
str, ok = w.checkArg(expr, 1)
if !ok {
return s, false
}
return str, true
}
func (lintErrorStrings) checkArg(expr *ast.CallExpr, arg int) (s *ast.BasicLit, success bool) {
str, ok := expr.Args[arg].(*ast.BasicLit)
if !ok {
return s, false
}
if str.Kind != token.STRING {
return s, false
}
return str, true
}
func lintErrorString(s string) (isClean bool, conf float64) {
const basicConfidence = 0.8
const capConfidence = basicConfidence - 0.2
first, firstN := utf8.DecodeRuneInString(s)
last, _ := utf8.DecodeLastRuneInString(s)
if last == '.' || last == ':' || last == '!' || last == '\n' {
return false, basicConfidence
}
if unicode.IsUpper(first) {
// People use proper nouns and exported Go identifiers in error strings,
// so decrease the confidence of warnings for capitalization.
if len(s) <= firstN {
return false, capConfidence
}
// Flag strings starting with something that doesn't look like an initialism.
if second, _ := utf8.DecodeRuneInString(s[firstN:]); !unicode.IsUpper(second) {
return false, capConfidence
}
}
return true, 0
}