| 1 |
package s1012 |
| 2 |
|
| 3 |
import ( |
| 4 |
"honnef.co/go/tools/analysis/code" |
| 5 |
"honnef.co/go/tools/analysis/edit" |
| 6 |
"honnef.co/go/tools/analysis/facts/generated" |
| 7 |
"honnef.co/go/tools/analysis/lint" |
| 8 |
"honnef.co/go/tools/analysis/report" |
| 9 |
"honnef.co/go/tools/pattern" |
| 10 |
|
| 11 |
"golang.org/x/tools/go/analysis" |
| 12 |
) |
| 13 |
|
| 14 |
var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{ |
| 15 |
Analyzer: &analysis.Analyzer{ |
| 16 |
Name: "S1012", |
| 17 |
Run: run, |
| 18 |
Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...), |
| 19 |
}, |
| 20 |
Doc: &lint.RawDocumentation{ |
| 21 |
Title: `Replace \'time.Now().Sub(x)\' with \'time.Since(x)\'`, |
| 22 |
Text: `The \'time.Since\' helper has the same effect as using \'time.Now().Sub(x)\' |
| 23 |
but is easier to read.`, |
| 24 |
Before: `time.Now().Sub(x)`, |
| 25 |
After: `time.Since(x)`, |
| 26 |
Since: "2017.1", |
| 27 |
MergeIf: lint.MergeIfAny, |
| 28 |
}, |
| 29 |
}) |
| 30 |
|
| 31 |
var Analyzer = SCAnalyzer.Analyzer |
| 32 |
|
| 33 |
var ( |
| 34 |
checkTimeSinceQ = pattern.MustParse(`(CallExpr (SelectorExpr (CallExpr (Symbol "time.Now") []) (Symbol "(time.Time).Sub")) [arg])`) |
| 35 |
checkTimeSinceR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Since")) [arg])`) |
| 36 |
) |
| 37 |
|
| 38 |
func run(pass *analysis.Pass) (any, error) { |
| 39 |
for node, m := range code.Matches(pass, checkTimeSinceQ) { |
| 40 |
edits := code.EditMatch(pass, node, m, checkTimeSinceR) |
| 41 |
report.Report(pass, node, "should use time.Since instead of time.Now().Sub", |
| 42 |
report.FilterGenerated(), |
| 43 |
report.Fixes(edit.Fix("Replace with call to time.Since", edits...))) |
| 44 |
} |
| 45 |
return nil, nil |
| 46 |
} |