diff --git a/private/date/utils.go b/private/date/utils.go index ecbc53daa54d..5e2bdd605c7a 100644 --- a/private/date/utils.go +++ b/private/date/utils.go @@ -4,7 +4,10 @@ // Package date contains various date-related utilities package date -import "time" +import ( + "fmt" + "time" +) // MonthBoundary extract month from the provided date and returns its edges. func MonthBoundary(t time.Time) (time.Time, time.Time) { @@ -21,8 +24,11 @@ func DayBoundary(t time.Time) (time.Time, time.Time) { // PeriodToTime returns time.Time period in format YYYY-MM from string. func PeriodToTime(period string) (_ time.Time, err error) { + if len(period) < 7 { + return time.Time{}, fmt.Errorf("invalid period %q", period) + } + shortPeriod := period[:7] layout := "2006-01" - shortPeriod := period[0:7] result, err := time.Parse(layout, shortPeriod) if err != nil { return time.Time{}, err diff --git a/private/date/utils_test.go b/private/date/utils_test.go index bf7415d1ca81..6043af6d5ac7 100644 --- a/private/date/utils_test.go +++ b/private/date/utils_test.go @@ -48,6 +48,21 @@ func TestPeriodToTime(t *testing.T) { } } +func TestPeriodToTime_Invalid(t *testing.T) { + testCases := [...]struct { + period string + error string + }{ + {"", "invalid period \"\""}, + {"2020", "invalid period \"2020\""}, + } + + for _, tc := range testCases { + _, err := date.PeriodToTime(tc.period) + require.ErrorContains(t, err, tc.error) + } +} + func TestMonthsBetweenDates(t *testing.T) { testCases := [...]struct { from time.Time