From 912df2e2848b5b5189071c36e0d09bfd28d4d144 Mon Sep 17 00:00:00 2001 From: Carl Bergquist Date: Mon, 10 Jun 2019 07:38:31 +0200 Subject: [PATCH] gtime: some code style refactoring (#17369) --- pkg/components/gtime/gtime.go | 33 ++++++++++++++++-------------- pkg/components/gtime/gtime_test.go | 2 ++ 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/pkg/components/gtime/gtime.go b/pkg/components/gtime/gtime.go index e3e4e449f66..12a66ff1d7f 100644 --- a/pkg/components/gtime/gtime.go +++ b/pkg/components/gtime/gtime.go @@ -6,23 +6,26 @@ import ( "time" ) -// ParseInterval parses and interval with support for all units that Grafana uses. +var dateUnitPattern = regexp.MustCompile(`(\d+)([wdy])`) + +// ParseInterval parses an interval with support for all units that Grafana uses. func ParseInterval(interval string) (time.Duration, error) { - re := regexp.MustCompile(`(\d+)([wdy])`) - result := re.FindSubmatch([]byte(interval)) + result := dateUnitPattern.FindSubmatch([]byte(interval)) - if len(result) == 3 { - num, _ := strconv.Atoi(string(result[1])) - period := string(result[2]) - - if period == `d` { - return time.Hour * 24 * time.Duration(num), nil - } else if period == `w` { - return time.Hour * 24 * 7 * time.Duration(num), nil - } else { - return time.Hour * 24 * 7 * 365 * time.Duration(num), nil - } - } else { + if len(result) != 3 { return time.ParseDuration(interval) } + + num, _ := strconv.Atoi(string(result[1])) + period := string(result[2]) + + if period == `d` { + return time.Hour * 24 * time.Duration(num), nil + } + + if period == `w` { + return time.Hour * 24 * 7 * time.Duration(num), nil + } + + return time.Hour * 24 * 7 * 365 * time.Duration(num), nil } diff --git a/pkg/components/gtime/gtime_test.go b/pkg/components/gtime/gtime_test.go index e683184023f..65489826af2 100644 --- a/pkg/components/gtime/gtime_test.go +++ b/pkg/components/gtime/gtime_test.go @@ -15,7 +15,9 @@ func TestParseInterval(t *testing.T) { }{ {interval: "1d", duration: time.Hour * 24}, {interval: "1w", duration: time.Hour * 24 * 7}, + {interval: "2w", duration: time.Hour * 24 * 7 * 2}, {interval: "1y", duration: time.Hour * 24 * 7 * 365}, + {interval: "5y", duration: time.Hour * 24 * 7 * 365 * 5}, {interval: "1M", err: errors.New("time: unknown unit M in duration 1M")}, {interval: "invalid-duration", err: errors.New("time: invalid duration invalid-duration")}, }