fix(query): report an uppercase duration unit as an unparseable time, not a negated internal error (#7683)
* refactor(timeparsing): export IsCompactDuration The query lexer keeps its own copy of the compact-duration unit set, and that copy has drifted from the grammar: it accepts the uppercase units H D W M Y, which ParseCompactDuration rejects. Export the classifier so the lexer can ask timeparsing instead of keeping a copy, and pin that it agrees with ParseCompactDuration on every row, uppercase spellings included. AC: AC-1 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(query): classify durations with timeparsing.IsCompactDuration The query lexer kept its own copy of the compact-duration unit set: isDurationSuffix for single runes and durationWords for "min". The copy had drifted. It accepted H D W M Y, which the case-sensitive grammar rejects, so "created>30M" reached the evaluator as a duration and failed with the internal error `not a compact duration: "-30M"`, quoting a value the user never typed. Classify the whole digit-led lexeme with timeparsing.IsCompactDuration and delete the copy (isDurationSuffix, durationWords, acceptDurationWord). Uppercase units now lex as identifiers and fail as an unparseable time; every lowercase input lexes as before. A unit added to compactDurationRe now reaches the lexer with no edit here: with "sec" added to the regex alone, TestCompactDurationGrammarReachesQueryPlane fails on the old lexer and passes on this one. Retire that test's text naming the deleted copy. AC: AC-2 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin that uppercase duration units lex as identifiers "updated>30M", "updated>30H" and "label=30D" lex the value as one TokenIdent with the text as typed; "updated>30m" and "updated>+30d" still lex as TokenDuration. On the base lexer the three uppercase rows fail (typed DURATION). AC: AC-3 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin the error for an uppercase duration unit created>, updated<, closed>= and started<= compared to 30M, 30D, 30W, 30Y, 30H or 1H, alone or in "... OR status=open", fail with `cannot parse time expression: "<value as typed>"`, never with the internal `not a compact duration` error and never quoting the negated "-<value>". 30MIN and 30Min, which always took this path, are the controls. On the base lexer 30 of the 40 subtests fail; the 10 controls pass. AC: AC-4 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): bind the lexer's duration grammar to timeparsing both ways TestCompactDurationGrammarReachesQueryPlane asserted only that every suffix ParseCompactDuration accepts lexes as a duration. Assert the reverse too: a suffix it rejects must not lex as TokenDuration, or the evaluator fails on it with ParseCompactDuration's internal error about a negated value. Widen the candidates to every one- and two-letter ASCII suffix in either case, every three-letter lowercase one, and every case spelling of an accepted three-letter unit. On the base lexer the reverse sweep fails on exactly [D H M W Y]. A mutant that case-folds before classifying fails it on those plus the seven other spellings of "min". AC: AC-5 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin that a signed uppercase unit stops at the parser "created>+30M" and "created>-30M" fail Parse and EvaluateAt with `unexpected token "M" at position 11 (expected end of query)`, as "created>+30x" already does: a signed digit run has no identifier fallback, so "+30" is a number and "M" a stray token. On the base lexer both parsed as a duration and failed in the evaluator with `not a compact duration: "-30M"` and `"--30M"`; the +30x control passes on both. AC: AC-6 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(query): pin the values rejecting uppercase units leaves alone At a fixed now, created>+30d is still 30 days ago, updated>5pm still 17:00 that day, and label=30M / title=30M still filter the literal "30M". TestQueryMinutesUnitResolvesAgo already pins created>30m (30 months ago) and created>30min (30 minutes ago). These rows pass on the base lexer as well, which is the point; a lexer mutant that stops typing signed lexemes as durations fails the +30d row. AC: AC-7 Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
994f5b82dd
commit
4c473b4580
5 changed files with 312 additions and 79 deletions
|
|
@ -777,6 +777,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
`bd dep add`'s: `bd: dep add <from> <to>` in place of
|
||||
`dependency: add <type> <from> -> <to>`.
|
||||
|
||||
- **`bd query` reports an uppercase duration unit as an unparseable time, not
|
||||
a negated internal error.** `created>30M` failed with
|
||||
`not a compact duration: "-30M"`, naming a value nobody typed; it now fails
|
||||
with `cannot parse time expression: "30M"`. A signed spelling
|
||||
(`created>+30M`) stops at the parser, as `created>+30x` already did, so
|
||||
quote one to match it as a literal (`label="+30M"`). Units remain lowercase
|
||||
(`30min`, `6h`, `7d`, `2w`, `3m`, `1y`); help and docs already say so.
|
||||
- **Strict `--readonly` no longer creates workspace gate files.** A
|
||||
`bd --readonly` command took its shared workspace gates with
|
||||
create-if-missing, so on a workspace no bd command had gated yet it left
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import (
|
|||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/steveyegge/beads/internal/timeparsing"
|
||||
)
|
||||
|
||||
// TokenType represents the type of a lexer token.
|
||||
|
|
@ -263,24 +265,19 @@ func (l *Lexer) readNumberOrDuration(startPos int) (Token, error) {
|
|||
sb.WriteRune(r)
|
||||
}
|
||||
|
||||
// Check for duration suffix. Only commit to a duration when the suffix
|
||||
// stands alone — if more identifier characters follow (e.g. "7day"),
|
||||
// fall through to the identifier-fallback below.
|
||||
if r != 0 && isDurationSuffix(r) && !isIdentChar(l.peek()) {
|
||||
sb.WriteRune(r)
|
||||
return Token{Type: TokenDuration, Value: sb.String(), Pos: startPos}, nil
|
||||
}
|
||||
|
||||
// Multi-rune duration suffixes ("min") cannot be recognized above:
|
||||
// isDurationSuffix classifies a single rune, and the stands-alone guard
|
||||
// bails on the letters that follow it. Left as an identifier, "30min"
|
||||
// would skip the evaluator's TokenDuration arm and resolve through
|
||||
// timeparsing.ParseRelativeTime as a *future* offset — the opposite
|
||||
// direction from the "N ago" contract 7d, 24h and 30m all honor.
|
||||
// Check for a duration suffix. internal/timeparsing owns the compact
|
||||
// duration grammar, so the whole lexeme is classified there rather than
|
||||
// against a copy of its unit set kept here. A copy drifts both ways: a
|
||||
// unit it misses ("30min") lexes as an identifier and resolves through
|
||||
// timeparsing.ParseRelativeTime as a *future* offset, the opposite of
|
||||
// the "N ago" contract every duration honors; a unit it adds ("30M")
|
||||
// reaches the evaluator as a duration the grammar then rejects. When
|
||||
// more identifier characters follow the unit ("7day", "30mins",
|
||||
// "42d-sla"), the lexeme is not a duration and falls through to the
|
||||
// identifier fallback below.
|
||||
if r != 0 {
|
||||
if word, ok := l.acceptDurationWord(); ok {
|
||||
sb.WriteString(word)
|
||||
return Token{Type: TokenDuration, Value: sb.String(), Pos: startPos}, nil
|
||||
if lexeme, ok := l.acceptDuration(sb.String()); ok {
|
||||
return Token{Type: TokenDuration, Value: lexeme, Pos: startPos}, nil
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -362,44 +359,26 @@ func isIdentChar(r rune) bool {
|
|||
return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '-' || r == '.' || r == ':' || r == '/'
|
||||
}
|
||||
|
||||
// isDurationSuffix returns true if r is a valid duration suffix.
|
||||
func isDurationSuffix(r rune) bool {
|
||||
switch r {
|
||||
case 'h', 'd', 'w', 'm', 'y', 'H', 'D', 'W', 'M', 'Y':
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// durationWords are the multi-rune duration suffixes of the shared
|
||||
// compact-duration grammar (internal/timeparsing). "min" is spelled out there
|
||||
// precisely because "m" means months, so the query plane has to match the whole
|
||||
// word to classify it as a duration. Lowercase only, matching that grammar.
|
||||
var durationWords = []string{"min"}
|
||||
|
||||
// acceptDurationWord reports whether the input spells a multi-rune duration
|
||||
// suffix, starting at the rune the caller most recently read with next() and
|
||||
// standing alone. On a match it consumes the suffix and returns it; otherwise
|
||||
// the lexer position is left untouched.
|
||||
func (l *Lexer) acceptDurationWord() (string, bool) {
|
||||
// acceptDuration reports whether number, followed by the run of identifier
|
||||
// characters that starts at the rune the caller most recently read with
|
||||
// next(), is a compact duration (timeparsing.IsCompactDuration). The run is
|
||||
// taken whole, so a unit only counts when it stands alone. On a match it
|
||||
// consumes the run and returns the full lexeme; otherwise the lexer position
|
||||
// is left untouched.
|
||||
func (l *Lexer) acceptDuration(number string) (string, bool) {
|
||||
if l.width == 0 {
|
||||
return "", false
|
||||
}
|
||||
start := l.pos - l.width
|
||||
for _, word := range durationWords {
|
||||
if !strings.HasPrefix(l.input[start:], word) {
|
||||
continue
|
||||
}
|
||||
end := start + len(word)
|
||||
// More identifier characters follow ("30mins", "30minutes",
|
||||
// "30min-sla"), so this is an identifier, not a duration.
|
||||
if end < len(l.input) && isIdentChar(rune(l.input[end])) {
|
||||
continue
|
||||
}
|
||||
l.pos = end
|
||||
l.width = 1
|
||||
return word, true
|
||||
end := start
|
||||
for end < len(l.input) && isIdentChar(rune(l.input[end])) {
|
||||
end++
|
||||
}
|
||||
return "", false
|
||||
lexeme := number + l.input[start:end]
|
||||
if !timeparsing.IsCompactDuration(lexeme) {
|
||||
return "", false
|
||||
}
|
||||
l.pos = end
|
||||
l.width = 1
|
||||
return lexeme, true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
package query
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
|
|
@ -177,6 +180,39 @@ func TestLexer(t *testing.T) {
|
|||
expected: []TokenType{TokenIdent, TokenEquals, TokenIdent, TokenEOF},
|
||||
values: []string{"label", "=", "30MIN", ""},
|
||||
},
|
||||
// Units are lowercase in the shared grammar, so an uppercase one is
|
||||
// not a duration: it reaches the evaluator as typed and fails there as
|
||||
// an unparseable time instead of as a negated compact duration.
|
||||
{
|
||||
name: "uppercase months unit stays an identifier",
|
||||
input: "updated>30M",
|
||||
expected: []TokenType{TokenIdent, TokenGreater, TokenIdent, TokenEOF},
|
||||
values: []string{"updated", ">", "30M", ""},
|
||||
},
|
||||
{
|
||||
name: "uppercase hours unit stays an identifier",
|
||||
input: "updated>30H",
|
||||
expected: []TokenType{TokenIdent, TokenGreater, TokenIdent, TokenEOF},
|
||||
values: []string{"updated", ">", "30H", ""},
|
||||
},
|
||||
{
|
||||
name: "uppercase days unit on a non-time field stays an identifier",
|
||||
input: "label=30D",
|
||||
expected: []TokenType{TokenIdent, TokenEquals, TokenIdent, TokenEOF},
|
||||
values: []string{"label", "=", "30D", ""},
|
||||
},
|
||||
{
|
||||
name: "lowercase months unit is a duration",
|
||||
input: "updated>30m",
|
||||
expected: []TokenType{TokenIdent, TokenGreater, TokenDuration, TokenEOF},
|
||||
values: []string{"updated", ">", "30m", ""},
|
||||
},
|
||||
{
|
||||
name: "signed lowercase days unit is a duration",
|
||||
input: "updated>+30d",
|
||||
expected: []TokenType{TokenIdent, TokenGreater, TokenDuration, TokenEOF},
|
||||
values: []string{"updated", ">", "+30d", ""},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
|
|
@ -764,44 +800,207 @@ func TestQueryMinutesUnitResolvesAgo(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestQueryRejectsUppercaseDurationUnits pins how an uppercase duration unit
|
||||
// fails on a time field. Units are lowercase in the shared grammar, so "30M"
|
||||
// is not a duration: it reaches ParseRelativeTime as typed, fails there, and
|
||||
// the error quotes what the user wrote. It must never be the internal
|
||||
// "not a compact duration" error, which quoted the negated "-30M" the
|
||||
// evaluator builds for a duration token. "30MIN" and "30Min" always took the
|
||||
// ParseRelativeTime path; they are controls for the expected error.
|
||||
func TestQueryRejectsUppercaseDurationUnits(t *testing.T) {
|
||||
now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
values := []string{"30M", "30D", "30W", "30Y", "30H", "1H", "30MIN", "30Min"}
|
||||
shapes := []string{
|
||||
"created>%s",
|
||||
"updated<%s",
|
||||
"closed>=%s",
|
||||
"started<=%s",
|
||||
"created>%s OR status=open",
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
for _, shape := range shapes {
|
||||
query := fmt.Sprintf(shape, value)
|
||||
t.Run(query, func(t *testing.T) {
|
||||
_, err := EvaluateAt(query, now)
|
||||
if err == nil {
|
||||
t.Fatalf("EvaluateAt(%q) succeeded, want an unparseable-time error", query)
|
||||
}
|
||||
msg := err.Error()
|
||||
if want := "cannot parse time expression: " + strconv.Quote(value); !strings.Contains(msg, want) {
|
||||
t.Errorf("EvaluateAt(%q) error = %q, want it to contain %q", query, msg, want)
|
||||
}
|
||||
if strings.Contains(msg, "not a compact duration") {
|
||||
t.Errorf("EvaluateAt(%q) error = %q, want no internal compact-duration error", query, msg)
|
||||
}
|
||||
if negated := strconv.Quote("-" + value); strings.Contains(msg, negated) {
|
||||
t.Errorf("EvaluateAt(%q) error = %q quotes %s, a value the user never typed", query, msg, negated)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuerySignedUppercaseDurationUnitStopsAtTheParser pins how a signed
|
||||
// uppercase unit fails. A signed digit run has no identifier fallback (the
|
||||
// user has to quote "-3-foo"), so with "M" not a unit, "+30M" lexes as the
|
||||
// number "+30" and then the identifier "M", and the parser rejects that stray
|
||||
// token as it already rejects the "x" of "+30x". It must not reach the
|
||||
// evaluator as a duration and fail there with the internal
|
||||
// "not a compact duration" error.
|
||||
func TestQuerySignedUppercaseDurationUnitStopsAtTheParser(t *testing.T) {
|
||||
now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
tests := []struct {
|
||||
query string
|
||||
wantErr string
|
||||
}{
|
||||
{"created>+30M", `unexpected token "M" at position 11 (expected end of query)`},
|
||||
{"created>-30M", `unexpected token "M" at position 11 (expected end of query)`},
|
||||
// Control: an unknown lowercase unit already fails this way.
|
||||
{"created>+30x", `unexpected token "x" at position 11 (expected end of query)`},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.query, func(t *testing.T) {
|
||||
if _, err := Parse(tt.query); err == nil || err.Error() != tt.wantErr {
|
||||
t.Errorf("Parse(%q) error = %v, want %q", tt.query, err, tt.wantErr)
|
||||
}
|
||||
if _, err := EvaluateAt(tt.query, now); err == nil || err.Error() != tt.wantErr {
|
||||
t.Errorf("EvaluateAt(%q) error = %v, want %q", tt.query, err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestQueryKeepsLowercaseUnitsAndLiteralValues pins, at a fixed now, what
|
||||
// rejecting uppercase units leaves alone: a signed lowercase unit still
|
||||
// resolves as N ago, a natural-language time still resolves through
|
||||
// ParseRelativeTime, and on a non-time field "30M" is still the literal string
|
||||
// it always was. TestQueryMinutesUnitResolvesAgo pins created>30m (30 months
|
||||
// ago) and created>30min (30 minutes ago).
|
||||
func TestQueryKeepsLowercaseUnitsAndLiteralValues(t *testing.T) {
|
||||
now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
bounds := []struct {
|
||||
query string
|
||||
want time.Time
|
||||
bound func(*types.IssueFilter) *time.Time
|
||||
}{
|
||||
{
|
||||
query: "created>+30d",
|
||||
want: now.AddDate(0, 0, -30),
|
||||
bound: func(f *types.IssueFilter) *time.Time { return f.CreatedAfter },
|
||||
},
|
||||
{
|
||||
query: "updated>5pm",
|
||||
want: time.Date(2025, 2, 4, 17, 0, 0, 0, time.UTC),
|
||||
bound: func(f *types.IssueFilter) *time.Time { return f.UpdatedAfter },
|
||||
},
|
||||
}
|
||||
for _, tt := range bounds {
|
||||
t.Run(tt.query, func(t *testing.T) {
|
||||
result, err := EvaluateAt(tt.query, now)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluateAt(%q) error = %v", tt.query, err)
|
||||
}
|
||||
got := tt.bound(&result.Filter)
|
||||
if got == nil {
|
||||
t.Fatalf("EvaluateAt(%q) left the time bound unset, filter=%+v", tt.query, result.Filter)
|
||||
}
|
||||
if !got.Equal(tt.want) {
|
||||
t.Errorf("EvaluateAt(%q) = %s, want %s", tt.query, got.Format(time.RFC3339), tt.want.Format(time.RFC3339))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("label=30M", func(t *testing.T) {
|
||||
result, err := EvaluateAt("label=30M", now)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluateAt(label=30M) error = %v", err)
|
||||
}
|
||||
if len(result.Filter.Labels) != 1 || result.Filter.Labels[0] != "30M" {
|
||||
t.Errorf("EvaluateAt(label=30M) Labels = %v, want [%q]", result.Filter.Labels, "30M")
|
||||
}
|
||||
})
|
||||
t.Run("title=30M", func(t *testing.T) {
|
||||
result, err := EvaluateAt("title=30M", now)
|
||||
if err != nil {
|
||||
t.Fatalf("EvaluateAt(title=30M) error = %v", err)
|
||||
}
|
||||
if result.Filter.TitleContains != "30M" {
|
||||
t.Errorf("EvaluateAt(title=30M) TitleContains = %q, want %q", result.Filter.TitleContains, "30M")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestCompactDurationGrammarReachesQueryPlane binds this package's duration
|
||||
// grammar to the shared one in internal/timeparsing, which owns it. The lexer
|
||||
// keeps a second copy of the unit set — isDurationSuffix for single runes,
|
||||
// durationWords for whole words — and nothing outside this test holds the two
|
||||
// in sync. A unit added to the shared grammar but missed here lexes as
|
||||
// TokenIdent, skips the evaluator's TokenDuration arm, and resolves through
|
||||
// ParseRelativeTime as a *future* offset: the "30min meant 30 minutes from now"
|
||||
// inversion this PR fixed, reproduced silently for the next unit.
|
||||
// grammar to the shared one in internal/timeparsing, which owns it, in both
|
||||
// directions. The lexer classifies a duration with
|
||||
// timeparsing.IsCompactDuration instead of keeping its own copy of the unit
|
||||
// set; this test holds it to that. A unit the shared grammar accepts but the
|
||||
// lexer types as TokenIdent skips the evaluator's TokenDuration arm and
|
||||
// resolves through ParseRelativeTime as a *future* offset: the "30min meant 30
|
||||
// minutes from now" inversion, reproduced silently for the next unit. A suffix
|
||||
// the shared grammar rejects but the lexer types as TokenDuration reaches
|
||||
// ParseCompactDuration in the evaluator and fails with that parser's internal
|
||||
// error about a negated value the user never typed: while the lexer took
|
||||
// "H D W M Y", "created>30M" failed with `not a compact duration: "-30M"`.
|
||||
//
|
||||
// The shared pattern is unexported, so ParseCompactDuration is the oracle:
|
||||
// whatever suffix it accepts must lex as a duration here. Candidates are
|
||||
// exhaustive over lowercase ASCII up to three runes, so plausible future
|
||||
// spellings ("sec", "hr", "mo", "yr") are covered alongside today's six.
|
||||
//
|
||||
// Only this direction is asserted. The reverse — everything the lexer accepts
|
||||
// being valid in the shared grammar — is already false at base: isDurationSuffix
|
||||
// also takes "H D W M Y", which the case-sensitive pattern rejects, so
|
||||
// "created>30M" lexes as a duration and then fails in ParseCompactDuration.
|
||||
// That asymmetry predates this PR and is not what this test is for.
|
||||
// ParseCompactDuration is the oracle: a suffix must lex as a duration here if
|
||||
// and only if it accepts it. Candidates are exhaustive over one- and
|
||||
// two-letter ASCII in either case and three-letter lowercase ASCII, plus every
|
||||
// case spelling of an accepted three-letter unit, so plausible future
|
||||
// spellings ("sec", "hr", "mo", "yr") are covered alongside today's six and
|
||||
// their uppercase forms.
|
||||
func TestCompactDurationGrammarReachesQueryPlane(t *testing.T) {
|
||||
now := time.Date(2025, 2, 4, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
const letters = "abcdefghijklmnopqrstuvwxyz"
|
||||
accepts := func(unit string) bool {
|
||||
_, err := timeparsing.ParseCompactDuration("1"+unit, now)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
const lower = "abcdefghijklmnopqrstuvwxyz"
|
||||
const letters = lower + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
var candidates []string
|
||||
for _, a := range letters {
|
||||
candidates = append(candidates, string(a))
|
||||
for _, b := range letters {
|
||||
candidates = append(candidates, string(a)+string(b))
|
||||
for _, c := range letters {
|
||||
candidates = append(candidates, string(a)+string(b)+string(c))
|
||||
}
|
||||
}
|
||||
for _, a := range lower {
|
||||
for _, b := range lower {
|
||||
for _, c := range lower {
|
||||
unit := string(a) + string(b) + string(c)
|
||||
candidates = append(candidates, unit)
|
||||
if !accepts(unit) {
|
||||
continue
|
||||
}
|
||||
// The lowercase sweep reaches only this spelling of an
|
||||
// accepted three-letter unit; add the others ("MIN", "Min", ...).
|
||||
for mask := 1; mask < 1<<len(unit); mask++ {
|
||||
var spelling strings.Builder
|
||||
for i := 0; i < len(unit); i++ {
|
||||
if mask&(1<<i) != 0 {
|
||||
spelling.WriteString(strings.ToUpper(unit[i : i+1]))
|
||||
} else {
|
||||
spelling.WriteByte(unit[i])
|
||||
}
|
||||
}
|
||||
candidates = append(candidates, spelling.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var accepted []string
|
||||
var accepted, rejected []string
|
||||
isAccepted := make(map[string]bool)
|
||||
for _, unit := range candidates {
|
||||
if _, err := timeparsing.ParseCompactDuration("1"+unit, now); err != nil {
|
||||
if !accepts(unit) {
|
||||
rejected = append(rejected, unit)
|
||||
continue
|
||||
}
|
||||
accepted = append(accepted, unit)
|
||||
|
|
@ -829,7 +1028,7 @@ func TestCompactDurationGrammarReachesQueryPlane(t *testing.T) {
|
|||
}
|
||||
if tokens[2].Type != TokenDuration || tokens[2].Value != value {
|
||||
t.Errorf("timeparsing accepts %q but the query lexer typed it %v(%q), want %v(%q); "+
|
||||
"add the unit to durationWords/isDurationSuffix or it resolves as a future offset",
|
||||
"classify durations with timeparsing.IsCompactDuration or the unit resolves as a future offset",
|
||||
value, tokens[2].Type, tokens[2].Value, TokenDuration, value)
|
||||
}
|
||||
|
||||
|
|
@ -845,6 +1044,29 @@ func TestCompactDurationGrammarReachesQueryPlane(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The reverse direction is one sweep with one report rather than a
|
||||
// subtest per suffix: there are over 20,000 of them.
|
||||
var typedDuration []string
|
||||
for _, unit := range rejected {
|
||||
value := "1" + unit
|
||||
tokens, err := NewLexer("updated>" + value).Tokenize()
|
||||
if err != nil {
|
||||
t.Errorf("Tokenize(updated>%s) error = %v", value, err)
|
||||
continue
|
||||
}
|
||||
for _, tok := range tokens {
|
||||
if tok.Type == TokenDuration {
|
||||
typedDuration = append(typedDuration, unit)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(typedDuration) > 0 {
|
||||
t.Errorf("timeparsing rejects these suffixes but the query lexer typed them %v: %v; "+
|
||||
"classify durations with timeparsing.IsCompactDuration or the evaluator fails on them "+
|
||||
"with an internal error", TokenDuration, typedDuration)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluatorMetadataQueries(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -183,6 +183,8 @@ func TestParseCompactDuration(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestIsCompactDuration(t *testing.T) {
|
||||
now := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
tests := []struct {
|
||||
input string
|
||||
want bool
|
||||
|
|
@ -191,9 +193,11 @@ func TestIsCompactDuration(t *testing.T) {
|
|||
{"-1d", true},
|
||||
{"+2w", true},
|
||||
{"3m", true},
|
||||
{"30m", true},
|
||||
{"1y", true},
|
||||
{"+24h", true},
|
||||
{"+30min", true},
|
||||
{"30min", true},
|
||||
{"+30mins", false},
|
||||
{"", false},
|
||||
{"tomorrow", false},
|
||||
|
|
@ -201,13 +205,29 @@ func TestIsCompactDuration(t *testing.T) {
|
|||
{"6h+", false},
|
||||
{"++1d", false},
|
||||
{"1x", false},
|
||||
|
||||
// Units are lowercase. Folding case would make "30M" mean 30 months,
|
||||
// the ambiguity "min" exists to avoid, so uppercase spellings are not
|
||||
// compact durations.
|
||||
{"30M", false},
|
||||
{"+6H", false},
|
||||
{"1D", false},
|
||||
{"2W", false},
|
||||
{"1Y", false},
|
||||
{"30MIN", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
got := isCompactDuration(tt.input)
|
||||
got := IsCompactDuration(tt.input)
|
||||
if got != tt.want {
|
||||
t.Errorf("isCompactDuration(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
t.Errorf("IsCompactDuration(%q) = %v, want %v", tt.input, got, tt.want)
|
||||
}
|
||||
// Callers classify with IsCompactDuration and then parse, so the
|
||||
// two must agree on every row here.
|
||||
_, err := ParseCompactDuration(tt.input, now)
|
||||
if parsed := err == nil; parsed != got {
|
||||
t.Errorf("IsCompactDuration(%q) = %v, but ParseCompactDuration error = %v", tt.input, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -87,8 +87,13 @@ func applyDuration(base time.Time, amount int, unit string) time.Time {
|
|||
}
|
||||
}
|
||||
|
||||
// isCompactDuration returns true if the string matches compact duration syntax.
|
||||
func isCompactDuration(s string) bool {
|
||||
// IsCompactDuration reports whether s is in the compact duration syntax that
|
||||
// ParseCompactDuration parses; only an amount too large for an int matches it
|
||||
// and still fails to parse. Callers that classify a compact duration without
|
||||
// parsing it (the query lexer) use this instead of keeping their own copy of
|
||||
// the unit set, so a unit added to compactDurationRe reaches them with no edit
|
||||
// of theirs.
|
||||
func IsCompactDuration(s string) bool {
|
||||
return compactDurationRe.MatchString(s)
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue