From 9a4dc61b130635525dc6ae2ff299f55330a0b8d1 Mon Sep 17 00:00:00 2001 From: Mark Benjamin Date: Fri, 6 Dec 2024 14:20:33 -0500 Subject: [PATCH] Fix time suggestions (#172) --- pkg/command/time.go | 15 ++++++++++----- pkg/command/time_test.go | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/pkg/command/time.go b/pkg/command/time.go index 2247c63..5c6f52f 100644 --- a/pkg/command/time.go +++ b/pkg/command/time.go @@ -11,15 +11,18 @@ import ( var RFC3339RegexString = []string{ `\d`, `\d`, `\d`, `\d`, `-`, `\d`, `\d`, `-`, `\d`, `\d`, `T`, `\d`, `\d`, `:`, `\d`, `\d`, `:`, `\d`, `\d`, - `Z`, `\d`, `\d`, `:`, `\d`, `\d`, } +const timestampFormatWithoutOffset = "2006-01-02T15:04:05Z" + func TimeSuggestion(str string) []string { var suggestion string if i, err := strconv.Atoi(str); err == nil && i <= 60 { suggestion = fmt.Sprintf("%dm", i) - } else if re, err := regexp.Compile(strings.Join(RFC3339RegexString[:len(str)], "")); err == nil && re.MatchString(str) { - suggestion = str + time.RFC3339[len(str):] + } else if len(str) <= len(RFC3339RegexString) { + if re, err := regexp.Compile(strings.Join(RFC3339RegexString[:len(str)], "")); err == nil && re.MatchString(str) { + suggestion = str + timestampFormatWithoutOffset[len(str):] + } } return []string{suggestion} @@ -66,11 +69,13 @@ func ParseTime(now time.Time, str *string) (*TimeOrRelative, error) { return nil, nil } - if t := parseRelativeTime(now, *str); t != nil { + trimmedString := strings.Trim(*str, " ") + + if t := parseRelativeTime(now, trimmedString); t != nil { return t, nil } - absoluteTime, err := time.Parse(time.RFC3339, *str) + absoluteTime, err := time.Parse(time.RFC3339, trimmedString) if err != nil { return nil, fmt.Errorf("invalid timestamp, time must either be relative (1m, 5h, etc) or in RFC3339 format: %s", time.RFC3339) } diff --git a/pkg/command/time_test.go b/pkg/command/time_test.go index b402243..749e561 100644 --- a/pkg/command/time_test.go +++ b/pkg/command/time_test.go @@ -37,6 +37,14 @@ func TestParseTime(t *testing.T) { str: now.Format(time.RFC3339), expected: command.TimeOrRelative{T: &now}, }, + { + name: "trims whitespace", + str: " 1m ", + expected: command.TimeOrRelative{ + T: pointers.From(now.Add(-time.Minute)), + Relative: pointers.From("1m"), + }, + }, } for _, tc := range tcs { @@ -95,7 +103,7 @@ func TestTimeSuggestion(t *testing.T) { { name: "empty string", str: "", - expected: []string{"2006-01-02T15:04:05Z07:00"}, + expected: []string{"2006-01-02T15:04:05Z"}, }, { name: "< 60 int", @@ -105,7 +113,12 @@ func TestTimeSuggestion(t *testing.T) { { name: "match time format", str: "202", - expected: []string{"2026-01-02T15:04:05Z07:00"}, + expected: []string{"2026-01-02T15:04:05Z"}, + }, + { + name: "no suggestion if time is too long", + str: "2026-01-02T15:04:05ZABC", + expected: []string{""}, }, }