github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/staticcheck/sa1002/sa1002.go (about)

     1  package sa1002
     2  
     3  import (
     4  	"go/constant"
     5  	"strings"
     6  	"time"
     7  
     8  	"github.com/amarpal/go-tools/analysis/callcheck"
     9  	"github.com/amarpal/go-tools/analysis/lint"
    10  	"github.com/amarpal/go-tools/internal/passes/buildir"
    11  	"github.com/amarpal/go-tools/knowledge"
    12  
    13  	"golang.org/x/tools/go/analysis"
    14  )
    15  
    16  var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{
    17  	Analyzer: &analysis.Analyzer{
    18  		Name:     "SA1002",
    19  		Requires: []*analysis.Analyzer{buildir.Analyzer},
    20  		Run:      callcheck.Analyzer(rules),
    21  	},
    22  	Doc: &lint.Documentation{
    23  		Title:    `Invalid format in \'time.Parse\'`,
    24  		Since:    "2017.1",
    25  		Severity: lint.SeverityError,
    26  		MergeIf:  lint.MergeIfAny,
    27  	},
    28  })
    29  
    30  var Analyzer = SCAnalyzer.Analyzer
    31  
    32  var rules = map[string]callcheck.Check{
    33  	"time.Parse": func(call *callcheck.Call) {
    34  		arg := call.Args[knowledge.Arg("time.Parse.layout")]
    35  		if c := callcheck.ExtractConstExpectKind(arg.Value, constant.String); c != nil {
    36  			s := constant.StringVal(c.Value)
    37  			s = strings.Replace(s, "_", " ", -1)
    38  			s = strings.Replace(s, "Z", "-", -1)
    39  			_, err := time.Parse(s, s)
    40  			if err != nil {
    41  				arg.Invalid(err.Error())
    42  			}
    43  		}
    44  	},
    45  }