Skip to content

Commit 2a7b31d

Browse files
MichaelUrmanpolyfloyd
authored andcommitted
Refactor check to switchComparesNonNil()
1 parent 8587396 commit 2a7b31d

File tree

1 file changed

+30
-23
lines changed

1 file changed

+30
-23
lines changed

errorlint/lint.go

+30-23
Original file line numberDiff line numberDiff line change
@@ -189,31 +189,13 @@ func LintErrorComparisons(fset *token.FileSet, info *TypesInfoExt) []Lint {
189189
continue
190190
}
191191

192-
hasErrorCase := false
193-
for _, caseBlock := range switchStmt.Body.List {
194-
caseClause, ok := caseBlock.(*ast.CaseClause)
195-
if !ok {
196-
continue
197-
}
198-
for _, clause := range caseClause.List {
199-
switch clause := clause.(type) {
200-
case nil:
201-
continue // default label is safe
202-
case *ast.Ident:
203-
if clause.Name != "nil" {
204-
hasErrorCase = true
205-
}
206-
}
207-
}
208-
}
209-
if !hasErrorCase {
210-
continue
192+
if switchComparesNonNil(switchStmt) {
193+
lints = append(lints, Lint{
194+
Message: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors",
195+
Pos: switchStmt.Pos(),
196+
})
211197
}
212198

213-
lints = append(lints, Lint{
214-
Message: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors",
215-
Pos: switchStmt.Pos(),
216-
})
217199
}
218200

219201
return lints
@@ -259,6 +241,31 @@ func isNodeInErrorIsFunc(info *TypesInfoExt, node ast.Node) bool {
259241
return true
260242
}
261243

244+
// switchComparesNonNil returns true if one of its clauses compares by value.
245+
func switchComparesNonNil(switchStmt *ast.SwitchStmt) bool {
246+
for _, caseBlock := range switchStmt.Body.List {
247+
caseClause, ok := caseBlock.(*ast.CaseClause)
248+
if !ok {
249+
continue
250+
}
251+
for _, clause := range caseClause.List {
252+
switch clause := clause.(type) {
253+
case nil:
254+
// default label is safe
255+
continue
256+
case *ast.Ident:
257+
// `case nil` is safe
258+
if clause.Name == "nil" {
259+
continue
260+
}
261+
}
262+
// anything else (including an Ident other than nil) isn't safe
263+
return true
264+
}
265+
}
266+
return false
267+
}
268+
262269
func LintErrorTypeAssertions(fset *token.FileSet, info types.Info) []Lint {
263270
lints := []Lint{}
264271

0 commit comments

Comments
 (0)