diff --git a/.superpowers/sdd/2026-08-01-18640-plan/task-3-report.md b/.superpowers/sdd/2026-08-01-18640-plan/task-3-report.md new file mode 100644 index 0000000..6a8e467 --- /dev/null +++ b/.superpowers/sdd/2026-08-01-18640-plan/task-3-report.md @@ -0,0 +1,275 @@ +# Task 3 Report: Fix `internal/pep508/` — `name()`, trailing line breaks, malformed quoted strings + +## Status: DONE + +**Commit:** 374af55 + +## Summary + +Fixed three PEP 508 grammar divergences from pypa/packaging 26.2, covering 8 of the 11 measured error-case divergences. All tests pass, including with `-race`. The tokenizer changes affected `marker/` and `reqtxt/` packages as expected, but both passed all tests — no behavior was broken. One test in the `requirement/` package had the wrong expectation and was corrected. + +## Changes Made + +### 1. Allow empty parenthesised specifier (`name()`) + +**Files modified:** +- `internal/pep508/requirement.go` + +**Changes:** +- Deleted the error branch (lines 191-193) that rejected empty parentheses +- Updated the doc comment on `parseVersionSpec` to document that `name()` is valid + +**Rationale:** According to pypa/packaging's `test_empty_specifier`, an empty parenthesized group is legal and means "no constraint". The function already returns `""` (empty string) when `clauses` is empty, which is the correct behavior. + +**Test verification:** Without this fix, all 4 test cases in `TestParseRequirement_EmptyParenthesisedSpecifier` fail with "Expected version specifier inside parentheses". + +### 2. Reject trailing line breaks + +**Files modified:** +- `internal/pep508/tokenizer.go` +- `internal/pep508/requirement.go` + +**Changes in tokenizer.go:** +- Changed the `WS` token pattern from `\A\s+` to `\A[ \t]+` + - This restricts whitespace matching to horizontal whitespace only (space and tab) + - Line breaks (`\n`, `\r`) are no longer consumed as whitespace + +**Changes in requirement.go:** +- Modified the URL whitespace handling (lines 146-168) to explicitly accept and consume line breaks after a URL +- This preserves the existing behavior where `name @ url\n; marker` is valid (defensively multiline format) +- The final `consume(WS)` before `expect(End)` only consumes horizontal whitespace, so a trailing line break at the end causes the `expect(End)` check to fail with "Expected end of requirement string" + +**Rationale:** Upstream rejects trailing line breaks in all 6 variants tested (3 line breaks × 2 bases). By restricting `WS` to horizontal whitespace, a trailing line break stays unconsumed and triggers the existing end-of-input error. The URL case needed special handling because line breaks are valid separators there (common in Requires-Dist metadata). + +**Test verification:** Without the tokenizer change, all 6 test cases in `TestParseRequirement_RejectsTrailingLineBreak` fail with "An error is expected but got nil" (the line breaks were accepted). + +**Horizontal whitespace still valid:** `TestParseRequirement_AllowsTrailingHorizontalWhitespace` passes, confirming that trailing spaces and tabs remain valid. + +### 3. Reject malformed quoted strings + +**Files modified:** +- `internal/pep508/tokenizer.go` + +**Changes:** +- Changed the `QuotedString` token pattern from `\A(?:'[^']*'|"[^"]*")` to `\A(?:'[^'\\]*'|"[^"\\]*")` +- This rejects any string containing a backslash + +**Rationale:** PEP 508 marker strings have **no escape sequences**. A backslash before the closing quote leaves the string unterminated. The simplest correct fix is to reject backslashes entirely, which matches upstream behavior for both `"C:\"` and `"\x"`. + +**Test verification:** Without this fix, both test cases in `TestParseRequirement_RejectsMalformedQuotedString` fail with "An error is expected but got nil" (the malformed strings were accepted). + +## Impact on Other Packages + +### `marker/` package +- All tests passed (0.652s without race, 1.998s with race) +- No changes needed +- The tokenizer is shared, but the whitespace and quoted string changes are correct for markers too + +### `reqtxt/` package +- All tests passed (0.603s without race, 1.677s with race) +- No changes needed +- This package handles its own line splitting before tokenizing, so the WS change doesn't affect it + +### `requirement/` package +- One test updated: `TestParse_VersionSpec_EmptyParens_IsError` → `TestParse_VersionSpec_EmptyParens_IsValid` +- The old test expected `foo()` to be an error, but according to upstream it should be valid +- This is a correction of a wrong expectation, not a behavior regression + +## Commands Run + +### Test execution +```bash +# Initial test run to verify failures +cd /Users/jonyoder/Dev/gpp-worktrees/conformance-18640 +go test ./internal/pep508/ -run 'TestParseRequirement_' -v +# Result: 4 failures in EmptyParenthesisedSpecifier, 6 in RejectsTrailingLineBreak, +# 2 in RejectsMalformedQuotedString (as expected) + +# After fixes, run pep508 tests +go test ./internal/pep508/ -run 'TestParseRequirement_' -v +# Result: PASS, all 4 new test functions pass + +# Full module test +go test ./... +# Result: PASS all packages except requirement (test expectation bug) + +# After fixing requirement test +go test ./... +# Result: PASS all 14 packages + +# Race detector +go test -race ./... +# Result: PASS all 14 packages +``` + +### Individual fix verification (stash and test) +```bash +# Fix 1: Empty parenthesised specifier +git stash push internal/pep508/requirement.go requirement/requirement_test.go +go test ./internal/pep508/ -run TestParseRequirement_EmptyParenthesisedSpecifier -v +# Result: FAIL - all 4 cases fail with "Expected version specifier inside parentheses" +git stash pop + +# Fix 2: Trailing line breaks +git stash push internal/pep508/tokenizer.go +go test ./internal/pep508/ -run TestParseRequirement_RejectsTrailingLineBreak -v +# Result: FAIL - all 6 cases fail with "An error is expected but got nil" + +# Fix 3: Malformed quoted strings +go test ./internal/pep508/ -run TestParseRequirement_RejectsMalformedQuotedString -v +# Result: FAIL - both cases fail with "An error is expected but got nil" +git stash pop +``` + +### Formatting and linting +```bash +gofmt -l . +# Result: (empty output - all files correctly formatted) + +golangci-lint config verify +golangci-lint run ./... --timeout 10m +# Result: 0 issues +``` + +## Test Results Summary + +**New tests added:** 4 test functions in `internal/pep508/grammar_conformance_test.go` +- `TestParseRequirement_EmptyParenthesisedSpecifier` (4 subtests) +- `TestParseRequirement_RejectsTrailingLineBreak` (6 subtests) +- `TestParseRequirement_AllowsTrailingHorizontalWhitespace` (3 subtests) +- `TestParseRequirement_RejectsMalformedQuotedString` (2 subtests) + +**Tests modified:** 1 in `requirement/requirement_test.go` +- `TestParse_VersionSpec_EmptyParens_IsError` → `TestParse_VersionSpec_EmptyParens_IsValid` + +**All module tests:** 14 packages, all PASS +**Race detector:** All PASS +**Lint:** 0 issues + +## Notes + +1. **URL whitespace handling:** The most complex part of this task was handling the `name @ url\n; marker` case. A newline after a URL is valid as a separator (defensively multiline format), but a trailing newline at the end of the requirement should be rejected. The fix adds explicit line-break consumption after a URL while keeping the final `consume(WS)` horizontal-only. + +2. **No tokenizer breakage:** The tokenizer is shared with `marker/` and `reqtxt/`, but both packages passed all tests. The whitespace and quoted-string changes are correct for all consumers. + +3. **Upstream citation:** The test file includes the upstream commit pinned at `4eb0753dba8fcaaac8eb75463374e448f0931558` (pypa/packaging). + +4. **No provenance blocks added:** As instructed, I did not add per-file provenance blocks (separate issues #19394, #19395). + +## Fix round 1 + +### Status: DONE + +**What was wrong:** The brief's premise that "PEP 508 marker strings have no escape sequences" was incorrect. Upstream `pypa/packaging` at the pinned SHA (`4eb0753dba8fcaaac8eb75463374e448f0931558`) does NOT reject all backslashes. The tokenizer pattern is `('[^']*')|("[^"]*")` (no backslash exclusion), and the parser calls `ast.literal_eval(token.text)` to decode Python string-literal escapes. Only *invalid* escapes are rejected. + +The prior implementation's `QuotedString` pattern `\A(?:'[^'\\]*'|"[^"\\]*")` rejected all backslashes, which was over-strict. + +### Changes Made + +**Files modified:** +- `internal/pep508/tokenizer.go` +- `internal/pep508/marker.go` +- `internal/pep508/grammar_conformance_test.go` + +### 1. Reverted tokenizer pattern to upstream's form + +**File:** `internal/pep508/tokenizer.go:191` + +Changed `QuotedString` pattern from: +```go +QuotedString: regexp.MustCompile(`\A(?:'[^'\\]*'|"[^"\\]*")`), +``` + +To upstream's exact form: +```go +QuotedString: regexp.MustCompile(`\A(?:'[^']*'|"[^"]*")`), +``` + +This allows backslashes to tokenize normally, matching upstream behavior. + +### 2. Fixed wrong comment about escape handling + +**File:** `internal/pep508/tokenizer.go:140-146` + +The comment previously claimed packaging "takes `token.text[1:-1]` directly" — it does not. Updated to describe what upstream actually does (`ast.literal_eval`), and note that we deliberately do not implement full escape decoding (out of scope), but validate only the two specific malformed cases upstream asserts. + +### 3. Added targeted validation logic in marker.go + +**File:** `internal/pep508/marker.go:315-325, 352-394` + +Added validation where the marker literal is produced (`parseMarkerVar`), mirroring upstream's structure (tokenize permissively, then validate): + +- New function `validateQuotedStringContents(s string)` checks for: + 1. **Trailing unpaired backslash** — counts consecutive backslashes at end, rejects if odd + 2. **Truncated `\x` escape** — finds any `\x` not followed by two hex digits + +- Returns `&SyntaxError{Msg: "Invalid quoted string"}` — matching upstream's wording + +- New helper `isHexDigit(c byte)` checks if a character is 0-9, a-f, or A-F + +### 4. Updated test to accept valid escapes + +**File:** `internal/pep508/grammar_conformance_test.go:55-82` + +- Split `TestParseRequirement_RejectsMalformedQuotedString` into two sections: + - Still **REJECTS** `"C:\"` (trailing unpaired backslash) and `"\x"` (truncated escape) + - Newly **ACCEPTS** `"C:\\U"` (doubled backslash, paired) and `"\n"` (newline escape) + +- Added comments noting we accept the token but do not decode the escape + +### Verification + +All commands run from `/Users/jonyoder/Dev/gpp-worktrees/conformance-18640`: + +**1. Test the new logic:** +```bash +go test ./internal/pep508/ -v -run TestParseRequirement_RejectsMalformedQuotedString +# Result: PASS (4 subtests: 2 rejects, 2 accepts) +``` + +**2. All conformance tests:** +```bash +go test ./internal/pep508/ -v -run TestParseRequirement_ +# Result: PASS (all 4 test functions, 33 total subtests) +``` + +**3. Full module test:** +```bash +go test ./... +# Result: PASS all 14 packages +``` + +**4. Race detector:** +```bash +go test -race ./... +# Result: PASS all 14 packages +``` + +**5. Verify rejections fail without validation:** +```bash +git stash push internal/pep508/marker.go +go test ./internal/pep508/ -run "TestParseRequirement_RejectsMalformedQuotedString/reject" -v +# Result: FAIL - both rejection cases fail with "An error is expected but got nil" +git stash pop +``` + +This proves the validation logic is necessary. + +**6. Formatting and linting:** +```bash +gofmt -l . +# Result: (empty - all files correctly formatted after gofmt -w .) + +golangci-lint config verify +golangci-lint run ./... --timeout 10m +# Result: 0 issues +``` + +### Summary + +The fix correctly implements upstream's behavior: +- **Accepts** valid Python string escapes (`"C:\\U"`, `"\n"`) +- **Rejects** the two specific malformed cases upstream asserts (`"C:\"`, `"\x"`) +- **Does not decode** escapes (out of scope, left for future work) + +The tokenizer pattern now matches upstream exactly, and validation logic mirrors upstream's structure (permissive tokenization + targeted validation). diff --git a/NOTICE b/NOTICE index c8062f0..3a1a328 100644 --- a/NOTICE +++ b/NOTICE @@ -82,3 +82,12 @@ derivation (getLicense/getLicenseTypes and the licenses package's PyPI path), Copyright (c) Posit Software, PBC, contributed under the Apache License, Version 2.0, or the MIT license. The embedded data/pypi_licenses.json maps public PyPI Trove classifiers to SPDX identifiers. + +The requirement/ package's conformance tests port the dependency-specifier +cases of pypa/packaging (https://github.com/pypa/packaging), Copyright (c) +Donald Stufft and individual contributors, specifically +tests/test_requirements.py's test_basic_valid_requirement_parsing +cross-product parameters and the invalid-requirement cases of class +TestRequirementParsing, licensed under the Apache License, Version 2.0. +Translated from Python/pytest to Go table-driven tests; the parametrize +cross-product is expressed as a curated subset with equivalent coverage. diff --git a/internal/pep508/grammar_conformance_test.go b/internal/pep508/grammar_conformance_test.go new file mode 100644 index 0000000..2dacf0a --- /dev/null +++ b/internal/pep508/grammar_conformance_test.go @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package pep508 + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Ported from pypa/packaging tests/test_requirements.py, class +// TestRequirementParsing. Pinned: +// 4eb0753dba8fcaaac8eb75463374e448f0931558. + +// test_empty_specifier: "name()" is VALID and means no constraint. +func TestParseRequirement_EmptyParenthesisedSpecifier(t *testing.T) { + for _, s := range []string{"name()", "name ()", "name( )", "name ( )"} { + t.Run(s, func(t *testing.T) { + raw, err := ParseRequirement(NewTokenizer(s)) + require.NoError(t, err, "input %q should parse", s) + assert.Equal(t, "name", raw.Name) + assert.Equal(t, "", raw.Specifier, "empty parens mean no specifier") + }) + } +} + +// test_error_when_suffixed_with_line_break: parametrized over "\n", "\r", +// "\r\n" and over two bases. +func TestParseRequirement_RejectsTrailingLineBreak(t *testing.T) { + bases := []string{"name>=1", `name; python_version >= "3"`} + breaks := []string{"\n", "\r", "\r\n"} + for _, base := range bases { + for _, lb := range breaks { + in := base + lb + t.Run(base+"+"+escapeForName(lb), func(t *testing.T) { + _, err := ParseRequirement(NewTokenizer(in)) + assert.Error(t, err, "input %q should be rejected", in) + }) + } + } +} + +// A trailing horizontal space or tab remains VALID +// (test_trailing_horizontal_whitespace). +func TestParseRequirement_AllowsTrailingHorizontalWhitespace(t *testing.T) { + for _, ws := range []string{" ", "\t", " \t"} { + t.Run(escapeForName(ws), func(t *testing.T) { + _, err := ParseRequirement(NewTokenizer("name>=1" + ws)) + assert.NoError(t, err, "trailing horizontal whitespace is legal") + }) + } +} + +// test_error_invalid_marker_malformed_quoted_string: upstream rejects strings +// with trailing unpaired backslash or truncated \x escape, but accepts valid +// escapes like doubled backslash and \n. We tokenize permissively (like +// upstream's QUOTED_STRING rule) then validate the contents. +func TestParseRequirement_RejectsMalformedQuotedString(t *testing.T) { + // These two cases are rejected by upstream's ast.literal_eval + rejects := []string{ + `name; os_name == "C:\"`, // trailing unpaired backslash + `name; os_name == "\x"`, // truncated \x escape + } + for _, s := range rejects { + t.Run("reject:"+s, func(t *testing.T) { + _, err := ParseRequirement(NewTokenizer(s)) + assert.Error(t, err, "input %q should be rejected", s) + }) + } + + // These cases are accepted by upstream (valid Python string escapes). + // We accept the token but do not decode the escape (out of scope). + accepts := []string{ + `name; os_name == "C:\\U"`, // doubled backslash (paired) + `name; os_name == "\n"`, // newline escape + // An escaped backslash consumes BOTH bytes, so these are a complete + // pair followed by a literal "x" -- NOT a truncated \x escape. An + // earlier implementation scanned for trailing backslashes and for \x + // independently, with no way to know which backslashes a prior escape + // had already consumed, and falsely rejected all three. Regression + // guard: the body must contain a `\\` pair immediately before an "x". + `name; os_name == "C:\\xyz"`, + `name; os_name == "a\\x"`, + `name; os_name == "\\x"`, + } + for _, s := range accepts { + t.Run("accept:"+s, func(t *testing.T) { + _, err := ParseRequirement(NewTokenizer(s)) + assert.NoError(t, err, "input %q should be accepted (upstream accepts it)", s) + }) + } +} + +// escapeForName renders whitespace visibly so subtest names stay distinct. +// Go replaces a space with "_" in subtest names, which would otherwise make +// the space and tab cases indistinguishable in test output. +func escapeForName(s string) string { + out := "" + for _, r := range s { + switch r { + case '\n': + out += "LF" + case '\r': + out += "CR" + case '\t': + out += "TAB" + case ' ': + out += "SP" + default: + out += string(r) + } + } + return out +} diff --git a/internal/pep508/marker.go b/internal/pep508/marker.go index 1e10c4d..21bc056 100644 --- a/internal/pep508/marker.go +++ b/internal/pep508/marker.go @@ -124,10 +124,14 @@ func (Literal) markerOperand() {} func (l Literal) String() string { return quoteLiteral(l.Value) } // quoteLiteral renders a literal's value back into PEP 508 quoted-string -// syntax. PEP 508 quoted strings have no escape syntax, so a value -// containing a double quote is rendered single-quoted instead; a value -// containing both quote characters cannot be round-tripped (packaging has -// the same limitation, for the same reason). +// syntax. We do not EMIT escape sequences, so a value containing a double +// quote is rendered single-quoted instead; a value containing both quote +// characters cannot be round-tripped (packaging has the same limitation). +// +// Note this is about what we emit, not what we accept: upstream runs the token +// through ast.literal_eval, so Python string escapes ARE valid on input (see +// Token.Unquoted and validateQuotedStringContents). Do not use this comment as +// grounds for removing the escape validation. func quoteLiteral(v string) string { if strings.Contains(v, `"`) { return "'" + v + "'" @@ -313,7 +317,16 @@ func parseMarkerVar(t *Tokenizer) (Operand, error) { return EnvVar{Name: foldEnvVarAlias(name)}, nil } if t.check(QuotedString) { - return Literal{Value: t.read().Unquoted()}, nil + tok := t.read() + val := tok.Unquoted() + // Upstream calls ast.literal_eval on the token, which rejects + // malformed escape sequences. We validate only the two specific + // cases upstream asserts in tests: a trailing unpaired backslash + // (the closing quote is "escaped"), and a truncated \x escape. + if err := validateQuotedStringContents(val); err != nil { + return nil, t.NewSyntaxErrorAt(err.Error(), tok.Pos, tok.Pos+len(tok.Text)) + } + return Literal{Value: val}, nil } return nil, t.NewSyntaxError("Expected a marker variable or quoted string") } @@ -341,6 +354,50 @@ func parseMarkerOp(t *Tokenizer) (CompareOp, error) { return "", t.NewSyntaxError("Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in") } +// validateQuotedStringContents checks for the two specific malformed escape +// cases that upstream's ast.literal_eval rejects: a trailing unpaired +// backslash, and a truncated \x escape (not followed by two hex digits). +// Returning nil means the string is valid (or contains other escape sequences +// we do not validate). A non-nil error's message is "Invalid quoted string", +// matching upstream. +// It walks the string ONCE, left to right, consuming each escape sequence as a +// unit. A single pass is required, not two independent scans: an escaped +// backslash consumes BOTH of its bytes, so `\\x` is a complete pair followed by +// a literal "x" -- not a truncated \x escape. Scanning for `\x` separately from +// the trailing-backslash check has no way to know which backslashes were +// already consumed, and falsely rejects `"C:\\xyz"`, `"a\\x"`, and `"\\x"` -- +// all of which upstream accepts. +func validateQuotedStringContents(s string) error { + for i := 0; i < len(s); i++ { + if s[i] != '\\' { + continue + } + // A backslash at the very end is unpaired: the escape is unterminated. + // This is upstream's `"C:\"` case. + if i+1 >= len(s) { + return &SyntaxError{Msg: "Invalid quoted string"} + } + if s[i+1] == 'x' { + // \x requires exactly two hex digits. This is upstream's `"\x"` + // (and `"\x4"`, `"\xZZ"`) case. + if i+3 >= len(s) || !isHexDigit(s[i+2]) || !isHexDigit(s[i+3]) { + return &SyntaxError{Msg: "Invalid quoted string"} + } + i += 3 // consume \xNN + continue + } + // Any other escape (including \\, \n, \t, \', \") consumes exactly two + // bytes. We deliberately do not validate \u/\U/octal -- see the package + // note on why full Python escape semantics are out of scope. + i++ + } + return nil +} + +func isHexDigit(c byte) bool { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') +} + // normalizeExtraLiteral normalizes the Literal side of a comparison against // the "extra" EnvVar via extras.Normalize, once, at parse time - handling // both operand orders ("extra == 'X'" and "'X' == extra") - so evaluation diff --git a/internal/pep508/requirement.go b/internal/pep508/requirement.go index 66b0955..7f7a49f 100644 --- a/internal/pep508/requirement.go +++ b/internal/pep508/requirement.go @@ -143,8 +143,25 @@ func parseRequirementDetails(t *Tokenizer, req *RawRequirement) error { if t.peek(End) { return nil } - if _, err := t.expect(WS, "whitespace after URL"); err != nil { - return err + // Consume horizontal whitespace and any immediately following line + // breaks. PEP 508 requires whitespace after a URL; a newline is valid + // (common in "defensively multiline" Requires-Dist metadata) and must + // be consumed here so a following "; marker" clause is recognized. + if !t.consume(WS) { + // No horizontal whitespace found; check for a line break. + if t.pos < len(t.source) && (t.source[t.pos] == '\n' || t.source[t.pos] == '\r') { + // Consume the line break(s). + for t.pos < len(t.source) && (t.source[t.pos] == '\n' || t.source[t.pos] == '\r') { + t.pos++ + } + } else { + return t.NewSyntaxError("Expected whitespace after URL") + } + } else { + // Consumed horizontal whitespace; also consume any following line breaks. + for t.pos < len(t.source) && (t.source[t.pos] == '\n' || t.source[t.pos] == '\r') { + t.pos++ + } } if t.peek(End) { return nil @@ -165,7 +182,9 @@ func parseRequirementDetails(t *Tokenizer, req *RawRequirement) error { // parenthesized, comma-separated run of version-specifier clauses. It // returns the raw specifier text (parens stripped, clauses rejoined with // ","), or "" if no version specifier is present at all - which is legal, -// since versionspec is entirely optional in name_req. +// since versionspec is entirely optional in name_req. An empty parenthesized +// group ("name()") is also legal and likewise yields "", matching +// pypa/packaging's test_empty_specifier. func parseVersionSpec(t *Tokenizer) (string, error) { t.consume(WS) parenthesized := t.check(LParen) @@ -188,8 +207,6 @@ func parseVersionSpec(t *Tokenizer) (string, error) { clauses = append(clauses, normalizeSpecifierClause(specTok.Text)) t.consume(WS) } - } else if parenthesized { - return "", t.NewSyntaxError("Expected version specifier inside parentheses") } if parenthesized { diff --git a/internal/pep508/tokenizer.go b/internal/pep508/tokenizer.go index 64c329a..1203e86 100644 --- a/internal/pep508/tokenizer.go +++ b/internal/pep508/tokenizer.go @@ -40,9 +40,13 @@ const ( // "platform_python_implementation". Folding the alias to its // canonical name is the marker parser's job, not the tokenizer's. Variable - // QuotedString matches a single- or double-quoted string literal. - // PEP 508 quoted strings have no escape syntax; a double-quoted - // string may embed unescaped single quotes and vice versa. + // QuotedString matches a single- or double-quoted string literal. The + // rule is deliberately permissive and matches upstream's exactly + // ('[^']*' / "[^"]*"), so a double-quoted string may embed unescaped + // single quotes and vice versa, and a backslash tokenizes fine. + // Upstream then validates the token via ast.literal_eval, i.e. Python + // string escapes ARE meaningful on input; see validateQuotedStringContents + // in marker.go for the subset we validate. QuotedString // End matches only at the end of the source (zero-width). End @@ -138,9 +142,12 @@ type Token struct { } // Unquoted returns a QuotedString token's value with its surrounding quote -// characters stripped. No escape processing is performed, since PEP 508 -// quoted strings support none; this mirrors packaging's _parser.py, which -// takes token.text[1:-1] directly. +// characters stripped. No escape processing is performed: while +// pypa/packaging calls ast.literal_eval on the token to decode Python +// string-literal escapes (\n, \\, \x41, etc.), we deliberately do not +// implement full escape decoding here (out of scope). We validate only the +// two specific malformed cases upstream asserts in tests: a trailing unpaired +// backslash and a truncated \x escape. func (t Token) Unquoted() string { if len(t.Text) < 2 { return t.Text @@ -168,7 +175,7 @@ func (t Token) Unquoted() string { // TestIdentifier_NeverCheckedAfterWordCharWithNoBoundary in // requirement_test.go. var tokenRules = map[Kind]*regexp.Regexp{ - WS: regexp.MustCompile(`\A\s+`), + WS: regexp.MustCompile(`\A[ \t]+`), LParen: regexp.MustCompile(`\A\(`), RParen: regexp.MustCompile(`\A\)`), OP: regexp.MustCompile(`\A(?:===|==|~=|!=|<=|>=|<|>)`), diff --git a/requirement/conformance_test.go b/requirement/conformance_test.go new file mode 100644 index 0000000..3c5a4c9 --- /dev/null +++ b/requirement/conformance_test.go @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// This file contains ONLY cases ported from pypa/packaging's test suite, one +// Go table per upstream test function. Hand-written cases belong in +// requirement_test.go. +// +// Where our expected value differs from upstream's literal assertion, the +// difference is annotated inline with a reason. An UNANNOTATED divergence from +// upstream is a bug in this file, NOT a licence to change the library. +// +// Known intentional divergences: +// extras - we canonicalize at parse time; upstream's Requirement.extras +// keeps the raw spelling and canonicalizes only in __eq__/__hash__. +// Compare canonicalized on BOTH sides. +// marker - our Marker.String() normalizes quoting and spacing; compare +// against marker.Parse(upstreamString).String(), not the raw text. +// +// Upstream pinned at 4eb0753dba8fcaaac8eb75463374e448f0931558. + +package requirement_test + +import ( + "sort" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/marker" + "github.com/posit-dev/go-python-packaging/requirement" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// pypa/packaging renders the marker separator CONDITIONALLY: "; " when the +// requirement has no URL, " ; " when it does. Verified against packaging 26.2: +// +// marker, no url -> 'package; python_version >= "3.3"' +// marker + url -> 'package @ https://e/p.zip ; python_version >= "3.3"' +// +// Ported from tests/test_requirements.py, test_normalized_requirements and +// the str(req) assertions of test_basic_valid_requirement_parsing. +func TestRequirement_String_MarkerSeparator(t *testing.T) { + tests := []struct { + in string + want string + }{ + {`name; os_name == "a"`, `name; os_name == "a"`}, + {`name>=1; python_version >= "3.3"`, `name>=1; python_version >= "3.3"`}, + {`name[x]<2; os_name == "a"`, `name[x]<2; os_name == "a"`}, + // With a URL, upstream uses " ; " -- we already match this. + { + `name @ https://e.com/p.zip ; python_version >= "3.3"`, + `name @ https://e.com/p.zip ; python_version >= "3.3"`, + }, + // No marker at all: no separator either way. + {`name>=1`, `name>=1`}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + r, err := requirement.Parse(tt.in) + require.NoError(t, err, "input %q", tt.in) + assert.Equal(t, tt.want, r.String(), "input %q", tt.in) + }) + } +} + +// Ported from pypa/packaging tests/test_requirements.py, +// test_basic_valid_requirement_parsing. Upstream stacks five +// @pytest.mark.parametrize decorators for 5,184 cases; the curated subset +// below was measured to cover every block the full cross-product reaches, so +// transcribing all 5,184 buys nothing. Whitespace contributes zero coverage +// blocks, so it is swept once rather than crossed with everything. +// +// The rule's six clauses generate overlapping tuples (54 raw), so add() +// deduplicates and the table runs 49 cases. Measured: the 49-case set's +// covered-block set is a strict superset of the full 5,184-case product's -- +// nothing is missed, and it reaches 7 blocks MORE because it runs the real +// assertions rather than only Parse. +// +// Curation rule (keep this reproducible): +// 1. all 18 (url, specifier) values x {no marker, simple marker} +// 2. each of the 6 names once +// 3. each of the 4 extras shapes once +// 4. each of the 4 markers once +// 5. each of the 3 whitespace values once, with a marker present +// 6. one url + extras + marker interaction case +const noURL = "\x00" // sentinel for Python's None (url absent) + +var ( + confNames = []string{"package", "pAcKaGe", "Package", "foo-bar.quux_bAz", "installer", "android12"} + confExtras = [][]string{nil, {"a"}, {"a", "b"}, {"a", "B", "CDEF123"}} + confUS = [][2]string{ + {noURL, ""}, + {"https://example.com/packagename.zip", ""}, + {"ssh://user:pass%20word@example.com/packagename.zip", ""}, + {"https://example.com/name;v=1.1/?query=foo&bar=baz#blah", ""}, + {"git+ssh://git.example.com/MyProject", ""}, + {"git+ssh://git@github.com:pypa/packaging.git", ""}, + {"git+https://git.example.com/MyProject.git@master", ""}, + {"git+https://git.example.com/MyProject.git@v1.0", ""}, + {"git+https://git.example.com/MyProject.git@refs/pull/123/head", ""}, + {"gopher:/foo/com", ""}, + {noURL, "==={ws}arbitrarystring"}, + {noURL, "({ws}==={ws}arbitrarystring{ws})"}, + {noURL, "=={ws}1.0"}, + {noURL, "({ws}=={ws}1.0{ws})"}, + {noURL, "=={ws}1.0-alpha"}, + {noURL, "<={ws}1!3.0.0.rc2"}, + {noURL, ">{ws}2.2{ws},{ws}<{ws}3"}, + {noURL, "(>{ws}2.2{ws},{ws}<{ws}3)"}, + } + confMarkers = []string{ + noURL, // sentinel: no marker clause at all + "python_version{ws}>={ws}'3.3'", + `({ws}python_version{ws}>={ws}"3.4"{ws}){ws}and extra{ws}=={ws}"oursql"`, + "sys_platform{ws}!={ws}'linux' and(os_name{ws}=={ws}'linux' or python_version{ws}>={ws}'3.3'{ws}){ws}", + } + confWS = []string{"", " ", "\t"} +) + +func subWS(s, ws string) string { return strings.ReplaceAll(s, "{ws}", ws) } + +// buildConfCase mirrors upstream's builder at test_requirements.py:133-151. +// Two details matter: extras are sorted() and joined with "{ws},{ws}", and a +// URL+marker case appends a hardcoded " ;" while a non-URL case appends ";". +func buildConfCase(name string, extras []string, us [2]string, mk, ws string) string { + parts := []string{name} + if len(extras) > 0 { + s := append([]string(nil), extras...) + sort.Strings(s) // Python sorted(): codepoint order, uppercase first + parts = append(parts, "[", strings.Join(s, ws+","+ws), "]") + } + if us[1] != "" { + parts = append(parts, subWS(us[1], ws)) + } + if us[0] != noURL { + parts = append(parts, "@", subWS(us[0], ws)) + } + if mk != noURL { + if us[0] != noURL { + parts = append(parts, " ;") + } else { + parts = append(parts, ";") + } + parts = append(parts, subWS(mk, ws)) + } + return strings.Join(parts, ws) +} + +// canonExtras applies PEP 685 normalization so both sides of the extras +// assertion are compared the same way. Upstream keeps the raw spelling and +// canonicalizes only in __eq__; we canonicalize at parse. Sorting happens +// AFTER normalizing so the comparison is order-independent. +func canonExtras(list []string) []string { + out := make([]string, 0, len(list)) + for _, e := range list { + e = strings.ToLower(strings.TrimSpace(e)) + e = strings.ReplaceAll(e, "_", "-") + e = strings.ReplaceAll(e, ".", "-") + if e != "" { + out = append(out, e) + } + } + sort.Strings(out) + return out +} + +func TestBasicValidRequirementParsing(t *testing.T) { + type sel struct { + ni, ei, ui, mi, wi int + } + seen := make(map[sel]bool) + var cases []sel + add := func(ni, ei, ui, mi, wi int) { + s := sel{ni, ei, ui, mi, wi} + if !seen[s] { + seen[s] = true + cases = append(cases, s) + } + } + + // 1. all 18 (url, specifier) values x {no marker, simple marker} + for ui := range confUS { + add(0, 0, ui, 0, 1) + add(0, 0, ui, 1, 1) + } + // 2. each name once + for ni := range confNames { + add(ni, 0, 0, 0, 1) + } + // 3. each extras shape once + for ei := range confExtras { + add(0, ei, 0, 0, 1) + } + // 4. each marker once + for mi := range confMarkers { + add(0, 0, 0, mi, 1) + } + // 5. each whitespace value once, with a marker present + for wi := range confWS { + add(0, 0, 0, 1, wi) + } + // 6. one url + extras + marker interaction + add(0, 1, 1, 1, 1) + + for _, c := range cases { + name, extras := confNames[c.ni], confExtras[c.ei] + us, mk, ws := confUS[c.ui], confMarkers[c.mi], confWS[c.wi] + src := buildConfCase(name, extras, us, mk, ws) + + t.Run(src, func(t *testing.T) { + r, err := requirement.Parse(src) + require.NoError(t, err, "Parse(%q) should succeed", src) + + assert.Equal(t, name, r.Name, "name, input %q", src) + assert.Equal(t, canonExtras(extras), canonExtras(r.Extras), + "extras, input %q", src) + + wantURL := "" + if us[0] != noURL { + wantURL = subWS(us[0], ws) + } + assert.Equal(t, wantURL, r.URL, "url, input %q", src) + + // Upstream: req.specifier == specifier.format(ws="").strip("()") + wantSpec := strings.Trim(subWS(us[1], ""), "()") + assert.Equal(t, wantSpec, r.Specifiers.String(), "specifier, input %q", src) + + // Upstream: req.marker == Marker(marker.format(ws="")). Compare + // CONTENT, not just presence -- our Marker.String() normalizes + // quoting and spacing, so the comparison goes through a parsed + // round-trip of the expected text rather than the raw string + // (see the intentional-divergence note in this file's header). + if mk == noURL { + assert.True(t, r.Marker.IsEmpty(), "expected no marker, input %q", src) + } else { + wantMarker, err := marker.Parse(subWS(mk, "")) + require.NoError(t, err, "expected-marker text should itself parse, input %q", src) + assert.Equal(t, wantMarker.String(), r.Marker.String(), + "marker content, input %q", src) + } + }) + } + + t.Logf("curated cases: %d", len(cases)) +} + +// Ported from pypa/packaging tests/test_requirements.py, class +// TestRequirementParsing. Each entry cites the upstream test function. +// wantErr mirrors upstream's expectation, NOT our current behavior. +// +// One case is deliberately omitted: the operator-less specifier "2.0", which +// we still accept via the non-PEP-440 "" entry in specifierOperators. +// Tightening that is behavior-narrowing and user-visible, and is tracked in +// rstudio/package-manager#18634 (blocked on #19371), whose acceptance criteria +// require re-enabling this case: +// +// {"name 2.0", true, "operator-less specifier"}, +func TestRequirementParsingErrors(t *testing.T) { + tests := []struct { + in string + wantErr bool + upstream string + }{ + {"name[]", false, "test_empty_extras"}, + {"name()", false, "test_empty_specifier"}, + {"foobar", false, "test_sole_use_of_name"}, + {"foobar[quux]<2,>=3; os_name=='a'", false, "test_valid_with_all_parts"}, + {"name>=1 ", false, "test_trailing_horizontal_whitespace"}, + {"name>=1\t", false, "test_trailing_horizontal_whitespace"}, + + {"demo===x,y", true, "test_error_when_specifier_set_rejects_parsed_specifier"}, + {"", true, "test_error_when_empty_string"}, + {"==0.0", true, "test_error_no_name"}, + {"name[bar baz]", true, "test_error_when_missing_comma_in_extras"}, + {"name[bar, baz,]", true, "test_error_when_trailing_comma_in_extras"}, + {"name (>= 1.0", true, "test_error_when_parens_not_closed_correctly"}, + {"black (>=20.*) ; extra == 'format'", true, "test_error_when_prefix_match_is_used_incorrectly"}, + {"name == 1.2.3.post4.*", true, "test_error_when_prefix_match_uses_post_release"}, + {"name != 1.2.3.post4.*", true, "test_error_when_prefix_match_uses_post_release"}, + {"name==1.2.3.post4.*", true, "test_error_when_prefix_match_uses_post_release_without_spaces"}, + // Local version labels: upstream parametrizes over >=, <=, >, <, ~= ONLY. + // "==" and "!=" ALLOW a local label -- do not add them here. + {"name >= 1.0+local.version.label", true, "test_error_when_local_version_label_is_used_incorrectly"}, + {"name <= 1.0+local.version.label", true, "test_error_when_local_version_label_is_used_incorrectly"}, + {"name > 1.0+local.version.label", true, "test_error_when_local_version_label_is_used_incorrectly"}, + {"name < 1.0+local.version.label", true, "test_error_when_local_version_label_is_used_incorrectly"}, + {"name ~= 1.0+local.version.label", true, "test_error_when_local_version_label_is_used_incorrectly"}, + {"name == 1.0+local.version.label", false, "local labels ARE legal with =="}, + {"name != 1.0+local.version.label", false, "local labels ARE legal with !="}, + {"name[bar, baz >= 1.0", true, "test_error_when_bracket_not_closed_correctly"}, + {"name[bar, baz", true, "test_error_when_extras_bracket_left_unclosed"}, + {"name @ https://example.com/; extra == 'example'", true, "test_error_no_space_after_url"}, + {"name; (extra == 'example'", true, "test_error_marker_bracket_unclosed"}, + {"name @ ", true, "test_error_no_url_after_at"}, + {"name; invalid_name", true, "test_error_invalid_marker_lvalue"}, + {"name; '3.7' <= invalid_name", true, "test_error_invalid_marker_rvalue"}, + {"name; '3.7' notin python_version", true, "test_error_invalid_marker_malformed_operator"}, + {"name; '3.6'inpython_version", true, "test_error_invalid_marker_malformed_operator"}, + {"name; '3.7' not python_version", true, "test_error_invalid_marker_malformed_operator"}, + {"name; '3.7' ~ python_version", true, "test_error_invalid_marker_malformed_operator"}, + {`name; os_name == "C:\"`, true, "test_error_invalid_marker_malformed_quoted_string"}, + {"name==1.0.org1", true, "test_error_invalid_version"}, + {"name==", true, "test_error_no_version_after_operator"}, + {"name 1.0", true, "test_error_missing_operator"}, + {"name >= 1.0 #", true, "test_error_trailing_garbage"}, + {"name >= 1.0 <= 2.0", true, "test_error_missing_comma_between_specifiers"}, + + {"name>=1\n", true, "test_error_when_suffixed_with_line_break"}, + {"name>=1\r", true, "test_error_when_suffixed_with_line_break"}, + {"name>=1\r\n", true, "test_error_when_suffixed_with_line_break"}, + {`name; python_version >= "3"` + "\n", true, "test_error_when_suffixed_with_line_break"}, + {`name; python_version >= "3"` + "\r", true, "test_error_when_suffixed_with_line_break"}, + {`name; python_version >= "3"` + "\r\n", true, "test_error_when_suffixed_with_line_break"}, + } + + for _, tt := range tests { + t.Run(tt.upstream+"/"+strings.NewReplacer("\n", "LF", "\r", "CR", "\t", "TAB").Replace(tt.in), func(t *testing.T) { + _, err := requirement.Parse(tt.in) + if tt.wantErr { + assert.Error(t, err, "input %q (%s) should be rejected", tt.in, tt.upstream) + } else { + assert.NoError(t, err, "input %q (%s) should parse", tt.in, tt.upstream) + } + }) + } +} diff --git a/requirement/requirement.go b/requirement/requirement.go index c5e6b2f..3fa6cc4 100644 --- a/requirement/requirement.go +++ b/requirement/requirement.go @@ -119,7 +119,14 @@ func (r Requirement) String() string { } if !r.Marker.IsEmpty() { - b.WriteString(" ; ") + // pypa/packaging renders "; " normally but " ; " when a URL is + // present, because a bare ";" immediately after a URL would be + // ambiguous - a URL may itself contain ";". Match that exactly. + if r.URL != "" { + b.WriteString(" ; ") + } else { + b.WriteString("; ") + } b.WriteString(r.Marker.String()) } diff --git a/requirement/requirement_test.go b/requirement/requirement_test.go index c2aa474..58a8d98 100644 --- a/requirement/requirement_test.go +++ b/requirement/requirement_test.go @@ -68,10 +68,13 @@ func TestParse_VersionSpec_Parenthesized(t *testing.T) { assert.Equal(t, want.String(), r.Specifiers.String()) } -func TestParse_VersionSpec_EmptyParens_IsError(t *testing.T) { - _, err := Parse("foo()") - require.Error(t, err) - assert.True(t, errors.Is(err, ErrInvalidRequirement)) +func TestParse_VersionSpec_EmptyParens_IsValid(t *testing.T) { + // An empty parenthesized specifier is valid and means "no constraint" + // (pypa/packaging test_empty_specifier). + r, err := Parse("foo()") + require.NoError(t, err) + assert.Equal(t, "foo", r.Name) + assert.Equal(t, "", r.Specifiers.String(), "empty parens mean no specifier") } func TestParse_VersionSpec_MultipleClauses(t *testing.T) { diff --git a/version/arbitrary_equality_test.go b/version/arbitrary_equality_test.go new file mode 100644 index 0000000..c8410f3 --- /dev/null +++ b/version/arbitrary_equality_test.go @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// PEP 440 arbitrary equality ("===") compares against an opaque single token, +// which need not be a valid version. +// +// Ported from pypa/packaging tests/test_specifiers.py, the "===" entries of +// TestSpecifier.test_specifiers_valid and test_arbitrary_equality. +// Pinned: 4eb0753dba8fcaaac8eb75463374e448f0931558. +func TestNewSpecifiers_ArbitraryEqualityAcceptsSingleToken(t *testing.T) { + valid := []string{ + "===lolwat", + "=== lolwat", + "===1.0", + "===v1.0", + "===1.0+abc", + "===arbitrarystring", + } + for _, s := range valid { + t.Run(s, func(t *testing.T) { + specs, err := NewSpecifiers(s) + require.NoError(t, err, "input %q should parse", s) + count := 0 + for _, g := range specs.specifiers { + count += len(g) + } + assert.Equal(t, 1, count, "input %q yielded %d specifiers (String()=%q)", + s, count, specs.String()) + }) + } +} + +// Arbitrary equality takes ONE token. An operand containing internal +// whitespace is rejected by pypa/packaging 26.2 as well. +func TestNewSpecifiers_ArbitraryEqualityRejectsMultipleTokens(t *testing.T) { + invalid := []string{ + "===any string here", + "===lolwat and stuff", + } + for _, s := range invalid { + t.Run(s, func(t *testing.T) { + _, err := NewSpecifiers(s) + assert.Error(t, err, "input %q should be rejected", s) + }) + } +} diff --git a/version/operator_order_test.go b/version/operator_order_test.go new file mode 100644 index 0000000..c637489 --- /dev/null +++ b/version/operator_order_test.go @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The operator alternation must be built in a deterministic, longest-first +// order. Go's regexp is leftmost-FIRST, not leftmost-longest, so an +// alternative that is a prefix of a later one wins: "=" would swallow the +// first character of "==" and "===". The empty operator matches anything and +// must come last. +// +// This is pinned rather than merely sorted because Task 2 relaxes the "===" +// operand pattern, removing the trailing PEP-440-shaped group that currently +// forces backtracking to the correct operator. See rstudio/package-manager#19369 +// for the same bug in the pre-release alternation. +func TestOperatorAlternationIsDeterministic(t *testing.T) { + // The empty operator is the last alternative and contributes an empty + // string, so the joined form ends with a trailing "|". That is correct and + // intentional: an empty trailing alternative is how the operator-less + // specifier form is expressed in the regexp. + want := "===|==|!=|<=|>=|~=|<|>|=|" + got := strings.Join(orderedOperatorPatterns(), "|") + assert.Equal(t, want, got, "operator alternation order changed") +} + +func TestOperatorAlternationLongestFirst(t *testing.T) { + ops := orderedOperatorPatterns() + for i, a := range ops { + for j := i + 1; j < len(ops); j++ { + b := ops[j] + assert.False(t, strings.HasPrefix(b, a), + "%q at index %d is a prefix of %q at index %d; longer alternatives must come first", + a, i, b, j) + } + } +} + +// The empty operator matches anything, so it must be last. +func TestEmptyOperatorIsLast(t *testing.T) { + ops := orderedOperatorPatterns() + require.NotEmpty(t, ops) + // The empty operator is represented by the empty string; QuoteMeta("") is "". + for i, o := range ops { + if o == "" { + assert.Equal(t, len(ops)-1, i, "the empty operator must be the last alternative") + } + } +} + +// A specifier string must never yield more specifiers than it has operators. +// This is the invariant that generalizes rstudio/package-manager#19369: there, +// a truncated pre-release token left a trailing fragment that was harvested as +// a second, operator-less specifier, so "==1.0alpha1" parsed cleanly and then +// matched nothing. +func TestSpecifierCountMatchesOperatorCount(t *testing.T) { + tests := []struct { + in string + want int + }{ + {"==1.0", 1}, + {"==1.0alpha1", 1}, + {"==1.0-beta2", 1}, + {"==1.0preview1", 1}, + {"==1.0rev1", 1}, + {">1.0,<2.0", 2}, + {">=1.0,!=1.5,<2.0", 3}, + {"~=1.0", 1}, + {"===1.0", 1}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + specs, err := NewSpecifiers(tt.in) + require.NoError(t, err, "input %q", tt.in) + count := 0 + for _, group := range specs.specifiers { + count += len(group) + } + assert.Equal(t, tt.want, count, + "input %q parsed to %d specifiers (String()=%q)", tt.in, count, specs.String()) + }) + } +} diff --git a/version/prefix_match_test.go b/version/prefix_match_test.go new file mode 100644 index 0000000..3df8b60 --- /dev/null +++ b/version/prefix_match_test.go @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// A ".*" prefix match may not be combined with a dev, local, OR post release. +// The post-release half was missing. +// +// Ported from pypa/packaging tests/test_requirements.py, +// TestRequirementParsing.test_error_when_prefix_match_uses_post_release +// (parametrized over "==" and "!=") and its _without_spaces sibling, plus the +// pre/post entries of tests/test_specifiers.py's test_specifiers_invalid. +// Pinned: 4eb0753dba8fcaaac8eb75463374e448f0931558. +func TestNewSpecifiers_RejectsWildcardOnPostRelease(t *testing.T) { + invalid := []string{ + "==2.0.post1.*", + "!=2.0.post1.*", + "==1.2.3.post4.*", + "!=1.2.3.post4.*", + } + for _, s := range invalid { + t.Run(s, func(t *testing.T) { + _, err := NewSpecifiers(s) + assert.Error(t, err, "input %q should be rejected", s) + }) + } +} + +// Regression guard: the dev and local halves of the same rule must keep working, +// and legitimate wildcards must keep parsing. +func TestNewSpecifiers_WildcardRuleUnchangedCases(t *testing.T) { + invalid := []string{"==1.0.dev1.*", "!=1.0.dev1.*", "==1.0.*+5", "!=1.0.*+deadbeef"} + for _, s := range invalid { + t.Run("invalid_"+s, func(t *testing.T) { + _, err := NewSpecifiers(s) + assert.Error(t, err, "input %q should be rejected", s) + }) + } + valid := []string{"==1.0.*", "!=2.2.*", "==2.1.*"} + for _, s := range valid { + t.Run("valid_"+s, func(t *testing.T) { + _, err := NewSpecifiers(s) + assert.NoError(t, err, "input %q should parse", s) + }) + } +} diff --git a/version/specifier.go b/version/specifier.go index a189ac9..b1ddbdd 100644 --- a/version/specifier.go +++ b/version/specifier.go @@ -30,15 +30,47 @@ var ( prefixRegexp *regexp.Regexp ) -func init() { - ops := make([]string, 0, len(specifierOperators)) - for k := range specifierOperators { - ops = append(ops, regexp.QuoteMeta(k)) +// orderedOperatorPatterns returns the regexp-quoted comparison operators in a +// deterministic order suitable for a regexp alternation. +// +// Go's regexp is leftmost-FIRST, not leftmost-longest, so an alternative that +// is a prefix of a later one wins the match: listing "=" before "==" makes +// "==1.0" parse with operator "=" and version "=1.0". Order longest-first, and +// keep the empty operator (which matches anything) last. Ranging over the +// specifierOperators map directly would randomize this per process. +func orderedOperatorPatterns() []string { + // Longest-first; "" last because it matches anything. + ordered := []string{"===", "==", "!=", "<=", ">=", "~=", "<", ">", "="} + out := make([]string, 0, len(ordered)+1) + for _, op := range ordered { + if _, ok := specifierOperators[op]; !ok { + panic("orderedOperatorPatterns: unknown operator " + op) + } + out = append(out, regexp.QuoteMeta(op)) + } + if _, ok := specifierOperators[""]; ok { + out = append(out, regexp.QuoteMeta("")) } + if len(out) != len(specifierOperators) { + panic("orderedOperatorPatterns: operator list is out of sync with specifierOperators") + } + return out +} + +func init() { + ops := orderedOperatorPatterns() + + // Arbitrary equality ("===") compares an opaque token, which need not be a + // valid PEP 440 version. Give it its own branch with a non-whitespace-run + // operand; every other operator keeps the version-shaped operand. The + // arbitrary branch is FIRST because Go's regexp is leftmost-first and + // "===" must not be decomposed into "==" + "=". + const arbitraryOperand = `[^\s,;)]+` specifierRegexp = regexp.MustCompile( fmt.Sprintf( - `(?i)(?P(%s))\s*(?P%s(\.\*)?)`, + `(?i)(?:(?P===)\s*(?P%s)|(?P(%s))\s*(?P%s(\.\*)?))`, + arbitraryOperand, strings.Join(ops, "|"), regex, ), @@ -46,7 +78,8 @@ func init() { validConstraintRegexp = regexp.MustCompile( fmt.Sprintf( - `^\s*(\s*(%s)\s*(%s(\.\*)?)\s*\,?)*\s*$`, + `^\s*(\s*(?:===\s*%s|(%s)\s*(%s(\.\*)?))\s*\,?)*\s*$`, + arbitraryOperand, strings.Join(ops, "|"), regex, ), @@ -180,7 +213,13 @@ func newSpecifier(s string, sanitizer func(s string) string) (specifier, error) operator := m[specifierRegexp.SubexpIndex("operator")] version := m[specifierRegexp.SubexpIndex("version")] - version = sanitizer(version) + if arbitrary := m[specifierRegexp.SubexpIndex("arbitrary")]; arbitrary != "" { + // Arbitrary equality: the operand is an opaque token, used verbatim. + operator = m[specifierRegexp.SubexpIndex("arbitraryop")] + version = arbitrary + } else { + version = sanitizer(version) + } if operator != "===" { if err := validate(operator, version); err != nil { @@ -208,9 +247,9 @@ func validate(operator, version string) error { switch operator { case "", "=", "==", "!=": - if hasWildcard && (!v.dev.isNull() || v.local != "") { + if hasWildcard && (!v.dev.isNull() || !v.post.isNull() || v.local != "") { return errors.New( - "the (non)equality operators don't allow to use a wild card and a dev or local version together", + "the (non)equality operators don't allow to use a wild card and a dev, post, or local version together", ) } case "~=": diff --git a/version/specifier_test.go b/version/specifier_test.go index 8653b05..095ae22 100644 --- a/version/specifier_test.go +++ b/version/specifier_test.go @@ -27,8 +27,7 @@ func TestNewConstraints(t *testing.T) { {"<1.0.dev1", false}, {">2.0.post1", false}, - // TODO - // {"===lolwat", false}, + {"===lolwat", false}, // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L50-L86 // Operator-less specifier @@ -107,8 +106,7 @@ func TestNewRSpecifiers(t *testing.T) { {"<1.0.dev1", false}, {">2.0.post1", false}, - // TODO - // {"===lolwat", false}, + {"===lolwat", false}, // https://github.com/pypa/packaging/blob/28d2fa0742747cda4bc4530b2a5bc919b7382039/tests/test_specifiers.py#L50-L86 // Operator-less specifier @@ -201,8 +199,6 @@ func TestVersion_Check(t *testing.T) { {"2", "==2.*", true}, {"2.0", "==2.*", true}, {"2.0.0", "==2.*", true}, - {"2.0.post1", "==2.0.post1.*", true}, - {"2.0.post1.dev1", "==2.0.post1.*", true}, {"2.1+local.version", "==2.1.*", true}, // Test the in-equality operation @@ -305,8 +301,6 @@ func TestVersion_Check(t *testing.T) { {"2", "!=2.*", false}, {"2.0", "!=2.*", false}, {"2.0.0", "!=2.*", false}, - {"2.0.post1", "!=2.0.post1.*", false}, - {"2.0.post1.dev1", "!=2.0.post1.*", false}, //Test the greater than equal operation {"2.0.dev1", ">=2", false},