Repository navigation
feat(reqtxt): pip requirements.txt parser (#18639) - #8
Merged
Merged
Conversation
Add the reqtxt package's foundational data model: File/Entry types (RequirementEntry, IncludeEntry, UnnamedEntry, OptionEntry), Kind, Hash, and ErrInvalidRequirementsFile, plus *File accessors (Requirements/Includes/Options and typed option lookups for --index-url, --extra-index-url, --find-links, --trusted-host, --no-binary, --only-binary, --no-index, --require-hashes, --pre, --prefer-binary). Scalars use last-occurrence-wins semantics; list options accumulate in order; booleans are true iff present. This is the foundation for later Parse/Flatten tasks in this package.
Add shlexSplit, matching Python's shlex.split(line, comments=False, posix=True) as used by pip's requirements-file line splitting: unquoted whitespace separates words, single quotes are fully literal, double quotes allow \ to escape only " and \, and a bare backslash escapes the next character. Implemented as a hand-written normal/single/double state machine (no regexp).
… set (#18639)
- Add TestShlexSplit_Errors cases for a trailing bare backslash after a
word (`a\`) and a lone backslash (`\`), exercising the stateNormal
branch that raises "trailing unescaped backslash" (previously
untested; unterminated-quote tests only hit the post-loop quote-state
checks).
- Replace unicode.IsSpace with a new isShlexSpace helper restricted to
Python shlex's default whitespace set (" \t\r\n"), dropping the now
unused unicode import. Add table cases confirming form feed and
vertical tab no longer split a word.
Ports pip req_file.preprocess: normalize line endings, join backslash
continuations with no separator, strip comments (COMMENT_RE), drop
blank lines, trim, and optionally expand ${VAR} (ENV_VAR_RE) via the
new WithEnv ParseOption. Tracks 1-based physical line numbers through
continuation joins for later error reporting.
Add classifyTarget and eggName, pure string-shape classifiers used by the Task 5 Parse dispatcher to distinguish pip's VCS/URL/archive/path requirement forms from PEP 508 requirements before falling back to requirement.Parse. Order: VCS scheme prefix, URL scheme, archive extension (longest suffix first), then generic path shape. Unlike pip's is_url/is_archive_file, this never touches the filesystem.
Adds the line dispatcher that turns preprocess()'d logical lines into typed Entry values: -r/-c includes, -e editable targets, known and unknown file-level flags (with the boolean/value-consuming rules pip's break_args_options uses), and per-requirement --hash/--config-settings options attached to RequirementEntry/UnnamedEntry. Every error wraps ErrInvalidRequirementsFile plus the offending physical line number, and a failed requirement.Parse additionally satisfies errors.Is(_, requirement.ErrInvalidRequirement) via errors.Join.
…ions (#18639)
Parse used to shlex-tokenize an entire package/requirement line and
require every token after tokens[0] to be a per-line option, so valid
PEP 508 lines with unquoted whitespace in the specifier or marker
("Django >= 3.2, < 4.0", `flask ; python_version >= "3.8"`) errored.
Port pip's break_args_options: split only on the boundary between the
requirement text and its options tail, pass the requirement text
verbatim (quotes/spacing intact) to classifyTarget/requirement.Parse,
and shlex-tokenize only the options tail. The -r/-c/-e/file-option
dispatch path is unchanged.
Also reject an "=value" given to a known arity-0 boolean option (e.g.
"--no-index=x"), matching pip optparse's rejection of a value for an
option that doesn't take one.
…ments (#18639) UnnamedEntry has no Marker field, so a trailing "; marker" clause (or any other extra content) after a bare VCS/URL/archive/path target was silently glued into Raw/EggName instead of being rejected, corrupting the target string. Require the target to be the line's sole token and error out otherwise, restoring the pre-break_args_options-fix loud failure for this input shape. Also adds a regression test for the quoted-"-bar" marker case, proving a quoted value starting with "-" inside a marker doesn't trip the options-tail split.
Add File.String(), rendering each parsed entry (RequirementEntry, UnnamedEntry, IncludeEntry, OptionEntry) back to a canonical requirements.txt line so Parse(f.String()) yields a semantically equivalent File. Comments and blank lines are not reconstructed, since Parse already drops them. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…values) (#18639)
renderFileOption rendered a non-empty file-level OptionEntry value in
space form ("--name value"), which does not round-trip for an unknown
flag: dispatchFileOption only recovers a value from the inline
"=value" form for unrecognized flags, so a bare "--unknown" reparses
as boolean and the following token becomes a phantom separate entry
(e.g. Parse("--cert=/etc/ssl/ca.pem") silently corrupted through a
String()/Parse() round trip). Render all option values (file-level,
per-line, and --hash) uniformly via the "=" form, and quote values
containing whitespace or a double quote so they survive shlex
re-tokenization on reparse.
…hing pip (#18639) flattenWalk previously OR'd the parent constraint context into a nested include's constraint-ness (transitive closure), so a -r nested inside a -c-included file stayed a constraint. Verified against pip's actual behavior in pip._internal.req.req_file.RequirementsFileParser ._parse_and_recurse: nested_constraint is computed solely from the immediate include directive (-r => False, -c => True) and is never OR'd with the ambient constraint flag. Fix childConstraint to use v.Constraint alone, update the code comments to cite pip's source, and update/add tests covering both nesting directions.
…e semantics (#18639)
Rewrite the reqtxt package doc comment to describe the implemented Parse/Flatten/WithEnv API, drop the stale TODO, add a NOTICE paragraph for the pip req_file and uv-requirements adaptations, and mark the reqtxt/ row implemented in the README package table.
…y option values (#18639) - preprocess: a physical line ending in "\" is no longer treated as a continuation when it is itself a whole-line comment (first non-whitespace char is "#"), matching pip's join_lines guard (COMMENT_RE.match(line), req_file.py:501). Previously "# note \" followed by a real requirement line joined onto the comment and was stripped entirely, silently dropping the requirement. Inline comments ending in "\" are unaffected and still join. - string: renderOption now renders an empty Value as the explicit `name=""` form for value-taking options (known arity-1 file options or per-line value options), instead of a bare flag that would reparse as a boolean and fail the option's "requires a value" check. Boolean/ arity-0 options and unrecognized flags still render bare.
…insensitive VCS, reordered egg (#18639) Four RoboRev-flagged robustness fixes in the reqtxt package: - resolveInclude now resolves a relative include target against a URL-hosted referencing file with net/url reference resolution, instead of mangling it with slash-based path.Dir/path.Join. - Comment detection (stripping and the whole-line continuation guard) now uses Unicode whitespace (matching Python re's \s, which pip's COMMENT_RE relies on) instead of Go RE2's ASCII-only \s. - classifyTarget's VCS scheme-prefix check is now case-insensitive, matching the URL/archive checks that already lowercase first. - eggName now finds the egg= fragment parameter regardless of its position among &-separated fragment params, instead of only recognizing a literal leading "#egg=".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements
reqtxt/— a parser for pip'srequirements.txtfile format — the final Phase 1 package of the native Go PyPI resolver (RFD 0001, epic rstudio/package-manager#18625). Builds on the mergedrequirement/(PEP 508) package.Closes rstudio/package-manager#18639.
What
Parse(content string, opts ...ParseOption) (*File, error)— a pure, no-I/O parser producing an ordered[]Entry(requirements,-r/-cincludes, unnamed URL/VCS/archive/path targets, options) plus typed accessors (IndexURL,ExtraIndexURLs,FindLinks,NoIndex,NoBinary/OnlyBinary/PreferBinary,RequireHashes,Pre,TrustedHosts).Flatten(root string, open func(path string) ([]byte, error), opts ...ParseOption) (*File, error)— follows-r/-cincludes through a caller-supplied opener (real FS, in-memory, or virtual), with relative-path resolution, current-stack cycle detection, and UTF-8/BOM decoding. No hidden I/O.WithEnv(lookup)— opt-in${VAR}expansion;File.String()— round-trippable rendering.Design notes (pip-anchored)
req_file.preprocess(line-ending normalize → continuation join → comment strip → env expand), including the guard that a whole-line comment ending in\is not a continuation.break_args_optionssplit: the requirement text is taken verbatim (quotes preserved, so markers likepython_version >= "3.8"survive) and only the options tail is shell-tokenized.foo-1.0.tar.gzis a local-archive reference, not a bogus named requirement).-r/-cdirective and is not inherited through nested includes — matching pip's_parse_and_recurse(verified against the pip source).Deliberate, documented divergences from pip
Markerfield on those entries yet — a documented not-yet-supported limitation).Verification
Per commit:
go build,go vet,go test,gofmt -l(empty),golangci-lint run ./...(v2, 0 issues). Behavior anchored on pip'sreq_file(a reference copy was read directly to confirm the continuation-comment guard and the constraint-nesting rule). No runtime deps beyond the standard library and the siblingrequirement/marker/version/extraspackages.