src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

s1024.go (1810B)


      1 package s1024
      2 
      3 import (
      4 	"go/ast"
      5 
      6 	"honnef.co/go/tools/analysis/code"
      7 	"honnef.co/go/tools/analysis/edit"
      8 	"honnef.co/go/tools/analysis/facts/generated"
      9 	"honnef.co/go/tools/analysis/lint"
     10 	"honnef.co/go/tools/analysis/report"
     11 	"honnef.co/go/tools/pattern"
     12 
     13 	"golang.org/x/tools/go/analysis"
     14 )
     15 
     16 var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
     17 	Analyzer: &analysis.Analyzer{
     18 		Name:     "S1024",
     19 		Run:      run,
     20 		Requires: append([]*analysis.Analyzer{generated.Analyzer}, code.RequiredAnalyzers...),
     21 	},
     22 	Doc: &lint.RawDocumentation{
     23 		Title: `Replace \'x.Sub(time.Now())\' with \'time.Until(x)\'`,
     24 		Text: `The \'time.Until\' helper has the same effect as using \'x.Sub(time.Now())\'
     25 but is easier to read.`,
     26 		Before:  `x.Sub(time.Now())`,
     27 		After:   `time.Until(x)`,
     28 		Since:   "2017.1",
     29 		MergeIf: lint.MergeIfAny,
     30 	},
     31 })
     32 
     33 var Analyzer = SCAnalyzer.Analyzer
     34 
     35 var (
     36 	checkTimeUntilQ = pattern.MustParse(`(CallExpr (Symbol "(time.Time).Sub") [(CallExpr (Symbol "time.Now") [])])`)
     37 	checkTimeUntilR = pattern.MustParse(`(CallExpr (SelectorExpr (Ident "time") (Ident "Until")) [arg])`)
     38 )
     39 
     40 func run(pass *analysis.Pass) (any, error) {
     41 	for node := range code.Matches(pass, checkTimeUntilQ) {
     42 		if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok {
     43 			r := pattern.NodeToAST(checkTimeUntilR.Root, map[string]any{"arg": sel.X}).(ast.Node)
     44 			report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())",
     45 				report.FilterGenerated(),
     46 				report.MinimumStdlibVersion("go1.8"),
     47 				report.Fixes(edit.Fix("Replace with call to time.Until", edit.ReplaceWithNode(pass.Fset, node, r))))
     48 		} else {
     49 			report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())",
     50 				report.MinimumStdlibVersion("go1.8"),
     51 				report.FilterGenerated())
     52 		}
     53 	}
     54 	return nil, nil
     55 }