Skip to content

Commit

Permalink
Fix time suggestions (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdbenjam authored Dec 6, 2024
1 parent 7932c13 commit 9a4dc61
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
15 changes: 10 additions & 5 deletions pkg/command/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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)
}
Expand Down
17 changes: 15 additions & 2 deletions pkg/command/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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",
Expand All @@ -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{""},
},
}

Expand Down

0 comments on commit 9a4dc61

Please sign in to comment.