|
| 1 | +// Copyright 2022 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// Package timeformat defines an Analyzer that checks for the use |
| 6 | +// of time.Format or time.Parse calls with a bad format. |
| 7 | +package timeformat |
| 8 | + |
| 9 | +import ( |
| 10 | + "go/ast" |
| 11 | + "go/constant" |
| 12 | + "go/types" |
| 13 | + "strings" |
| 14 | + |
| 15 | + "golang.org/x/tools/go/analysis" |
| 16 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 17 | + "golang.org/x/tools/go/ast/inspector" |
| 18 | + "golang.org/x/tools/go/types/typeutil" |
| 19 | +) |
| 20 | + |
| 21 | +const Doc = `check for calls of (time.Time).Format or time.Parse with 2006-02-01 |
| 22 | +
|
| 23 | +The timeformat checker looks for time formats with the 2006-02-01 (yyyy-dd-mm) |
| 24 | +format. Internationally, "yyyy-dd-mm" does not occur in common calendar date |
| 25 | +standards, and so it is more likely that 2006-01-02 (yyyy-mm-dd) was intended. |
| 26 | +` |
| 27 | + |
| 28 | +var Analyzer = &analysis.Analyzer{ |
| 29 | + Name: "timeformat", |
| 30 | + Doc: Doc, |
| 31 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 32 | + Run: run, |
| 33 | +} |
| 34 | + |
| 35 | +func run(pass *analysis.Pass) (interface{}, error) { |
| 36 | + inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 37 | + |
| 38 | + nodeFilter := []ast.Node{ |
| 39 | + (*ast.CallExpr)(nil), |
| 40 | + } |
| 41 | + inspect.Preorder(nodeFilter, func(n ast.Node) { |
| 42 | + call := n.(*ast.CallExpr) |
| 43 | + fn, ok := typeutil.Callee(pass.TypesInfo, call).(*types.Func) |
| 44 | + if !ok { |
| 45 | + return |
| 46 | + } |
| 47 | + if fn.Pkg().Path() != "time" { |
| 48 | + return |
| 49 | + } |
| 50 | + if name := fn.Name(); name != "Format" && name != "Parse" { |
| 51 | + return |
| 52 | + } |
| 53 | + if len(call.Args) > 0 && isBadFormat(pass.TypesInfo, call.Args[0]) { |
| 54 | + pass.ReportRangef(call, "2006-02-01 should be 2006-01-02") |
| 55 | + } |
| 56 | + }) |
| 57 | + return nil, nil |
| 58 | +} |
| 59 | + |
| 60 | +// isBadFormat return true when e is a string containing 2006-02-01. |
| 61 | +func isBadFormat(info *types.Info, e ast.Expr) bool { |
| 62 | + tv, ok := info.Types[e] |
| 63 | + if !ok { // no type info, assume good |
| 64 | + return false |
| 65 | + } |
| 66 | + |
| 67 | + t, ok := tv.Type.(*types.Basic) |
| 68 | + if !ok || t.Info()&types.IsString == 0 { |
| 69 | + return false |
| 70 | + } |
| 71 | + |
| 72 | + if tv.Value == nil { |
| 73 | + return false |
| 74 | + } |
| 75 | + |
| 76 | + return strings.Contains(constant.StringVal(tv.Value), "2006-02-01") |
| 77 | +} |
0 commit comments