|
| 1 | +package rule |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "go/ast" |
| 7 | + "go/token" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/mgechev/revive/lint" |
| 12 | + "github.com/mgechev/revive/logging" |
| 13 | +) |
| 14 | + |
| 15 | +// TimeDateRule lints the way time.Date is used. |
| 16 | +type TimeDateRule struct{} |
| 17 | + |
| 18 | +// Apply applies the rule to given file. |
| 19 | +func (*TimeDateRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure { |
| 20 | + var failures []lint.Failure |
| 21 | + |
| 22 | + onFailure := func(failure lint.Failure) { |
| 23 | + failures = append(failures, failure) |
| 24 | + } |
| 25 | + |
| 26 | + w := &lintTimeDate{file, onFailure} |
| 27 | + |
| 28 | + ast.Walk(w, file.AST) |
| 29 | + return failures |
| 30 | +} |
| 31 | + |
| 32 | +// Name returns the rule name. |
| 33 | +func (*TimeDateRule) Name() string { |
| 34 | + return "time-date" |
| 35 | +} |
| 36 | + |
| 37 | +type lintTimeDate struct { |
| 38 | + file *lint.File |
| 39 | + onFailure func(lint.Failure) |
| 40 | +} |
| 41 | + |
| 42 | +var ( |
| 43 | + // timeDateArgumentNames are the names of the arguments of time.Date |
| 44 | + timeDateArgumentNames = []string{ |
| 45 | + "year", |
| 46 | + "month", |
| 47 | + "day", |
| 48 | + "hour", |
| 49 | + "minute", |
| 50 | + "second", |
| 51 | + "nanosecond", |
| 52 | + "timezone", |
| 53 | + } |
| 54 | + |
| 55 | + // timeDateArity is the number of arguments of time.Date |
| 56 | + timeDateArity = len(timeDateArgumentNames) |
| 57 | +) |
| 58 | + |
| 59 | +func (w lintTimeDate) Visit(n ast.Node) ast.Visitor { |
| 60 | + ce, ok := n.(*ast.CallExpr) |
| 61 | + if !ok || len(ce.Args) != timeDateArity { |
| 62 | + return w |
| 63 | + } |
| 64 | + if !isPkgDot(ce.Fun, "time", "Date") { |
| 65 | + return w |
| 66 | + } |
| 67 | + |
| 68 | + // The last argument is a timezone, the is no need to check it, also it has a different type |
| 69 | + for pos, arg := range ce.Args[:timeDateArity-1] { |
| 70 | + bl, ok := arg.(*ast.BasicLit) |
| 71 | + if !ok { |
| 72 | + continue |
| 73 | + } |
| 74 | + |
| 75 | + replacedValue, err := parseDecimalInteger(bl) |
| 76 | + if err == nil { |
| 77 | + continue |
| 78 | + } |
| 79 | + |
| 80 | + confidence := 0.8 // default confidence |
| 81 | + errMessage := err.Error() |
| 82 | + instructions := fmt.Sprintf("use %s instead of %s", replacedValue, bl.Value) |
| 83 | + if errors.Is(err, errParsedOctal) { |
| 84 | + switch { |
| 85 | + case errors.Is(err, errParsedOctalWithZero): |
| 86 | + // people are allowed to use 00, 01, 02, 03, 04, 05, 06, and 07 |
| 87 | + confidence = 0.5 |
| 88 | + |
| 89 | + case errors.Is(err, errParsedOctalWithPaddingZeroes): |
| 90 | + confidence = 1 // this is a clear mistake |
| 91 | + // example with 000123456 (octal) is about 123456 or 42798 ? |
| 92 | + |
| 93 | + strippedValue := strings.TrimLeft(bl.Value, "0") |
| 94 | + if strippedValue == "" { |
| 95 | + // avoid issue with 00000000 |
| 96 | + strippedValue = "0" |
| 97 | + } |
| 98 | + |
| 99 | + if strippedValue != replacedValue { |
| 100 | + instructions = fmt.Sprintf( |
| 101 | + "choose between %s and %s (decimal value of %s octal value)", |
| 102 | + strippedValue, replacedValue, strippedValue, |
| 103 | + ) |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + w.onFailure(lint.Failure{ |
| 109 | + Category: "time", |
| 110 | + Node: bl, |
| 111 | + Confidence: confidence, |
| 112 | + Failure: fmt.Sprintf( |
| 113 | + "use decimal digits for time.Date %s argument: %s found: %s", |
| 114 | + timeDateArgumentNames[pos], errMessage, instructions), |
| 115 | + }) |
| 116 | + } |
| 117 | + |
| 118 | + return w |
| 119 | +} |
| 120 | + |
| 121 | +var ( |
| 122 | + errParsedOctal = errors.New("octal notation") |
| 123 | + errParsedOctalWithZero = fmt.Errorf("%w with leading zero", errParsedOctal) |
| 124 | + errParsedOctalWithPaddingZeroes = fmt.Errorf("%w with padding zeroes", errParsedOctal) |
| 125 | + errParsedHexadecimal = errors.New("hexadecimal notation") |
| 126 | + errParseBinary = errors.New("binary notation") |
| 127 | + errParsedFloat = errors.New("float literal") |
| 128 | + errParsedExponential = errors.New("exponential notation") |
| 129 | + errParsedAlternative = errors.New("alternative notation") |
| 130 | +) |
| 131 | + |
| 132 | +func parseDecimalInteger(bl *ast.BasicLit) (string, error) { |
| 133 | + currentValue := strings.ToLower(bl.Value) |
| 134 | + |
| 135 | + switch currentValue { |
| 136 | + case "0": |
| 137 | + // 0 is a valid value for all the arguments |
| 138 | + // let's skip it |
| 139 | + return bl.Value, nil |
| 140 | + // people can use 00, 01, 02, 03, 04, 05, 06, 07, if they want |
| 141 | + case "00", "01", "02", "03", "04", "05", "06", "07": |
| 142 | + return bl.Value[1:], errParsedOctalWithZero |
| 143 | + } |
| 144 | + |
| 145 | + loggerError := func(message string, err error) { |
| 146 | + logger, errLogger := logging.GetLogger() |
| 147 | + if errLogger != nil { |
| 148 | + // this is not supposed to happen |
| 149 | + return |
| 150 | + } |
| 151 | + if err != nil { |
| 152 | + logger = logger.With( |
| 153 | + "error", err.Error(), |
| 154 | + ) |
| 155 | + } |
| 156 | + logger.With( |
| 157 | + "value", bl.Value, |
| 158 | + "kind", bl.Kind.String(), |
| 159 | + ).Error(message) |
| 160 | + } |
| 161 | + |
| 162 | + switch bl.Kind { |
| 163 | + case token.FLOAT: |
| 164 | + // someone used a float literal, while they should have used a integer literal |
| 165 | + parsedValue, err := strconv.ParseFloat(currentValue, 64) |
| 166 | + if err != nil { |
| 167 | + // this is not supposed to happen |
| 168 | + // but let's be defensive and log it |
| 169 | + loggerError("failed to parse number as float", err) |
| 170 | + |
| 171 | + // and return the original value, as if everything was ok |
| 172 | + return bl.Value, nil |
| 173 | + } |
| 174 | + |
| 175 | + // this will convert back the number to a string |
| 176 | + cleanedValue := strconv.FormatFloat(parsedValue, 'f', -1, 64) |
| 177 | + if strings.Contains(currentValue, "e") { |
| 178 | + return cleanedValue, errParsedExponential |
| 179 | + } |
| 180 | + |
| 181 | + return cleanedValue, errParsedFloat |
| 182 | + |
| 183 | + case token.INT: |
| 184 | + // we expect this format |
| 185 | + |
| 186 | + default: |
| 187 | + // this is not supposed to happen |
| 188 | + // but let's be defensive and log it |
| 189 | + loggerError("unexpected kind of literal", nil) |
| 190 | + |
| 191 | + // let's be defensive and return nil |
| 192 | + return bl.Value, nil |
| 193 | + } |
| 194 | + |
| 195 | + // Parse the number with base=0 that allows to accept all number formats and base |
| 196 | + parsedValue, err := strconv.ParseInt(currentValue, 0, 64) |
| 197 | + if err != nil { |
| 198 | + // this is not supposed to happen |
| 199 | + // but let's be defensive and log it |
| 200 | + |
| 201 | + loggerError("failed to parse number as integer", err) |
| 202 | + |
| 203 | + // and return the original value, as if everything was ok |
| 204 | + return bl.Value, nil |
| 205 | + } |
| 206 | + |
| 207 | + cleanedValue := strconv.FormatInt(parsedValue, 10) |
| 208 | + |
| 209 | + // The number is not in decimal notation |
| 210 | + // let's forge a failure message |
| 211 | + |
| 212 | + // Let's figure out the notation |
| 213 | + switch { |
| 214 | + case strings.HasPrefix(currentValue, "0b"): |
| 215 | + return cleanedValue, errParseBinary |
| 216 | + case strings.HasPrefix(currentValue, "0x"): |
| 217 | + return cleanedValue, errParsedHexadecimal |
| 218 | + case strings.HasPrefix(currentValue, "0"): |
| 219 | + // this matches both "0" and "0o" octal notation. |
| 220 | + |
| 221 | + if strings.HasPrefix(currentValue, "00") { |
| 222 | + // 00123456 (octal) is about 123456 or 42798 ? |
| 223 | + return cleanedValue, errParsedOctalWithPaddingZeroes |
| 224 | + } |
| 225 | + |
| 226 | + // 0006 is a valid octal notation, but we can use 6 instead. |
| 227 | + return cleanedValue, errParsedOctal |
| 228 | + } |
| 229 | + |
| 230 | + // anything else uses decimal notation |
| 231 | + // but let's validate it to be sure |
| 232 | + |
| 233 | + // convert back the number to a string, and compare it with the original one |
| 234 | + formattedValue := strconv.FormatInt(parsedValue, 10) |
| 235 | + if formattedValue != currentValue { |
| 236 | + // this can catch some edge cases like: 1_0 ... |
| 237 | + return cleanedValue, errParsedAlternative |
| 238 | + } |
| 239 | + |
| 240 | + return bl.Value, nil |
| 241 | +} |
0 commit comments