Skip to content

Commit 02b6b93

Browse files
committed
feature: Add nil timezone handling detection to time-date rule
1 parent a56cf72 commit 02b6b93

File tree

3 files changed

+53
-1
lines changed

3 files changed

+53
-1
lines changed

rule/time_date.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,18 @@ func (w lintTimeDate) Visit(n ast.Node) ast.Visitor {
6565
return w
6666
}
6767

68-
// The last argument is a timezone, there is no need to check it, also it has a different type
68+
// The last argument is a timezone, check it
69+
tzArg := ce.Args[timeDateArity-1]
70+
if tz, ok := tzArg.(*ast.Ident); ok && tz.Name == "nil" {
71+
w.onFailure(lint.Failure{
72+
Category: "time",
73+
Node: tzArg,
74+
Confidence: 1,
75+
Failure: "time.Date timezone argument cannot be nil, it would panic on runtime",
76+
})
77+
}
78+
79+
// All the other arguments should be decimal integers.
6980
for pos, arg := range ce.Args[:timeDateArity-1] {
7081
bl, ok := arg.(*ast.BasicLit)
7182
if !ok {

test/time_date_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ import (
88

99
func TestTimeDate(t *testing.T) {
1010
testRule(t, "time_date_decimal_literal", &rule.TimeDateRule{})
11+
testRule(t, "time_date_nil_timezone", &rule.TimeDateRule{})
1112
}

testdata/time_date_nil_timezone.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package pkg
2+
3+
import "time"
4+
5+
var (
6+
// a nil timezone will panic at runtime
7+
// this is an invalid usage
8+
// it should be reported as an error
9+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, nil) // MATCH /time.Date timezone argument cannot be nil, it would panic on runtime/
10+
)
11+
12+
func _() {
13+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, nil) // MATCH /time.Date timezone argument cannot be nil, it would panic on runtime/
14+
}
15+
16+
func _() {
17+
// this is a valid usage
18+
// it should not be reported as an error
19+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, time.UTC)
20+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, time.Local)
21+
22+
loc := time.LoadLocation("Europe/Paris")
23+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, loc)
24+
25+
loc := time.FixedZone("UTC-8", -8*60*60)
26+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, loc)
27+
28+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, time.FixedZone("UTC-8", -8*60*60))
29+
}
30+
31+
// this would be difficult to detect
32+
// and are for now not reported
33+
// even if they panic at runtime
34+
func _() {
35+
var loc *time.Location
36+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, loc)
37+
38+
loc, _ = time.LoadLocation("whatever")
39+
_ = time.Date(2023, 1, 2, 3, 4, 5, 0, loc)
40+
}

0 commit comments

Comments
 (0)