From fcded9ca566ea9f7ba97e157f29d017e1b33d3ef Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 19:05:00 -0400 Subject: [PATCH 01/16] feat(reqtxt): entry model + file accessors (#18639) 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. --- reqtxt/types.go | 253 +++++++++++++++++++++++++++++++++++++++++++ reqtxt/types_test.go | 212 ++++++++++++++++++++++++++++++++++++ 2 files changed, 465 insertions(+) create mode 100644 reqtxt/types.go create mode 100644 reqtxt/types_test.go diff --git a/reqtxt/types.go b/reqtxt/types.go new file mode 100644 index 0000000..a413000 --- /dev/null +++ b/reqtxt/types.go @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + + "github.com/posit-dev/go-python-packaging/requirement" +) + +// ErrInvalidRequirementsFile is the sentinel wrapped by errors returned +// while parsing a malformed requirements.txt file. +var ErrInvalidRequirementsFile = errors.New("invalid requirements file") + +// File is a parsed requirements.txt (or constraints) file: an ordered list +// of the entries it contains, in file order. +type File struct { + Entries []Entry +} + +// Entry is one line's worth of parsed requirements.txt content. It is +// implemented by *RequirementEntry, *IncludeEntry, *UnnamedEntry, and +// *OptionEntry. +type Entry interface { + entry() +} + +// RequirementEntry is a PEP 508 requirement line (e.g. "flask==2.0 ; +// python_version >= '3.8'"), optionally followed by "--hash" and other +// per-requirement options on continuation lines. +type RequirementEntry struct { + Requirement requirement.Requirement + Hashes []Hash + Options []OptionEntry + // Constraint is true if this entry came from a file included via + // "-c"/"--constraint" (or transitively from one), rather than + // "-r"/"--requirement" or the top-level file. + Constraint bool +} + +func (*RequirementEntry) entry() {} + +// IncludeEntry is a "-r"/"--requirement" or "-c"/"--constraint" directive +// referencing another requirements/constraints file. +type IncludeEntry struct { + Path string + // Constraint is true if this include used "-c"/"--constraint" rather + // than "-r"/"--requirement". + Constraint bool +} + +func (*IncludeEntry) entry() {} + +// UnnamedEntry is a requirement line that isn't a plain PEP 508 +// requirement: a VCS reference, a direct URL, a local path, or an editable +// install ("-e") of any of those. Its Raw field preserves the original +// requirement specifier text for later classification/parsing. +type UnnamedEntry struct { + Raw string + Kind Kind + Editable bool + // EggName is the "#egg=name" fragment, if present. + EggName string + Hashes []Hash + Options []OptionEntry + // Constraint is true if this entry came from a file included via + // "-c"/"--constraint" (or transitively from one), rather than + // "-r"/"--requirement" or the top-level file. + Constraint bool +} + +func (*UnnamedEntry) entry() {} + +// OptionEntry is a global pip option line (e.g. "--index-url +// https://example.com/simple"), as opposed to a per-requirement option +// attached to a RequirementEntry or UnnamedEntry. +type OptionEntry struct { + Name string + Value string +} + +func (*OptionEntry) entry() {} + +// Kind identifies the flavor of requirement specifier an UnnamedEntry +// represents. +type Kind int + +const ( + // KindVCS is a VCS reference (e.g. "git+https://..."). + KindVCS Kind = iota + // KindURL is a direct URL to a source archive or wheel. + KindURL + // KindLocalPath is a path to a local directory or archive. + KindLocalPath +) + +// String renders k as a readable name, primarily so test failures are +// legible. +func (k Kind) String() string { + switch k { + case KindVCS: + return "vcs" + case KindURL: + return "url" + case KindLocalPath: + return "local-path" + default: + return "unknown" + } +} + +// Hash is a "--hash" value attached to a requirement, used for +// hash-checking mode. +type Hash struct { + Algorithm string + Digest string +} + +// Canonical long option names, as used by OptionEntry.Name. +const ( + optIndexURL = "--index-url" + optExtraIndexURL = "--extra-index-url" + optNoIndex = "--no-index" + optFindLinks = "--find-links" + optRequireHashes = "--require-hashes" + optPre = "--pre" + optTrustedHost = "--trusted-host" + optNoBinary = "--no-binary" + optOnlyBinary = "--only-binary" + optPreferBinary = "--prefer-binary" +) + +// Requirements returns the RequirementEntry values in f.Entries, in file +// order. +func (f *File) Requirements() []RequirementEntry { + var out []RequirementEntry + for _, e := range f.Entries { + if r, ok := e.(*RequirementEntry); ok { + out = append(out, *r) + } + } + return out +} + +// Includes returns the IncludeEntry values in f.Entries, in file order. +func (f *File) Includes() []IncludeEntry { + var out []IncludeEntry + for _, e := range f.Entries { + if i, ok := e.(*IncludeEntry); ok { + out = append(out, *i) + } + } + return out +} + +// Options returns the OptionEntry values in f.Entries, in file order. +func (f *File) Options() []OptionEntry { + var out []OptionEntry + for _, e := range f.Entries { + if o, ok := e.(*OptionEntry); ok { + out = append(out, *o) + } + } + return out +} + +// IndexURL returns the value of the last "--index-url" option in f, and +// whether one was present at all. +func (f *File) IndexURL() (string, bool) { + var ( + value string + found bool + ) + for _, o := range f.Options() { + if o.Name == optIndexURL { + value = o.Value + found = true + } + } + return value, found +} + +// ExtraIndexURLs returns the values of all "--extra-index-url" options in +// f, in file order. +func (f *File) ExtraIndexURLs() []string { + return optionValues(f.Options(), optExtraIndexURL) +} + +// FindLinks returns the values of all "--find-links" options in f, in file +// order. +func (f *File) FindLinks() []string { + return optionValues(f.Options(), optFindLinks) +} + +// TrustedHosts returns the values of all "--trusted-host" options in f, in +// file order. +func (f *File) TrustedHosts() []string { + return optionValues(f.Options(), optTrustedHost) +} + +// NoBinary returns the values of all "--no-binary" options in f, in file +// order. +func (f *File) NoBinary() []string { + return optionValues(f.Options(), optNoBinary) +} + +// OnlyBinary returns the values of all "--only-binary" options in f, in +// file order. +func (f *File) OnlyBinary() []string { + return optionValues(f.Options(), optOnlyBinary) +} + +// NoIndex reports whether f has a "--no-index" option. +func (f *File) NoIndex() bool { + return hasOption(f.Options(), optNoIndex) +} + +// RequireHashes reports whether f has a "--require-hashes" option. +func (f *File) RequireHashes() bool { + return hasOption(f.Options(), optRequireHashes) +} + +// Pre reports whether f has a "--pre" option. +func (f *File) Pre() bool { + return hasOption(f.Options(), optPre) +} + +// PreferBinary reports whether f has a "--prefer-binary" option. +func (f *File) PreferBinary() bool { + return hasOption(f.Options(), optPreferBinary) +} + +// optionValues returns the Value of every OptionEntry in opts whose Name +// matches name, in order. +func optionValues(opts []OptionEntry, name string) []string { + var out []string + for _, o := range opts { + if o.Name == name { + out = append(out, o.Value) + } + } + return out +} + +// hasOption reports whether any OptionEntry in opts has the given Name. +func hasOption(opts []OptionEntry, name string) bool { + for _, o := range opts { + if o.Name == name { + return true + } + } + return false +} diff --git a/reqtxt/types_test.go b/reqtxt/types_test.go new file mode 100644 index 0000000..04fd963 --- /dev/null +++ b/reqtxt/types_test.go @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "testing" + + "github.com/posit-dev/go-python-packaging/requirement" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// buildMixedFile constructs a File with one of each Entry kind, plus extra +// OptionEntry/RequirementEntry/IncludeEntry values interleaved, so ordering +// and filtering can be asserted precisely. +func buildMixedFile(t *testing.T) *File { + t.Helper() + + flaskReq, err := requirement.Parse("flask") + require.NoError(t, err) + requestsReq, err := requirement.Parse("requests") + require.NoError(t, err) + + reqA := &RequirementEntry{Requirement: flaskReq} + incA := &IncludeEntry{Path: "base.txt"} + optIndex1 := &OptionEntry{Name: "--index-url", Value: "https://example.com/simple"} + unnamed := &UnnamedEntry{Raw: "./local-pkg", Kind: KindLocalPath} + reqB := &RequirementEntry{Requirement: requestsReq, Constraint: true} + incB := &IncludeEntry{Path: "constraints.txt", Constraint: true} + optIndex2 := &OptionEntry{Name: "--index-url", Value: "https://example.com/simple2"} + optExtra1 := &OptionEntry{Name: "--extra-index-url", Value: "https://extra1.example.com"} + optExtra2 := &OptionEntry{Name: "--extra-index-url", Value: "https://extra2.example.com"} + optFindLinks1 := &OptionEntry{Name: "--find-links", Value: "./wheels"} + optFindLinks2 := &OptionEntry{Name: "--find-links", Value: "./more-wheels"} + optTrusted1 := &OptionEntry{Name: "--trusted-host", Value: "example.com"} + optTrusted2 := &OptionEntry{Name: "--trusted-host", Value: "example.org"} + optNoBinary1 := &OptionEntry{Name: "--no-binary", Value: ":all:"} + optNoBinary2 := &OptionEntry{Name: "--no-binary", Value: "foo"} + optOnlyBinary1 := &OptionEntry{Name: "--only-binary", Value: "bar"} + optOnlyBinary2 := &OptionEntry{Name: "--only-binary", Value: ":none:"} + optNoIndex := &OptionEntry{Name: "--no-index"} + optRequireHashes := &OptionEntry{Name: "--require-hashes"} + optPre := &OptionEntry{Name: "--pre"} + optPreferBinary := &OptionEntry{Name: "--prefer-binary"} + + return &File{ + Entries: []Entry{ + reqA, + incA, + optIndex1, + unnamed, + reqB, + incB, + optIndex2, + optExtra1, + optExtra2, + optFindLinks1, + optFindLinks2, + optTrusted1, + optTrusted2, + optNoBinary1, + optNoBinary2, + optOnlyBinary1, + optOnlyBinary2, + optNoIndex, + optRequireHashes, + optPre, + optPreferBinary, + }, + } +} + +func TestFile_Requirements(t *testing.T) { + f := buildMixedFile(t) + got := f.Requirements() + require.Len(t, got, 2) + assert.Equal(t, "flask", got[0].Requirement.Name) + assert.False(t, got[0].Constraint) + assert.Equal(t, "requests", got[1].Requirement.Name) + assert.True(t, got[1].Constraint) +} + +func TestFile_Includes(t *testing.T) { + f := buildMixedFile(t) + got := f.Includes() + require.Len(t, got, 2) + assert.Equal(t, "base.txt", got[0].Path) + assert.False(t, got[0].Constraint) + assert.Equal(t, "constraints.txt", got[1].Path) + assert.True(t, got[1].Constraint) +} + +func TestFile_Options(t *testing.T) { + f := buildMixedFile(t) + got := f.Options() + // 16 OptionEntry values were added to the mixed file. + require.Len(t, got, 16) + assert.Equal(t, "--index-url", got[0].Name) + assert.Equal(t, "https://example.com/simple", got[0].Value) + assert.Equal(t, "--prefer-binary", got[len(got)-1].Name) +} + +func TestFile_Requirements_Empty(t *testing.T) { + f := &File{} + assert.Empty(t, f.Requirements()) +} + +func TestFile_Includes_Empty(t *testing.T) { + f := &File{} + assert.Empty(t, f.Includes()) +} + +func TestFile_Options_Empty(t *testing.T) { + f := &File{} + assert.Empty(t, f.Options()) +} + +func TestFile_IndexURL_LastWins(t *testing.T) { + f := buildMixedFile(t) + got, ok := f.IndexURL() + assert.True(t, ok) + assert.Equal(t, "https://example.com/simple2", got) +} + +func TestFile_IndexURL_Absent(t *testing.T) { + f := &File{} + got, ok := f.IndexURL() + assert.False(t, ok) + assert.Empty(t, got) +} + +func TestFile_ExtraIndexURLs_Accumulates(t *testing.T) { + f := buildMixedFile(t) + assert.Equal(t, []string{"https://extra1.example.com", "https://extra2.example.com"}, f.ExtraIndexURLs()) +} + +func TestFile_ExtraIndexURLs_Absent(t *testing.T) { + f := &File{} + assert.Empty(t, f.ExtraIndexURLs()) +} + +func TestFile_FindLinks_Accumulates(t *testing.T) { + f := buildMixedFile(t) + assert.Equal(t, []string{"./wheels", "./more-wheels"}, f.FindLinks()) +} + +func TestFile_TrustedHosts_Accumulates(t *testing.T) { + f := buildMixedFile(t) + assert.Equal(t, []string{"example.com", "example.org"}, f.TrustedHosts()) +} + +func TestFile_NoBinary_Accumulates(t *testing.T) { + f := buildMixedFile(t) + assert.Equal(t, []string{":all:", "foo"}, f.NoBinary()) +} + +func TestFile_OnlyBinary_Accumulates(t *testing.T) { + f := buildMixedFile(t) + assert.Equal(t, []string{"bar", ":none:"}, f.OnlyBinary()) +} + +func TestFile_NoIndex(t *testing.T) { + assert.True(t, buildMixedFile(t).NoIndex()) + assert.False(t, (&File{}).NoIndex()) +} + +func TestFile_RequireHashes(t *testing.T) { + assert.True(t, buildMixedFile(t).RequireHashes()) + assert.False(t, (&File{}).RequireHashes()) +} + +func TestFile_Pre(t *testing.T) { + assert.True(t, buildMixedFile(t).Pre()) + assert.False(t, (&File{}).Pre()) +} + +func TestFile_PreferBinary(t *testing.T) { + assert.True(t, buildMixedFile(t).PreferBinary()) + assert.False(t, (&File{}).PreferBinary()) +} + +func TestKind_String(t *testing.T) { + cases := []struct { + kind Kind + want string + }{ + {KindVCS, "vcs"}, + {KindURL, "url"}, + {KindLocalPath, "local-path"}, + } + for _, c := range cases { + t.Run(c.want, func(t *testing.T) { + assert.Equal(t, c.want, c.kind.String()) + }) + } +} + +func TestEntry_PointerReceivers(t *testing.T) { + // Compile-time-ish assertion: each concrete entry type satisfies Entry + // only via a pointer receiver. + var entries []Entry + entries = append(entries, &RequirementEntry{}) + entries = append(entries, &IncludeEntry{}) + entries = append(entries, &UnnamedEntry{}) + entries = append(entries, &OptionEntry{}) + assert.Len(t, entries, 4) +} + +func TestErrInvalidRequirementsFile(t *testing.T) { + require.Error(t, ErrInvalidRequirementsFile) + assert.Equal(t, "invalid requirements file", ErrInvalidRequirementsFile.Error()) +} From efe7c02709fe883cc7ca2a5d027c909aa8740dba Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Thu, 9 Jul 2026 19:10:07 -0400 Subject: [PATCH 02/16] feat(reqtxt): POSIX shell-style line tokenizer (#18639) 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). --- reqtxt/shlex.go | 122 +++++++++++++++++++++++++++++++++++++++++++ reqtxt/shlex_test.go | 109 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 231 insertions(+) create mode 100644 reqtxt/shlex.go create mode 100644 reqtxt/shlex_test.go diff --git a/reqtxt/shlex.go b/reqtxt/shlex.go new file mode 100644 index 0000000..257af73 --- /dev/null +++ b/reqtxt/shlex.go @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "fmt" + "unicode" +) + +// shlexSplit splits line into words the way Python's shlex.split(line, +// comments=False, posix=True) would. pip's requirements-file reader +// (pip/_internal/req/req_file.py, via pip's COMMENT_RE stripping followed +// by shlex.split of the remaining line) uses exactly this POSIX-mode shlex +// behavior to split each requirements-file line into option/value tokens, +// which is why requirements files support quoting values that contain +// spaces (e.g. --find-links "/opt/my links"). Comment handling is not +// performed here: callers are expected to strip comments before calling +// shlexSplit. +// +// Rules (POSIX shlex, whitespace-split mode): +// - Runs of unquoted whitespace separate words; leading, trailing, and +// repeated whitespace produce no empty words. +// - Single quotes ('...') preserve every character inside literally, +// including backslashes: there is no escape syntax inside single +// quotes. +// - Double quotes ("...") preserve whitespace, but a backslash escapes +// only a following '"' or '\\'; a backslash before any other +// character is kept as a literal backslash (POSIX sh semantics, not +// C-string escaping). +// - A backslash outside of any quoting escapes the next character, +// making it literal (e.g. "\ " is a literal space within a word). +// - Quoted and unquoted runs immediately adjacent to each other +// concatenate into a single word (e.g. a"b"c -> abc). +// - An unterminated single or double quote is an error. +// +// A word only exists once at least one character (quoted or unquoted) has +// been appended to it, so shlexSplit("") and shlexSplit(" ") both +// return an empty, non-nil slice. +func shlexSplit(line string) ([]string, error) { + const ( + stateNormal = iota + stateSingle + stateDouble + ) + + words := []string{} + var word []rune + inWord := false + state := stateNormal + + appendRune := func(r rune) { + word = append(word, r) + inWord = true + } + endWord := func() { + if inWord { + words = append(words, string(word)) + word = word[:0] + inWord = false + } + } + + runes := []rune(line) + for i := 0; i < len(runes); i++ { + r := runes[i] + + switch state { + case stateNormal: + switch { + case unicode.IsSpace(r): + endWord() + case r == '\'': + state = stateSingle + inWord = true + case r == '"': + state = stateDouble + inWord = true + case r == '\\': + i++ + if i >= len(runes) { + return nil, fmt.Errorf("%w: trailing unescaped backslash", ErrInvalidRequirementsFile) + } + appendRune(runes[i]) + default: + appendRune(r) + } + + case stateSingle: + switch r { + case '\'': + state = stateNormal + default: + appendRune(r) + } + + case stateDouble: + switch r { + case '"': + state = stateNormal + case '\\': + if i+1 < len(runes) && (runes[i+1] == '"' || runes[i+1] == '\\') { + i++ + appendRune(runes[i]) + } else { + appendRune(r) + } + default: + appendRune(r) + } + } + } + + switch state { + case stateSingle: + return nil, fmt.Errorf("%w: unterminated single-quoted string", ErrInvalidRequirementsFile) + case stateDouble: + return nil, fmt.Errorf("%w: unterminated double-quoted string", ErrInvalidRequirementsFile) + } + + endWord() + return words, nil +} diff --git a/reqtxt/shlex_test.go b/reqtxt/shlex_test.go new file mode 100644 index 0000000..c036355 --- /dev/null +++ b/reqtxt/shlex_test.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestShlexSplit(t *testing.T) { + cases := []struct { + name string + line string + want []string + }{ + { + name: "simple words", + line: "a b c", + want: []string{"a", "b", "c"}, + }, + { + name: "double-quoted argument with embedded space", + line: `--find-links "/opt/my links"`, + want: []string{"--find-links", "/opt/my links"}, + }, + { + name: "single-quoted argument with embedded space", + line: `-r 'sub dir/reqs.txt'`, + want: []string{"-r", "sub dir/reqs.txt"}, + }, + { + name: "single quotes preserve backslash literally", + line: `'a\b'`, + want: []string{`a\b`}, + }, + { + name: "double quotes allow backslash to escape a double quote", + line: `"a\"b"`, + want: []string{`a"b`}, + }, + { + name: "leading, trailing, and multiple whitespace collapse", + line: " a b c ", + want: []string{"a", "b", "c"}, + }, + { + name: "empty input", + line: "", + want: []string{}, + }, + { + name: "whitespace-only input", + line: " ", + want: []string{}, + }, + { + name: "adjacent quoted and unquoted runs concatenate", + line: `a"b"c`, + want: []string{"abc"}, + }, + { + name: "backslash outside quotes escapes a space", + line: `a\ b`, + want: []string{"a b"}, + }, + { + name: "double quotes preserve a literal backslash before a non-special char", + line: `"a\nb"`, + want: []string{`a\nb`}, + }, + { + name: "adjacent single- and double-quoted runs concatenate", + line: `'a b'"c d"e`, + want: []string{"a bc de"}, + }, + { + name: "empty quoted string still produces a word", + line: `''`, + want: []string{""}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := shlexSplit(c.line) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +func TestShlexSplit_UnterminatedQuote(t *testing.T) { + cases := []struct { + name string + line string + }{ + {name: "unterminated double quote", line: `"abc`}, + {name: "unterminated single quote", line: `'abc`}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + _, err := shlexSplit(c.line) + require.Error(t, err) + }) + } +} From e9626bae327d951228db9b28acb4099b1922d060 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 07:16:35 -0400 Subject: [PATCH 03/16] test(reqtxt): cover trailing-backslash error + match shlex whitespace 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. --- reqtxt/shlex.go | 17 +++++++++++++++-- reqtxt/shlex_test.go | 14 +++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/reqtxt/shlex.go b/reqtxt/shlex.go index 257af73..cd459c4 100644 --- a/reqtxt/shlex.go +++ b/reqtxt/shlex.go @@ -4,7 +4,6 @@ package reqtxt import ( "fmt" - "unicode" ) // shlexSplit splits line into words the way Python's shlex.split(line, @@ -67,7 +66,7 @@ func shlexSplit(line string) ([]string, error) { switch state { case stateNormal: switch { - case unicode.IsSpace(r): + case isShlexSpace(r): endWord() case r == '\'': state = stateSingle @@ -120,3 +119,17 @@ func shlexSplit(line string) ([]string, error) { endWord() return words, nil } + +// isShlexSpace reports whether r is a word separator under Python shlex's +// default whitespace set (shlex.whitespace = " \t\r\n"). This is narrower +// than unicode.IsSpace, which also treats '\v', '\f', NEL, NBSP, and other +// Unicode Zs-category runes as whitespace; those must remain ordinary word +// characters here to match Python's behavior. +func isShlexSpace(r rune) bool { + switch r { + case ' ', '\t', '\r', '\n': + return true + default: + return false + } +} diff --git a/reqtxt/shlex_test.go b/reqtxt/shlex_test.go index c036355..28a4c63 100644 --- a/reqtxt/shlex_test.go +++ b/reqtxt/shlex_test.go @@ -80,6 +80,16 @@ func TestShlexSplit(t *testing.T) { line: `''`, want: []string{""}, }, + { + name: "form feed is not a word separator (unlike unicode.IsSpace)", + line: "a\x0cb", + want: []string{"a\x0cb"}, + }, + { + name: "vertical tab is not a word separator (unlike unicode.IsSpace)", + line: "a\vb", + want: []string{"a\vb"}, + }, } for _, c := range cases { @@ -91,13 +101,15 @@ func TestShlexSplit(t *testing.T) { } } -func TestShlexSplit_UnterminatedQuote(t *testing.T) { +func TestShlexSplit_Errors(t *testing.T) { cases := []struct { name string line string }{ {name: "unterminated double quote", line: `"abc`}, {name: "unterminated single quote", line: `'abc`}, + {name: "trailing bare backslash after a word", line: `a\`}, + {name: "bare backslash with nothing else", line: `\`}, } for _, c := range cases { From 2da5dbb1a57fc37494124c69a5f781494ecca170 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 07:20:44 -0400 Subject: [PATCH 04/16] feat(reqtxt): preprocessing pipeline + WithEnv (#18639) 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. --- reqtxt/preprocess.go | 153 +++++++++++++++++++++++++++ reqtxt/preprocess_test.go | 213 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 366 insertions(+) create mode 100644 reqtxt/preprocess.go create mode 100644 reqtxt/preprocess_test.go diff --git a/reqtxt/preprocess.go b/reqtxt/preprocess.go new file mode 100644 index 0000000..28dcc6a --- /dev/null +++ b/reqtxt/preprocess.go @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "regexp" + "strings" +) + +// commentRE matches pip's COMMENT_RE (pip/_internal/req/req_file.py): +// "(^|\s+)#.*$". A '#' at the start of the line, or preceded by +// whitespace, begins a comment that runs to end-of-line. A '#' that is +// not whitespace-preceded (e.g. the fragment in +// "git+https://h/p#egg=name") is left alone. +var commentRE = regexp.MustCompile(`(^|\s+)#.*$`) + +// envVarRE matches pip's ENV_VAR_RE (pip/_internal/req/req_file.py): +// `\$\{([A-Z0-9_]+)\}`. Only the uppercase form is recognized; a +// lowercase or mixed-case name inside ${...} is left as literal text. +var envVarRE = regexp.MustCompile(`\$\{([A-Z0-9_]+)\}`) + +// ParseOption configures optional behavior for preprocessing/parsing a +// requirements file, e.g. WithEnv. +type ParseOption func(*parseConfig) + +// parseConfig holds the options accumulated from a caller's ParseOption +// values. +type parseConfig struct { + // env looks up an environment variable by name, returning its value + // and whether it is set. When nil, ${VAR} references are left + // literal (no expansion is attempted). + env func(string) (string, bool) +} + +// WithEnv enables "${VAR}" expansion using lookup (e.g. os.LookupEnv). +// Without it, "${VAR}" is left literal. Only the uppercase "${NAME}" form +// (NAME matching [A-Z0-9_]+) is ever expanded; a variable that lookup +// reports as unset, or that resolves to the empty string, is also left +// literal - matching pip's expand_env_variables behavior. Expansion is +// applied to the whole assembled logical line, before tokenization. +func WithEnv(lookup func(string) (string, bool)) ParseOption { + return func(cfg *parseConfig) { + cfg.env = lookup + } +} + +// logicalLine is one preprocessed line of a requirements file, ready for +// tokenization: comments and blank lines have already been removed, any +// backslash continuations already joined, and (if configured) any +// "${VAR}" references already expanded. +type logicalLine struct { + // text is the fully assembled, comment-stripped, trimmed, and + // (optionally) env-expanded line content. + text string + // line is the 1-based physical line number, in the original + // (post-line-ending-normalization) content, of this logical line's + // first segment - i.e. the line a continuation join started on. + line int +} + +// preprocess turns raw requirements-file content into an ordered slice of +// logicalLine values, following pip's req_file.preprocess pipeline: +// +// 1. Normalize line endings ("\r\n" and lone "\r" both become "\n"), +// before anything else, so continuation joining and physical-line +// counting are CRLF-safe. +// 2. Join backslash continuations: a physical line ending in "\" +// concatenates directly to the next physical line, with NO separator +// inserted (the trailing "\" is simply removed). The joined logical +// line's line number is that of its first physical segment. +// 3. Strip comments per commentRE. +// 4. Drop logical lines that are empty or all-whitespace once comments +// are stripped. +// 5. Trim remaining surrounding whitespace. +// 6. If cfg.env is set, expand "${NAME}" references (see WithEnv). +// +// The returned error exists for signature stability with future callers; +// preprocess itself has no failure mode today. +func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { + normalized := normalizeLineEndings(content) + physicalLines := strings.Split(normalized, "\n") + + var lines []logicalLine + var ( + joined strings.Builder + joinedLine int + joining bool + ) + + flush := func() { + if !joining { + return + } + joining = false + + text := commentRE.ReplaceAllString(joined.String(), "") + text = strings.TrimSpace(text) + if text == "" { + return + } + if cfg.env != nil { + text = expandEnv(text, cfg.env) + } + lines = append(lines, logicalLine{text: text, line: joinedLine}) + } + + for i, physical := range physicalLines { + physicalLineNum := i + 1 + + if !joining { + joining = true + joinedLine = physicalLineNum + joined.Reset() + } + + if rest, ok := strings.CutSuffix(physical, `\`); ok { + joined.WriteString(rest) + continue + } + + joined.WriteString(physical) + flush() + } + // A trailing continuation with no following physical line still + // needs to be flushed (there's no next segment to join to). + flush() + + return lines, nil +} + +// normalizeLineEndings converts "\r\n" and lone "\r" to "\n", matching +// Python's universal-newlines splitlines() behavior that pip's preprocess +// relies on. +func normalizeLineEndings(content string) string { + content = strings.ReplaceAll(content, "\r\n", "\n") + return strings.ReplaceAll(content, "\r", "\n") +} + +// expandEnv replaces every "${NAME}" reference in text (NAME matching +// [A-Z0-9_]+) with the value lookup(NAME) returns, unless lookup reports +// the variable as unset or reports an empty value - in either case the +// literal "${NAME}" is left in place, matching pip's +// expand_env_variables. +func expandEnv(text string, lookup func(string) (string, bool)) string { + return envVarRE.ReplaceAllStringFunc(text, func(match string) string { + name := envVarRE.FindStringSubmatch(match)[1] + value, ok := lookup(name) + if !ok || value == "" { + return match + } + return value + }) +} diff --git a/reqtxt/preprocess_test.go b/reqtxt/preprocess_test.go new file mode 100644 index 0000000..97a838c --- /dev/null +++ b/reqtxt/preprocess_test.go @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPreprocess_Continuations(t *testing.T) { + cases := []struct { + name string + content string + want []logicalLine + }{ + { + name: "no-space continuation joins with no separator", + content: "foo==\\\n1.0", + want: []logicalLine{{text: "foo==1.0", line: 1}}, + }, + { + name: "space-before-backslash continuation preserves the space", + content: "foo \\\n1.0", + want: []logicalLine{{text: "foo 1.0", line: 1}}, + }, + { + name: "CRLF continuation", + content: "foo==\\\r\n1.0", + want: []logicalLine{{text: "foo==1.0", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, parseConfig{}) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +func TestPreprocess_Comments(t *testing.T) { + cases := []struct { + name string + content string + want []logicalLine + }{ + { + name: "full-line comment is dropped entirely", + content: "# a comment", + want: nil, + }, + { + name: "inline comment preceded by whitespace is stripped", + content: "foo # a comment", + want: []logicalLine{{text: "foo", line: 1}}, + }, + { + name: "bare hash not preceded by whitespace is content, not a comment", + content: "git+https://h/p#egg=n", + want: []logicalLine{{text: "git+https://h/p#egg=n", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, parseConfig{}) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +func TestPreprocess_BlankLinesAndWhitespace(t *testing.T) { + cases := []struct { + name string + content string + want []logicalLine + }{ + { + name: "blank lines are dropped", + content: "foo\n\nbar", + want: []logicalLine{ + {text: "foo", line: 1}, + {text: "bar", line: 3}, + }, + }, + { + name: "whitespace-only line is dropped", + content: "foo\n \nbar", + want: []logicalLine{ + {text: "foo", line: 1}, + {text: "bar", line: 3}, + }, + }, + { + name: "leading whitespace is trimmed", + content: " foo", + want: []logicalLine{{text: "foo", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, parseConfig{}) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +func TestPreprocess_LineNumbers(t *testing.T) { + // Line 1 is a comment (dropped), line 2 is blank (dropped), line 3 is + // the kept logical line. + content := "# c\n\nfoo" + got, err := preprocess(content, parseConfig{}) + require.NoError(t, err) + require.Len(t, got, 1) + assert.Equal(t, "foo", got[0].text) + assert.Equal(t, 3, got[0].line) +} + +func TestPreprocess_LineNumbers_AfterContinuationJoin(t *testing.T) { + // Line 1: comment (dropped). Line 2: blank (dropped). Lines 3-4: a + // continuation join whose first segment is physical line 3. Line 5: a + // trailing plain line, physical line 5. + content := "# c\n\nfoo==\\\n1.0\nbar" + got, err := preprocess(content, parseConfig{}) + require.NoError(t, err) + require.Len(t, got, 2) + assert.Equal(t, logicalLine{text: "foo==1.0", line: 3}, got[0]) + assert.Equal(t, logicalLine{text: "bar", line: 5}, got[1]) +} + +func TestPreprocess_Env(t *testing.T) { + lookup := func(name string) (string, bool) { + switch name { + case "TOKEN": + return "t", true + case "EMPTY": + return "", true + default: + return "", false + } + } + + cases := []struct { + name string + content string + cfg parseConfig + want []logicalLine + }{ + { + name: "set-nonempty var is substituted", + content: "--index-url https://${TOKEN}@h/s", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "--index-url https://t@h/s", line: 1}}, + }, + { + name: "unset var is left literal", + content: "${MISSING}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${MISSING}", line: 1}}, + }, + { + name: "set-but-empty var is left literal", + content: "${EMPTY}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${EMPTY}", line: 1}}, + }, + { + name: "lowercase name is never expanded", + content: "${token}", + cfg: parseConfig{env: lookup}, + want: []logicalLine{{text: "${token}", line: 1}}, + }, + { + name: "no env configured leaves everything literal", + content: "${TOKEN}", + cfg: parseConfig{}, + want: []logicalLine{{text: "${TOKEN}", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, c.cfg) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +func TestWithEnv(t *testing.T) { + lookup := func(name string) (string, bool) { + return "v", true + } + + var cfg parseConfig + opt := WithEnv(lookup) + opt(&cfg) + + require.NotNil(t, cfg.env) + v, ok := cfg.env("ANYTHING") + assert.True(t, ok) + assert.Equal(t, "v", v) + + got, err := preprocess("${X}", cfg) + require.NoError(t, err) + assert.Equal(t, []logicalLine{{text: "v", line: 1}}, got) +} From 9126a9abced8df8794d4d17dd1e19dec3118a14c Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 07:25:54 -0400 Subject: [PATCH 05/16] feat(reqtxt): shape-first target classification (#18639) 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. --- reqtxt/classify.go | 88 +++++++++++++++++++++++ reqtxt/classify_test.go | 152 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+) create mode 100644 reqtxt/classify.go create mode 100644 reqtxt/classify_test.go diff --git a/reqtxt/classify.go b/reqtxt/classify.go new file mode 100644 index 0000000..e01547c --- /dev/null +++ b/reqtxt/classify.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import "strings" + +// vcsSchemePrefixes are the "+" prefixes pip recognizes on a +// requirement target, one per supported VCS backend (pip's +// pip/_internal/vcs/{git,mercurial,subversion,bazaar}.py each register a +// scheme of this form via VersionControl.register). +var vcsSchemePrefixes = []string{"git+", "hg+", "svn+", "bzr+"} + +// urlSchemes are the URL schemes classifyTarget treats as a direct URL +// target, mirroring the schemes pip's is_url (pip/_internal/utils/misc.py) +// accepts for a requirement specifier: "file" plus the schemes registered +// by pip's index backends (http/https). +var urlSchemes = []string{"http://", "https://", "file://"} + +// archiveExtensions are the local-archive suffixes pip's is_archive_file +// (pip/_internal/utils/misc.py) recognizes by extension. Multi-dot +// suffixes are ordered before their shorter overlapping counterpart (e.g. +// ".tar.gz" before ".tar") so the longer, more specific suffix is checked +// first. +var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".whl", ".tgz", ".tar", ".zip"} + +// classifyTarget determines whether tok is shaped like a VCS reference, a +// direct URL, a local archive, or a local path — the non-PEP-508 +// requirement forms pip accepts on a requirement line — and if so, which +// Kind it is. It reports (_, false) when tok doesn't match any of those +// shapes, meaning the caller should instead try parsing it as a PEP 508 +// requirement (name/version/extras/marker). +// +// This mirrors the target recognition performed by pip's is_url and +// is_archive_file (pip/_internal/utils/misc.py) and the VCS scheme +// dispatch in pip/_internal/vcs/__init__.py, but is a pure, shape-only +// string classifier: unlike pip, it never touches the filesystem. pip +// additionally treats a bare local name as a path if it exists on disk +// (via os.path.exists) even without a "/", "./", or recognized +// extension; this package deliberately does not reproduce that +// filesystem-dependent fallback, so a bare name with no path/URL/archive +// shape (e.g. "flask") always falls through to (_, false) here. +func classifyTarget(tok string) (kind Kind, ok bool) { + for _, prefix := range vcsSchemePrefixes { + if strings.HasPrefix(tok, prefix) { + return KindVCS, true + } + } + + lower := strings.ToLower(tok) + for _, scheme := range urlSchemes { + if strings.HasPrefix(lower, scheme) { + return KindURL, true + } + } + + for _, ext := range archiveExtensions { + if strings.HasSuffix(lower, ext) { + return KindLocalPath, true + } + } + + if strings.HasPrefix(tok, "./") || strings.HasPrefix(tok, "../") || strings.HasPrefix(tok, "/") || + tok == "." || strings.Contains(tok, "/") { + return KindLocalPath, true + } + + return 0, false +} + +// eggName returns the value of a "#egg=" fragment on raw (pip's +// legacy way of naming a VCS/URL requirement whose distribution name +// can't otherwise be inferred; see pip's _egg_fragment in +// pip/_internal/req/constructors.py). It returns "" if raw has no such +// fragment. The fragment may be followed by additional "&"-separated +// fragment parameters (e.g. "&subdirectory=..."), which are not part of +// the returned name. +func eggName(raw string) string { + const marker = "#egg=" + i := strings.Index(raw, marker) + if i < 0 { + return "" + } + rest := raw[i+len(marker):] + if j := strings.IndexByte(rest, '&'); j >= 0 { + return rest[:j] + } + return rest +} diff --git a/reqtxt/classify_test.go b/reqtxt/classify_test.go new file mode 100644 index 0000000..4d4fa58 --- /dev/null +++ b/reqtxt/classify_test.go @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestClassifyTarget(t *testing.T) { + cases := []struct { + name string + tok string + wantKind Kind + wantOK bool + }{ + { + name: "vcs git+https with egg fragment", + tok: "git+https://h/p@v1#egg=n", + wantKind: KindVCS, + wantOK: true, + }, + { + name: "url https to a wheel", + tok: "https://h/x-1.0.whl", + wantKind: KindURL, + wantOK: true, + }, + { + name: "url file scheme", + tok: "file:///a/b", + wantKind: KindURL, + wantOK: true, + }, + { + name: "bare tar.gz archive", + tok: "foo-1.0.tar.gz", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "bare wheel archive", + tok: "x.whl", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "relative path with leading dot-slash", + tok: "./local", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "relative path with leading dot-dot-slash", + tok: "../up", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "absolute path", + tok: "/abs/pkg", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "path shape via embedded slash", + tok: "subdir/pkg", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "current directory", + tok: ".", + wantKind: KindLocalPath, + wantOK: true, + }, + { + name: "plain requirement name", + tok: "flask", + wantOK: false, + }, + { + name: "plain requirement with version specifier", + tok: "flask>=2.0", + wantOK: false, + }, + { + name: "plain requirement with extras", + tok: "requests[security]", + wantOK: false, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + gotKind, gotOK := classifyTarget(c.tok) + assert.Equal(t, c.wantOK, gotOK, "ok mismatch for %q", c.tok) + if c.wantOK { + assert.Equal(t, c.wantKind.String(), gotKind.String(), "kind mismatch for %q", c.tok) + } + }) + } +} + +func TestClassifyTargetVCSSchemePrefixes(t *testing.T) { + for _, prefix := range []string{"git+", "hg+", "svn+", "bzr+"} { + tok := prefix + "https://h/p" + kind, ok := classifyTarget(tok) + assert.True(t, ok, "expected %q to classify as VCS", tok) + assert.Equal(t, KindVCS.String(), kind.String(), "expected %q to be KindVCS", tok) + } +} + +func TestClassifyTargetArchiveExtensions(t *testing.T) { + for _, ext := range []string{".whl", ".tar.gz", ".tgz", ".tar.bz2", ".tar", ".zip"} { + tok := "pkg-1.0" + ext + kind, ok := classifyTarget(tok) + assert.True(t, ok, "expected %q to classify as an archive", tok) + assert.Equal(t, KindLocalPath.String(), kind.String(), "expected %q to be KindLocalPath", tok) + } +} + +func TestEggName(t *testing.T) { + cases := []struct { + name string + raw string + want string + }{ + { + name: "vcs fragment with egg only", + raw: "git+https://h/p#egg=name", + want: "name", + }, + { + name: "vcs fragment with egg and subdirectory", + raw: "git+https://h/p#egg=name&subdirectory=x", + want: "name", + }, + { + name: "no fragment at all", + raw: "./x", + want: "", + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + assert.Equal(t, c.want, eggName(c.raw)) + }) + } +} From 74d9c40e9dbb624d561325554450204b1cd8e35c Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 07:36:37 -0400 Subject: [PATCH 06/16] =?UTF-8?q?feat(reqtxt):=20Parse=20=E2=80=94=20dispa?= =?UTF-8?q?tch,=20options,=20hashes=20(#18639)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- reqtxt/parse.go | 339 +++++++++++++++++++++++++++++++++++++++++++ reqtxt/parse_test.go | 221 ++++++++++++++++++++++++++++ 2 files changed, 560 insertions(+) create mode 100644 reqtxt/parse.go create mode 100644 reqtxt/parse_test.go diff --git a/reqtxt/parse.go b/reqtxt/parse.go new file mode 100644 index 0000000..33194d8 --- /dev/null +++ b/reqtxt/parse.go @@ -0,0 +1,339 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "fmt" + "strings" + + "github.com/posit-dev/go-python-packaging/requirement" +) + +// knownOption describes one of pip's recognized global requirements-file +// options (pip's SUPPORTED_OPTIONS in pip/_internal/req/req_file.py): its +// canonical long name (OptionEntry.Name always uses this, even when a +// short form was used on the line) and how many values it takes. +type knownOption struct { + long string + arity int +} + +// knownOptions maps every short and long spelling of a recognized +// file-level option to its canonical long name and arity. A flag not in +// this table is still accepted (see dispatchFileOption) but captured +// generically, without normalization. +var knownOptions = map[string]knownOption{ + "-i": {optIndexURL, 1}, + "--index-url": {optIndexURL, 1}, + "--extra-index-url": {optExtraIndexURL, 1}, + "--no-index": {optNoIndex, 0}, + "-f": {optFindLinks, 1}, + "--find-links": {optFindLinks, 1}, + "--require-hashes": {optRequireHashes, 0}, + "--pre": {optPre, 0}, + "--trusted-host": {optTrustedHost, 1}, + "--no-binary": {optNoBinary, 1}, + "--only-binary": {optOnlyBinary, 1}, + "--prefer-binary": {optPreferBinary, 0}, +} + +// perLineValueOptions are the per-requirement options (other than +// "--hash") that pip's SUPPORTED_OPTIONS_REQ recognizes and that this +// package captures onto RequirementEntry.Options / UnnamedEntry.Options. +var perLineValueOptions = map[string]bool{ + "--config-settings": true, + "--global-option": true, + "--install-option": true, +} + +// Parse parses content as a requirements.txt (or constraints) file. It +// follows pip's req_file preprocessing pipeline (see preprocess) to +// produce logical lines, then dispatches each one by its leading token +// (see pip's req_file.break_args_options / process_line) into the +// Entry it represents. +// +// Parse does not follow "-r"/"-c" includes; that is Flatten's job. +func Parse(content string, opts ...ParseOption) (*File, error) { + var cfg parseConfig + for _, opt := range opts { + opt(&cfg) + } + + lines, err := preprocess(content, cfg) + if err != nil { + return nil, err + } + + file := &File{} + for _, ll := range lines { + tokens, err := shlexSplit(ll.text) + if err != nil { + return nil, wrapLineErr(ll.line, err) + } + + entries, err := dispatchLine(tokens, ll.line) + if err != nil { + return nil, err + } + file.Entries = append(file.Entries, entries...) + } + + return file, nil +} + +// dispatchLine dispatches the tokens of one (recursive tail of a) logical +// line into zero or more Entry values, per pip's break_args_options: the +// leading token determines the entry kind. For the plain file-option +// branch only, any tokens left over after that flag's own value (if any) +// are dispatched again as if they began a new line — so e.g. an +// unrecognized boolean flag followed by a requirement ("--frob foo") +// yields two entries, rather than the flag swallowing "foo" as its value. +// The include/editable/package branches instead consume the *entire* +// remaining token stream for their own per-line options (hashes, etc.) +// and never recurse. +func dispatchLine(tokens []string, lineNum int) ([]Entry, error) { + if len(tokens) == 0 { + return nil, nil + } + + first := tokens[0] + rest := tokens[1:] + name, eqValue, hasEq := splitFlagValue(first) + + switch name { + case "-r", "--requirement": + return dispatchInclude(false, hasEq, eqValue, rest, lineNum) + case "-c", "--constraint": + return dispatchInclude(true, hasEq, eqValue, rest, lineNum) + case "-e", "--editable": + return dispatchEditable(hasEq, eqValue, rest, lineNum) + } + + if strings.HasPrefix(first, "-") { + return dispatchFileOption(name, hasEq, eqValue, rest, lineNum) + } + + return dispatchPackage(first, rest, lineNum) +} + +// dispatchInclude handles a leading "-r"/"--requirement" or +// "-c"/"--constraint" directive, producing an *IncludeEntry. +func dispatchInclude(constraint, hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { + label := "-r/--requirement" + if constraint { + label = "-c/--constraint" + } + + path, remaining, err := takeValue(label, hasEq, eqValue, rest, lineNum) + if err != nil { + return nil, err + } + + following, err := dispatchLine(remaining, lineNum) + if err != nil { + return nil, err + } + + entry := &IncludeEntry{Path: path, Constraint: constraint} + return append([]Entry{entry}, following...), nil +} + +// dispatchEditable handles a leading "-e"/"--editable" directive: the +// next token is the install target, classified the same way a package +// line's target would be, plus any trailing per-line options. +func dispatchEditable(hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { + target, remaining, err := takeValue("-e/--editable", hasEq, eqValue, rest, lineNum) + if err != nil { + return nil, err + } + + kind, ok := classifyTarget(target) + if !ok { + return nil, lineError(lineNum, "editable requirement %q is not a recognized VCS/URL/local-path target", target) + } + + entry := &UnnamedEntry{ + Raw: target, + Kind: kind, + Editable: true, + EggName: eggName(target), + } + if err := attachReqOptions(&entry.Hashes, &entry.Options, remaining, lineNum); err != nil { + return nil, err + } + + return []Entry{entry}, nil +} + +// dispatchFileOption handles a leading "-"/"--" token that isn't +// -r/-c/-e: a file-level pip option, matched against knownOptions when +// recognized, or captured generically otherwise. A standalone "--hash" +// (with no preceding requirement to attach to) is rejected: "--hash" is +// only ever a per-requirement option (see attachReqOptions). +func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, lineNum int) ([]Entry, error) { + if name == "--hash" { + return nil, lineError(lineNum, "--hash has no associated requirement") + } + + var ( + value string + remaining []string + ) + + if spec, known := knownOptions[name]; known { + name = spec.long + if spec.arity == 1 { + var err error + value, remaining, err = takeValue(name, hasEq, eqValue, rest, lineNum) + if err != nil { + return nil, err + } + } else { + // A boolean known option never consumes a following token, + // even if it happened to be written with "=". + value, remaining = eqValue, rest + } + } else { + // Unknown flag: "--opt=value" takes the value; a bare "--opt" is + // boolean and never consumes the next token — it is left to be + // dispatched as its own, separate entry. + value, remaining = eqValue, rest + } + + following, err := dispatchLine(remaining, lineNum) + if err != nil { + return nil, err + } + + entry := &OptionEntry{Name: name, Value: value} + return append([]Entry{entry}, following...), nil +} + +// dispatchPackage handles a package/requirement line: first is either a +// VCS/URL/local-path target (classifyTarget) or a plain PEP 508 +// requirement (requirement.Parse). Unlike the file-option branch, every +// remaining token on the line is a per-requirement option attached to +// this single entry (attachReqOptions) — none of it is dispatched as a +// separate entry. +func dispatchPackage(first string, rest []string, lineNum int) ([]Entry, error) { + var ( + entry Entry + hashes *[]Hash + options *[]OptionEntry + ) + + if kind, ok := classifyTarget(first); ok { + e := &UnnamedEntry{Raw: first, Kind: kind, EggName: eggName(first)} + entry, hashes, options = e, &e.Hashes, &e.Options + } else { + req, err := requirement.Parse(first) + if err != nil { + return nil, wrapLineErr(lineNum, err) + } + e := &RequirementEntry{Requirement: req} + entry, hashes, options = e, &e.Hashes, &e.Options + } + + if err := attachReqOptions(hashes, options, rest, lineNum); err != nil { + return nil, err + } + + return []Entry{entry}, nil +} + +// attachReqOptions consumes every token in tokens as a per-requirement +// option (pip's SUPPORTED_OPTIONS_REQ), appending to *hashes or *options +// as appropriate. Unlike dispatchFileOption, this never leaves tokens for +// a separate entry: every token on a requirement/editable line's tail +// belongs to that one requirement. +func attachReqOptions(hashes *[]Hash, options *[]OptionEntry, tokens []string, lineNum int) error { + i := 0 + for i < len(tokens) { + tok := tokens[i] + if !strings.HasPrefix(tok, "-") { + return lineError(lineNum, "unexpected token %q (expected a per-requirement option)", tok) + } + + name, eqValue, hasEq := splitFlagValue(tok) + i++ + + var value string + switch { + case hasEq: + value = eqValue + case name == "--hash" || perLineValueOptions[name]: + if i >= len(tokens) { + return lineError(lineNum, "%s requires a value", name) + } + value = tokens[i] + i++ + } + // An unknown bare "--flag" (no "=", not --hash/perLineValueOptions) + // falls through with value == "", matching the generic + // unknown-flag boolean rule. + + if name == "--hash" { + h, err := parseHash(value, lineNum) + if err != nil { + return err + } + *hashes = append(*hashes, h) + continue + } + + *options = append(*options, OptionEntry{Name: name, Value: value}) + } + + return nil +} + +// parseHash parses a "--hash" value ("algorithm:digest") into a Hash, +// splitting on the first ':' only (a digest can't itself contain a +// leading algorithm-style prefix, but be conservative and only split +// once regardless). +func parseHash(raw string, lineNum int) (Hash, error) { + algo, digest, ok := strings.Cut(raw, ":") + if !ok { + return Hash{}, lineError(lineNum, "malformed --hash value %q: expected \"algorithm:digest\"", raw) + } + return Hash{Algorithm: algo, Digest: digest}, nil +} + +// splitFlagValue splits tok on its first '=', if any, into a flag name +// and inline value (e.g. "--index-url=https://x" -> "--index-url", +// "https://x", true). A token with no '=' returns (tok, "", false). +func splitFlagValue(tok string) (name, value string, hasValue bool) { + if i := strings.Index(tok, "="); i >= 0 { + return tok[:i], tok[i+1:], true + } + return tok, "", false +} + +// takeValue resolves the value for a single-value directive (-r/-c/-e, or +// a known arity-1 file option): the inline "=value" form if present, +// otherwise the next token in rest. label names the directive, for the +// error produced when neither form supplies a value. +func takeValue(label string, hasEq bool, eqValue string, rest []string, lineNum int) (value string, remaining []string, err error) { + if hasEq { + return eqValue, rest, nil + } + if len(rest) == 0 { + return "", nil, lineError(lineNum, "%s requires a value", label) + } + return rest[0], rest[1:], nil +} + +// lineError builds a line-numbered error wrapping ErrInvalidRequirementsFile. +func lineError(lineNum int, format string, args ...any) error { + msg := fmt.Errorf(format, args...) + return errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("line %d: %w", lineNum, msg)) +} + +// wrapLineErr wraps an existing error (e.g. from shlexSplit or +// requirement.Parse) with a line number, ensuring the result still +// satisfies errors.Is against both ErrInvalidRequirementsFile and +// whatever sentinel err itself wraps (e.g. requirement.ErrInvalidRequirement). +func wrapLineErr(lineNum int, err error) error { + return errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("line %d: %w", lineNum, err)) +} diff --git a/reqtxt/parse_test.go b/reqtxt/parse_test.go new file mode 100644 index 0000000..584bd0c --- /dev/null +++ b/reqtxt/parse_test.go @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "testing" + + "github.com/posit-dev/go-python-packaging/requirement" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParse_Requirement(t *testing.T) { + f, err := Parse("flask>=2.0") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "flask", re.Requirement.Name) +} + +func TestParse_Include(t *testing.T) { + cases := []struct { + name string + content string + want IncludeEntry + }{ + {name: "-r space form", content: "-r base.txt", want: IncludeEntry{Path: "base.txt"}}, + {name: "-c space form is a constraint", content: "-c c.txt", want: IncludeEntry{Path: "c.txt", Constraint: true}}, + {name: "--requirement= form", content: "--requirement=x.txt", want: IncludeEntry{Path: "x.txt"}}, + {name: "--constraint= form is a constraint", content: "--constraint=x.txt", want: IncludeEntry{Path: "x.txt", Constraint: true}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + f, err := Parse(c.content) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + ie, ok := f.Entries[0].(*IncludeEntry) + require.True(t, ok, "want *IncludeEntry, got %T", f.Entries[0]) + assert.Equal(t, c.want, *ie) + }) + } +} + +func TestParse_Editable(t *testing.T) { + f, err := Parse("-e ./pkg") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + ue, ok := f.Entries[0].(*UnnamedEntry) + require.True(t, ok, "want *UnnamedEntry, got %T", f.Entries[0]) + assert.True(t, ue.Editable) + assert.Equal(t, KindLocalPath, ue.Kind) + assert.Equal(t, "./pkg", ue.Raw) + assert.Empty(t, ue.EggName) + + f, err = Parse("-e git+https://h/p#egg=n") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + ue, ok = f.Entries[0].(*UnnamedEntry) + require.True(t, ok, "want *UnnamedEntry, got %T", f.Entries[0]) + assert.True(t, ue.Editable) + assert.Equal(t, KindVCS, ue.Kind) + assert.Equal(t, "n", ue.EggName) +} + +func TestParse_FileOptions(t *testing.T) { + cases := []struct { + name string + content string + want []OptionEntry + }{ + { + name: "--index-url space form", + content: "--index-url https://i/simple", + want: []OptionEntry{{Name: "--index-url", Value: "https://i/simple"}}, + }, + { + name: "-i short form normalizes to --index-url", + content: "-i https://i/simple", + want: []OptionEntry{{Name: "--index-url", Value: "https://i/simple"}}, + }, + { + name: "--index-url= form", + content: "--index-url=https://i", + want: []OptionEntry{{Name: "--index-url", Value: "https://i"}}, + }, + { + name: "--no-index is boolean", + content: "--no-index", + want: []OptionEntry{{Name: "--no-index", Value: ""}}, + }, + { + name: "--find-links repeated across lines", + content: "--find-links a\n--find-links b", + want: []OptionEntry{{Name: "--find-links", Value: "a"}, {Name: "--find-links", Value: "b"}}, + }, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + f, err := Parse(c.content) + require.NoError(t, err) + require.Len(t, f.Entries, len(c.want)) + + for i, e := range f.Entries { + oe, ok := e.(*OptionEntry) + require.True(t, ok, "entry %d: want *OptionEntry, got %T", i, e) + assert.Equal(t, c.want[i], *oe) + } + }) + } +} + +func TestParse_UnknownFlag(t *testing.T) { + f, err := Parse("--frobnicate=1") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + oe, ok := f.Entries[0].(*OptionEntry) + require.True(t, ok, "want *OptionEntry, got %T", f.Entries[0]) + assert.Equal(t, OptionEntry{Name: "--frobnicate", Value: "1"}, *oe) + + f, err = Parse("--frob foo") + require.NoError(t, err) + require.Len(t, f.Entries, 2) + + oe, ok = f.Entries[0].(*OptionEntry) + require.True(t, ok, "entry 0: want *OptionEntry, got %T", f.Entries[0]) + assert.Equal(t, OptionEntry{Name: "--frob", Value: ""}, *oe) + + re, ok := f.Entries[1].(*RequirementEntry) + require.True(t, ok, "entry 1: want *RequirementEntry, got %T", f.Entries[1]) + assert.Equal(t, "foo", re.Requirement.Name) +} + +func TestParse_Hashes(t *testing.T) { + f, err := Parse("requests==2.0 --hash=sha256:abc --hash sha256:def") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + require.Len(t, re.Hashes, 2) + assert.Equal(t, Hash{Algorithm: "sha256", Digest: "abc"}, re.Hashes[0]) + assert.Equal(t, Hash{Algorithm: "sha256", Digest: "def"}, re.Hashes[1]) + + _, err = Parse("foo --hash=bad") + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) + + _, err = Parse("--hash=sha256:x") + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) +} + +func TestParse_ConfigSettings(t *testing.T) { + f, err := Parse("foo==1.0 --config-settings=x=y") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + require.Len(t, re.Options, 1) + assert.Equal(t, OptionEntry{Name: "--config-settings", Value: "x=y"}, re.Options[0]) +} + +func TestParse_BareArchiveIsUnnamed(t *testing.T) { + f, err := Parse("foo-1.0.tar.gz") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + ue, ok := f.Entries[0].(*UnnamedEntry) + require.True(t, ok, "want *UnnamedEntry, got %T", f.Entries[0]) + assert.Equal(t, KindLocalPath, ue.Kind) + assert.Equal(t, "foo-1.0.tar.gz", ue.Raw) +} + +func TestParse_Env(t *testing.T) { + lookup := func(name string) (string, bool) { + if name == "TOKEN" { + return "t", true + } + return "", false + } + + f, err := Parse("--index-url https://${TOKEN}@h/s", WithEnv(lookup)) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + oe, ok := f.Entries[0].(*OptionEntry) + require.True(t, ok, "want *OptionEntry, got %T", f.Entries[0]) + assert.Equal(t, "https://t@h/s", oe.Value) + + f, err = Parse("--index-url https://${TOKEN}@h/s") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + oe, ok = f.Entries[0].(*OptionEntry) + require.True(t, ok, "want *OptionEntry, got %T", f.Entries[0]) + assert.Equal(t, "https://${TOKEN}@h/s", oe.Value) +} + +func TestParse_ErrorLineNumber(t *testing.T) { + // Line 1 is a comment, line 2 is blank, so the bad requirement is the + // logical line whose *physical* line number is 3. + content := "# comment\n\nfoo[bad\n" + _, err := Parse(content) + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) + assert.ErrorIs(t, err, requirement.ErrInvalidRequirement) + assert.Contains(t, err.Error(), "line 3") +} + +func TestParse_ErrorIsErrorsIsCompatible(t *testing.T) { + _, err := Parse("foo[bad") + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile)) + assert.True(t, errors.Is(err, requirement.ErrInvalidRequirement)) +} From 1daf07fc4325301158f4ca1202cfe4c79647dba5 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 07:53:14 -0400 Subject: [PATCH 07/16] fix(reqtxt): split requirement text vs options per pip break_args_options (#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. --- reqtxt/parse.go | 140 +++++++++++++++++++++++++++++++++++++------ reqtxt/parse_test.go | 67 +++++++++++++++++++++ 2 files changed, 188 insertions(+), 19 deletions(-) diff --git a/reqtxt/parse.go b/reqtxt/parse.go index 33194d8..d1d6ec6 100644 --- a/reqtxt/parse.go +++ b/reqtxt/parse.go @@ -67,12 +67,7 @@ func Parse(content string, opts ...ParseOption) (*File, error) { file := &File{} for _, ll := range lines { - tokens, err := shlexSplit(ll.text) - if err != nil { - return nil, wrapLineErr(ll.line, err) - } - - entries, err := dispatchLine(tokens, ll.line) + entries, err := dispatchLogicalLine(ll.text, ll.line) if err != nil { return nil, err } @@ -82,16 +77,46 @@ func Parse(content string, opts ...ParseOption) (*File, error) { return file, nil } +// dispatchLogicalLine routes one preprocessed logical line to the flag +// path or the package path, deciding from the line's first +// whitespace-delimited raw token - before any shlex tokenization happens. +// This mirrors pip's req_file.process_line: pip never shlexes a +// package/requirement line's args, only its trailing per-line options +// (see break_args_options and dispatchPackageLine), because shlex would +// strip quotes that are semantically significant in a "; marker" clause +// and would choke on unquoted whitespace inside a version specifier. +func dispatchLogicalLine(text string, lineNum int) ([]Entry, error) { + fields := strings.Fields(text) + if len(fields) == 0 { + // preprocess already drops blank/all-whitespace logical lines; + // guard defensively in case that invariant ever changes. + return nil, nil + } + + if strings.HasPrefix(fields[0], "-") { + tokens, err := shlexSplit(text) + if err != nil { + return nil, wrapLineErr(lineNum, err) + } + return dispatchLine(tokens, lineNum) + } + + return dispatchPackageLine(text, lineNum) +} + // dispatchLine dispatches the tokens of one (recursive tail of a) logical -// line into zero or more Entry values, per pip's break_args_options: the -// leading token determines the entry kind. For the plain file-option -// branch only, any tokens left over after that flag's own value (if any) -// are dispatched again as if they began a new line — so e.g. an -// unrecognized boolean flag followed by a requirement ("--frob foo") -// yields two entries, rather than the flag swallowing "foo" as its value. -// The include/editable/package branches instead consume the *entire* -// remaining token stream for their own per-line options (hashes, etc.) -// and never recurse. +// line into zero or more Entry values: the leading token determines the +// entry kind. It is reached only for lines whose first raw token starts +// with "-" (see dispatchLogicalLine) - -r/-c/-e, a known file option, or +// an unrecognized flag - never for a package/requirement line, which +// dispatchPackageLine handles without shlex-tokenizing the whole line. +// For the plain file-option branch only, any tokens left over after that +// flag's own value (if any) are dispatched again as if they began a new +// line — so e.g. an unrecognized boolean flag followed by a requirement +// ("--frob foo") yields two entries, rather than the flag swallowing +// "foo" as its value. The include/editable/package branches instead +// consume the *entire* remaining token stream for their own per-line +// options (hashes, etc.) and never recurse. func dispatchLine(tokens []string, lineNum int) ([]Entry, error) { if len(tokens) == 0 { return nil, nil @@ -183,15 +208,20 @@ func dispatchFileOption(name string, hasEq bool, eqValue string, rest []string, if spec, known := knownOptions[name]; known { name = spec.long - if spec.arity == 1 { + switch { + case spec.arity == 1: var err error value, remaining, err = takeValue(name, hasEq, eqValue, rest, lineNum) if err != nil { return nil, err } - } else { - // A boolean known option never consumes a following token, - // even if it happened to be written with "=". + case hasEq: + // A known boolean (arity-0) option given an "=value" is + // invalid, matching pip optparse's rejection of a value for + // an option that doesn't take one (e.g. "--no-index=x"). + return nil, lineError(lineNum, "%s does not take a value", name) + default: + // A boolean known option never consumes a following token. value, remaining = eqValue, rest } } else { @@ -242,6 +272,78 @@ func dispatchPackage(first string, rest []string, lineNum int) ([]Entry, error) return []Entry{entry}, nil } +// dispatchPackageLine handles a package/requirement logical line - one +// whose first raw token does not start with "-" (see +// dispatchLogicalLine). It mirrors pip's break_args_options +// (pip/_internal/req/req_file.py): pip does NOT shlex-tokenize a +// package line's requirement text, only its trailing per-line options, +// because shlex would strip the quotes that are semantically +// significant in a "; marker" clause (e.g. `python_version >= "3.8"`) +// and would choke on the unquoted whitespace that's perfectly legal +// inside a version specifier (e.g. "Django >= 3.2, < 4.0"). The +// requirement/target text is passed to classifyTarget/requirement.Parse +// verbatim; only the options tail is shlex-tokenized and attached via +// attachReqOptions, exactly as dispatchPackage does for a package tail +// reached via token recursion. +func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { + argsText, optionsText := breakArgsOptions(line) + + // dispatchLogicalLine only calls dispatchPackageLine when line's + // first raw token doesn't start with "-", so breakArgsOptions always + // leaves at least that one token in argsText. + argFirst := strings.Fields(argsText)[0] + + var ( + entry Entry + hashes *[]Hash + options *[]OptionEntry + ) + + if kind, ok := classifyTarget(argFirst); ok { + e := &UnnamedEntry{Raw: argsText, Kind: kind, EggName: eggName(argsText)} + entry, hashes, options = e, &e.Hashes, &e.Options + } else { + req, err := requirement.Parse(argsText) + if err != nil { + return nil, wrapLineErr(lineNum, err) + } + e := &RequirementEntry{Requirement: req} + entry, hashes, options = e, &e.Hashes, &e.Options + } + + optTokens, err := shlexSplit(optionsText) + if err != nil { + return nil, wrapLineErr(lineNum, err) + } + if err := attachReqOptions(hashes, options, optTokens, lineNum); err != nil { + return nil, err + } + + return []Entry{entry}, nil +} + +// breakArgsOptions splits a package/requirement logical line into its +// requirement text ("args") and its per-line options tail ("options"), +// per pip's break_args_options (pip/_internal/req/req_file.py): pip +// plain-splits the line on whitespace and takes every leading token that +// doesn't start with "-" as part of the requirement, stopping at the +// first token that does - everything from there on is the options tail. +// Both halves are returned re-joined with single spaces (not the +// original, possibly irregular, whitespace), matching pip's +// ' '.join(...) of each half. +func breakArgsOptions(line string) (args string, options string) { + fields := strings.Fields(line) + + i := 0 + for ; i < len(fields); i++ { + if strings.HasPrefix(fields[i], "-") { + break + } + } + + return strings.Join(fields[:i], " "), strings.Join(fields[i:], " ") +} + // attachReqOptions consumes every token in tokens as a per-requirement // option (pip's SUPPORTED_OPTIONS_REQ), appending to *hashes or *options // as appropriate. Unlike dispatchFileOption, this never leaves tokens for diff --git a/reqtxt/parse_test.go b/reqtxt/parse_test.go index 584bd0c..731b1c7 100644 --- a/reqtxt/parse_test.go +++ b/reqtxt/parse_test.go @@ -21,6 +21,73 @@ func TestParse_Requirement(t *testing.T) { assert.Equal(t, "flask", re.Requirement.Name) } +func TestParse_RequirementWithUnquotedWhitespaceInSpecifier(t *testing.T) { + // Regression test: Parse used to shlex-tokenize the whole logical + // line and require every token after tokens[0] to be a per-line + // option, so unquoted whitespace inside a version specifier ("Django + // >= 3.2, < 4.0") errored on ">=" looking like an unexpected token. + f, err := Parse("Django >= 3.2, < 4.0") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "Django", re.Requirement.Name) + assert.Equal(t, ">=3.2,<4.0", re.Requirement.Specifiers.String()) +} + +func TestParse_RequirementWithQuotedMarker(t *testing.T) { + // Regression test: naively rejoining shlex tokens does not fix this + // case, because shlex strips the marker's quotes, and the quotes are + // semantically significant in a PEP 508 marker (python_version >= + // "3.8" is a string comparison, not a bareword). Parse must pass the + // requirement text through to requirement.Parse verbatim. + f, err := Parse(`flask ; python_version >= "3.8"`) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "flask", re.Requirement.Name) + assert.False(t, re.Requirement.Marker.IsEmpty()) + assert.Contains(t, re.Requirement.Marker.String(), "python_version") +} + +func TestParse_RequirementWithExtrasSpecifierAndHash(t *testing.T) { + f, err := Parse("requests[security] >= 2.0 --hash=sha256:abc") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "requests", re.Requirement.Name) + assert.Equal(t, []string{"security"}, re.Requirement.Extras) + assert.Equal(t, ">=2.0", re.Requirement.Specifiers.String()) + require.Len(t, re.Hashes, 1) + assert.Equal(t, Hash{Algorithm: "sha256", Digest: "abc"}, re.Hashes[0]) +} + +func TestParse_URLRequirementNotSplitOnHyphenInFilename(t *testing.T) { + // Regression test: the requirement text must be classified/parsed + // as a whole, not mis-split at the "-" inside the wheel filename + // (breakArgsOptions only ever looks at whether a *token* starts with + // "-", never at a "-" occurring mid-token). + f, err := Parse("pkg @ https://h/x-1.0.whl") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "pkg", re.Requirement.Name) + assert.Equal(t, "https://h/x-1.0.whl", re.Requirement.URL) +} + +func TestParse_ArityZeroKnownOptionRejectsValue(t *testing.T) { + _, err := Parse("--no-index=x") + require.Error(t, err) + assert.ErrorIs(t, err, ErrInvalidRequirementsFile) +} + func TestParse_Include(t *testing.T) { cases := []struct { name string From 5d52e52ebcd300a79bdbcba3af7e0efd0e49479f Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:05:00 -0400 Subject: [PATCH 08/16] fix(reqtxt): reject markers/extra content on direct-reference requirements (#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. --- reqtxt/parse.go | 11 +++++++++++ reqtxt/parse_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/reqtxt/parse.go b/reqtxt/parse.go index d1d6ec6..d0661ad 100644 --- a/reqtxt/parse.go +++ b/reqtxt/parse.go @@ -300,6 +300,17 @@ func dispatchPackageLine(line string, lineNum int) ([]Entry, error) { ) if kind, ok := classifyTarget(argFirst); ok { + // A bare target (VCS/URL/archive/path) must be the line's only + // argument token. UnnamedEntry has no Marker field, so any + // trailing content here - almost always a "; marker" clause, e.g. + // "./local/pkg ; python_version >= \"3.8\"" - can't be represented + // and would otherwise get silently glued onto Raw/EggName, + // corrupting the target. PEP 508 markers are only supported on + // named requirements, which route through requirement.Parse + // below. Reject instead of silently truncating/corrupting. + if fields := strings.Fields(argsText); len(fields) != 1 { + return nil, lineError(lineNum, "direct-reference requirement %q does not support markers or trailing content", argsText) + } e := &UnnamedEntry{Raw: argsText, Kind: kind, EggName: eggName(argsText)} entry, hashes, options = e, &e.Hashes, &e.Options } else { diff --git a/reqtxt/parse_test.go b/reqtxt/parse_test.go index 731b1c7..b60f9c2 100644 --- a/reqtxt/parse_test.go +++ b/reqtxt/parse_test.go @@ -246,6 +246,42 @@ func TestParse_BareArchiveIsUnnamed(t *testing.T) { assert.Equal(t, "foo-1.0.tar.gz", ue.Raw) } +func TestParse_DirectReferenceRejectsMarker(t *testing.T) { + // Regression test: UnnamedEntry has no Marker field, so a "; marker" + // clause (or any other trailing content) trailing a bare VCS/URL/ + // archive/path target must be rejected rather than silently glued + // into Raw/EggName. + _, err := Parse(`./local/pkg ; python_version >= "3.8"`) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile)) + + // A clean, single-token direct-reference target is still fine. + f, err := Parse("./local/pkg") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + ue, ok := f.Entries[0].(*UnnamedEntry) + require.True(t, ok, "want *UnnamedEntry, got %T", f.Entries[0]) + assert.Equal(t, KindLocalPath, ue.Kind) + assert.Equal(t, "./local/pkg", ue.Raw) +} + +func TestParse_QuotedDashInMarkerIsNotAnOptionsTail(t *testing.T) { + // Regression test: breakArgsOptions splits the options tail at the + // first *token* that starts with "-". The quoted marker value + // "-bar" is one shlex-atom, `"-bar"`, whose first character is a + // quote, not a dash, so it must stay part of the requirement args + // and not be mistaken for the start of a per-line options tail. + f, err := Parse(`foo ; extra == "-bar"`) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "foo", re.Requirement.Name) + assert.False(t, re.Requirement.Marker.IsEmpty()) +} + func TestParse_Env(t *testing.T) { lookup := func(name string) (string, bool) { if name == "TOKEN" { From e6f127d6b782b03fc1e9c8288a3f99abe88281a0 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:10:34 -0400 Subject: [PATCH 09/16] feat(reqtxt): String round-trip (#18639) 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) --- reqtxt/string.go | 87 +++++++++++++++++++++++++++ reqtxt/string_test.go | 135 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 reqtxt/string.go create mode 100644 reqtxt/string_test.go diff --git a/reqtxt/string.go b/reqtxt/string.go new file mode 100644 index 0000000..febecd7 --- /dev/null +++ b/reqtxt/string.go @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import "strings" + +// String renders f as a canonical requirements.txt document: one line per +// entry, in file order, joined with "\n". The rendering is not +// byte-identical to whatever produced f (comments and blank lines, which +// Parse drops, are never reconstructed), but Parse(f.String()) yields a +// File equivalent to f: every entry's semantic fields (name, extras, +// specifiers, marker, hashes, options, paths, ...) survive the round trip. +func (f *File) String() string { + lines := make([]string, len(f.Entries)) + for i, e := range f.Entries { + lines[i] = renderEntry(e) + } + return strings.Join(lines, "\n") +} + +// renderEntry renders a single Entry to its canonical line, per the +// per-type rules documented on File.String. +func renderEntry(e Entry) string { + switch v := e.(type) { + case *RequirementEntry: + var b strings.Builder + b.WriteString(v.Requirement.String()) + writeReqOptions(&b, v.Hashes, v.Options) + return b.String() + case *UnnamedEntry: + var b strings.Builder + if v.Editable { + b.WriteString("-e ") + } + b.WriteString(v.Raw) + writeReqOptions(&b, v.Hashes, v.Options) + return b.String() + case *IncludeEntry: + if v.Constraint { + return "-c " + v.Path + } + return "-r " + v.Path + case *OptionEntry: + return renderFileOption(*v) + default: + // Entry is a closed interface (only the four types above + // implement entry()), so this is unreachable barring a new + // implementation added without updating this switch. + return "" + } +} + +// writeReqOptions appends the canonical rendering of a RequirementEntry's +// or UnnamedEntry's per-line "--hash" values and other options to b: each +// as " --hash=:" or " =" (bare " " +// when Value is empty), in that order, matching the fields' declaration +// order on the struct. The "=" form (rather than a separate token) is used +// for per-line options so a value containing spaces still round-trips as +// a single shlex token. +func writeReqOptions(b *strings.Builder, hashes []Hash, options []OptionEntry) { + for _, h := range hashes { + b.WriteString(" --hash=") + b.WriteString(h.Algorithm) + b.WriteString(":") + b.WriteString(h.Digest) + } + for _, o := range options { + b.WriteString(" ") + b.WriteString(o.Name) + if o.Value != "" { + b.WriteString("=") + b.WriteString(o.Value) + } + } +} + +// renderFileOption renders a file-level OptionEntry as " ", +// using a space (rather than "=") to separate name and value: this matches +// the predominant form pip's own documentation and generated files use for +// file-level options (e.g. "--index-url https://..."). A bare boolean +// option (Value == "") renders as just its name (e.g. "--no-index"). +func renderFileOption(o OptionEntry) string { + if o.Value == "" { + return o.Name + } + return o.Name + " " + o.Value +} diff --git a/reqtxt/string_test.go b/reqtxt/string_test.go new file mode 100644 index 0000000..46a06bd --- /dev/null +++ b/reqtxt/string_test.go @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// reparse is a small test helper: it renders f via String(), re-parses the +// result, and returns the reparsed File, so tests can assert the two Files +// are equivalent entry-by-entry. +func reparse(t *testing.T, f *File) *File { + t.Helper() + rendered := f.String() + f2, err := Parse(rendered) + require.NoError(t, err, "reparsing rendered content failed: %q", rendered) + return f2 +} + +func TestFileString_RequirementWithHashesAndMarker(t *testing.T) { + f, err := Parse(`requests[security]>=2.0 ; python_version >= "3.8" --hash=sha256:aaa --hash=sha256:bbb`) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1) + + want, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok) + got, ok := f2.Entries[0].(*RequirementEntry) + require.True(t, ok) + + assert.Equal(t, want.Requirement.Name, got.Requirement.Name) + assert.Equal(t, want.Requirement.Extras, got.Requirement.Extras) + assert.Equal(t, want.Requirement.Specifiers.String(), got.Requirement.Specifiers.String()) + assert.Equal(t, want.Requirement.Marker.String(), got.Requirement.Marker.String()) + assert.False(t, got.Requirement.Marker.IsEmpty()) + assert.Equal(t, want.Hashes, got.Hashes) + require.Len(t, got.Hashes, 2) +} + +func TestFileString_EditableVCSWithEgg(t *testing.T) { + f, err := Parse("-e git+https://h/p#egg=n") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1) + + want, ok := f.Entries[0].(*UnnamedEntry) + require.True(t, ok) + got, ok := f2.Entries[0].(*UnnamedEntry) + require.True(t, ok) + + assert.True(t, got.Editable) + assert.Equal(t, KindVCS, got.Kind) + assert.Equal(t, "n", got.EggName) + assert.Equal(t, want.Raw, got.Raw) + assert.Equal(t, want.EggName, got.EggName) + assert.Equal(t, want.Kind, got.Kind) + assert.Equal(t, want.Editable, got.Editable) +} + +func TestFileString_Includes(t *testing.T) { + f, err := Parse("-r base.txt\n-c constraints.txt") + require.NoError(t, err) + require.Len(t, f.Entries, 2) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 2) + + incR, ok := f2.Entries[0].(*IncludeEntry) + require.True(t, ok) + assert.Equal(t, "base.txt", incR.Path) + assert.False(t, incR.Constraint) + + incC, ok := f2.Entries[1].(*IncludeEntry) + require.True(t, ok) + assert.Equal(t, "constraints.txt", incC.Path) + assert.True(t, incC.Constraint) +} + +func TestFileString_FileOptions(t *testing.T) { + f, err := Parse("--index-url https://i/simple\n--no-index\n--find-links x\n--find-links y") + require.NoError(t, err) + + f2 := reparse(t, f) + + indexURL, ok := f2.IndexURL() + require.True(t, ok) + assert.Equal(t, "https://i/simple", indexURL) + assert.True(t, f2.NoIndex()) + assert.Equal(t, []string{"x", "y"}, f2.FindLinks()) +} + +func TestFileString_UnnamedArchive(t *testing.T) { + f, err := Parse("foo-1.0.tar.gz") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1) + + got, ok := f2.Entries[0].(*UnnamedEntry) + require.True(t, ok) + assert.Equal(t, "foo-1.0.tar.gz", got.Raw) + assert.Equal(t, KindLocalPath, got.Kind) + assert.False(t, got.Editable) +} + +func TestFileString_CommentsDropped(t *testing.T) { + f, err := Parse("# c\nflask") + require.NoError(t, err) + + rendered := f.String() + assert.Contains(t, rendered, "flask") + assert.NotContains(t, rendered, "# c") + assert.NotContains(t, rendered, "#") +} + +func TestFileString_JoinsWithNewline(t *testing.T) { + f, err := Parse("flask\nrequests") + require.NoError(t, err) + require.Len(t, f.Entries, 2) + + rendered := f.String() + lines := strings.Split(rendered, "\n") + require.Len(t, lines, 2) + assert.True(t, strings.HasPrefix(lines[0], "flask")) + assert.True(t, strings.HasPrefix(lines[1], "requests")) +} From 00496eb9475356e29e9a4bd2f534f98c9e56a644 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:19:19 -0400 Subject: [PATCH 10/16] fix(reqtxt): round-trippable option rendering (= form + quote spaced 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. --- reqtxt/string.go | 57 ++++++++++++++++++++++++++++++------------- reqtxt/string_test.go | 46 ++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 17 deletions(-) diff --git a/reqtxt/string.go b/reqtxt/string.go index febecd7..0846c8c 100644 --- a/reqtxt/string.go +++ b/reqtxt/string.go @@ -41,7 +41,15 @@ func renderEntry(e Entry) string { } return "-r " + v.Path case *OptionEntry: - return renderFileOption(*v) + // A file-level option renders as "=" (see renderOption): + // a bare " " would not round-trip for an option that + // isn't in knownOptions, since dispatchFileOption only recovers a + // value for an unrecognized flag from the inline "=value" form — a + // bare "--unknown" is treated as a boolean and the following token + // is dispatched as a separate entry. Known arity-1 options (e.g. + // --index-url) also accept the "=" form on reparse, so using it + // uniformly doesn't regress them. + return renderOption(*v) default: // Entry is a closed interface (only the four types above // implement entry()), so this is unreachable barring a new @@ -56,32 +64,47 @@ func renderEntry(e Entry) string { // when Value is empty), in that order, matching the fields' declaration // order on the struct. The "=" form (rather than a separate token) is used // for per-line options so a value containing spaces still round-trips as -// a single shlex token. +// a single shlex token; the value (or hash algorithm:digest pair) is +// quoted via quoteIfNeeded so embedded whitespace survives shlex +// re-tokenization on reparse. func writeReqOptions(b *strings.Builder, hashes []Hash, options []OptionEntry) { for _, h := range hashes { b.WriteString(" --hash=") - b.WriteString(h.Algorithm) - b.WriteString(":") - b.WriteString(h.Digest) + b.WriteString(quoteIfNeeded(h.Algorithm + ":" + h.Digest)) } for _, o := range options { b.WriteString(" ") - b.WriteString(o.Name) - if o.Value != "" { - b.WriteString("=") - b.WriteString(o.Value) - } + b.WriteString(renderOption(o)) } } -// renderFileOption renders a file-level OptionEntry as " ", -// using a space (rather than "=") to separate name and value: this matches -// the predominant form pip's own documentation and generated files use for -// file-level options (e.g. "--index-url https://..."). A bare boolean -// option (Value == "") renders as just its name (e.g. "--no-index"). -func renderFileOption(o OptionEntry) string { +// renderOption renders an OptionEntry (file-level or per-line) as +// "=" (quoting value via quoteIfNeeded so it survives shlex +// re-tokenization), or bare "" when Value is empty. +func renderOption(o OptionEntry) string { if o.Value == "" { return o.Name } - return o.Name + " " + o.Value + return o.Name + "=" + quoteIfNeeded(o.Value) +} + +// quoteIfNeeded returns s unchanged if it contains no shlex-significant +// whitespace or double quotes; otherwise it wraps s in double quotes, +// backslash-escaping any '"' or '\\' so the result re-tokenizes (via +// shlexSplit's double-quote handling) back to the original value. +func quoteIfNeeded(s string) string { + if !strings.ContainsAny(s, " \t\"") { + return s + } + + var b strings.Builder + b.WriteByte('"') + for _, r := range s { + if r == '"' || r == '\\' { + b.WriteByte('\\') + } + b.WriteRune(r) + } + b.WriteByte('"') + return b.String() } diff --git a/reqtxt/string_test.go b/reqtxt/string_test.go index 46a06bd..536e96b 100644 --- a/reqtxt/string_test.go +++ b/reqtxt/string_test.go @@ -97,6 +97,52 @@ func TestFileString_FileOptions(t *testing.T) { assert.Equal(t, []string{"x", "y"}, f2.FindLinks()) } +func TestFileString_UnknownFileOptionWithValue(t *testing.T) { + // Regression test: an unknown file-level option with a value must + // round-trip through the "=" form. A bare "--cert /etc/ssl/ca.pem" + // reparse would silently corrupt this into a boolean "--cert" plus a + // phantom UnnamedEntry for "/etc/ssl/ca.pem" (dispatchFileOption only + // recovers a value for an unrecognized flag from the inline "=value" + // form). + f, err := Parse("--cert=/etc/ssl/ca.pem") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1, "expected exactly one entry, no phantom entry from misparsed value") + + got, ok := f2.Entries[0].(*OptionEntry) + require.True(t, ok) + assert.Equal(t, "--cert", got.Name) + assert.Equal(t, "/etc/ssl/ca.pem", got.Value) +} + +func TestFileString_KnownFileOptionValueWithSpace(t *testing.T) { + f, err := Parse(`--find-links "/opt/my links"`) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1) + + assert.Equal(t, []string{"/opt/my links"}, f2.FindLinks()) +} + +func TestFileString_PerLineOptionRoundTrip(t *testing.T) { + f, err := Parse(`flask --config-settings=key=val`) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + f2 := reparse(t, f) + require.Len(t, f2.Entries, 1) + + got, ok := f2.Entries[0].(*RequirementEntry) + require.True(t, ok) + require.Len(t, got.Options, 1) + assert.Equal(t, "--config-settings", got.Options[0].Name) + assert.Equal(t, "key=val", got.Options[0].Value) +} + func TestFileString_UnnamedArchive(t *testing.T) { f, err := Parse("foo-1.0.tar.gz") require.NoError(t, err) From 69a95bc13a0205cb66642d7ad71ed0b61fdb5230 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:23:38 -0400 Subject: [PATCH 11/16] feat(reqtxt): Flatten include walker (#18639) --- reqtxt/flatten.go | 145 +++++++++++++++++++++++++++++ reqtxt/flatten_test.go | 202 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 347 insertions(+) create mode 100644 reqtxt/flatten.go create mode 100644 reqtxt/flatten_test.go diff --git a/reqtxt/flatten.go b/reqtxt/flatten.go new file mode 100644 index 0000000..111bfce --- /dev/null +++ b/reqtxt/flatten.go @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "bytes" + "errors" + "fmt" + "path" + "regexp" + "strings" +) + +// utf8BOM is the UTF-8 encoding of U+FEFF (byte order mark), which some +// requirements files (and pip itself, via its charset-detection fallback) +// tolerate as a leading marker. Flatten contracts UTF-8 input and strips a +// leading BOM before handing content to Parse, since Parse has no charset +// awareness of its own. +var utf8BOM = []byte{0xEF, 0xBB, 0xBF} + +// schemeRE matches a URL scheme prefix (RFC 3986 ALPHA *( ALPHA / DIGIT / +// "+" / "-" / "." ) "://"), e.g. "https://", "file://", "git+https://". +// Flatten uses this (alongside a leading "/") to decide whether an include +// target is passed to open verbatim rather than resolved against the +// referencing file's directory. +var schemeRE = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*://`) + +// Flatten parses the file at root and follows its "-r"/"-c" includes +// (pip's parse_requirements / RequirementsFileParser._parse_and_recurse in +// pip._internal.req.req_file) to produce a single File with every include +// expanded inline, in the order encountered by a depth-first traversal. +// Each IncludeEntry is consumed and dropped; the entries of the file it +// references are spliced into its place. All file content is obtained via +// open, which Flatten decodes as UTF-8, stripping a leading byte-order +// mark. root is passed to open verbatim; relative include targets nested +// inside it (and inside whatever it includes) are resolved against the +// referencing file's directory using slash-based path semantics - +// deliberately not the OS-dependent filepath package, so behavior doesn't +// depend on host CWD or path separator. opts is threaded to every +// recursive Parse call, so e.g. WithEnv expansion is applied consistently +// at every level of the include tree. +func Flatten(root string, open func(path string) ([]byte, error), opts ...ParseOption) (*File, error) { + entries, err := flattenWalk(root, false, map[string]bool{}, open, opts) + if err != nil { + return nil, err + } + return &File{Entries: entries}, nil +} + +// flattenWalk parses the file at p and recursively expands its includes, +// returning the flattened entries it (transitively) contributes. +// constraintCtx is true if p was itself reached via a "-c"/"--constraint" +// include (or transitively from one); visited is the set of resolved +// paths on the CURRENT recursion stack, used for cycle detection - a +// diamond (the same file reached via two different, non-overlapping +// branches) is fine and yields its entries twice (see the double-inclusion +// case below); a path already on the active stack is a true cycle. +func flattenWalk(p string, constraintCtx bool, visited map[string]bool, open func(string) ([]byte, error), opts []ParseOption) ([]Entry, error) { + if visited[p] { + return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("%q recursively includes itself", p)) + } + + raw, err := open(p) + if err != nil { + return nil, errors.Join(ErrInvalidRequirementsFile, fmt.Errorf("opening %q: %w", p, err)) + } + + content := decodeUTF8(raw) + + file, err := Parse(content, opts...) + if err != nil { + return nil, err + } + + visited[p] = true + defer delete(visited, p) + + var out []Entry + for _, e := range file.Entries { + switch v := e.(type) { + case *IncludeEntry: + target := resolveInclude(p, v.Path) + + // childConstraint: the transitive-closure interpretation - once + // the walk crosses a "-c" edge, every entry below stays a + // constraint, even a further "-r" nested inside the + // "-c"-included file. This is the design's stated default + // (docs/rfds design note, task 7 spec), NOT what pip itself + // does: verified against pip._internal.req.req_file + // (RequirementsFileParser._parse_and_recurse), pip computes + // nested_constraint solely from the include *directive* + // ("-r" vs "-c") that reached the nested file, without OR-ing + // in the ambient constraint flag of the referencing file - so + // pip actually RESETS constraint-ness on a "-r" nested inside + // a "-c" file, rather than inheriting it. This is a deliberate, + // documented divergence for this package; confirm/reconcile + // against pip's exact rule at PPM-cutover time if constraint + // semantics for deeply-nested includes end up load-bearing. + childConstraint := constraintCtx || v.Constraint + + children, err := flattenWalk(target, childConstraint, visited, open, opts) + if err != nil { + return nil, err + } + out = append(out, children...) + + case *RequirementEntry: + cp := *v + cp.Constraint = constraintCtx || v.Constraint + out = append(out, &cp) + + case *UnnamedEntry: + cp := *v + cp.Constraint = constraintCtx || v.Constraint + out = append(out, &cp) + + default: + out = append(out, e) + } + } + + return out, nil +} + +// decodeUTF8 decodes raw as UTF-8 text, stripping a leading byte-order +// mark if present. +func decodeUTF8(raw []byte) string { + raw = bytes.TrimPrefix(raw, utf8BOM) + return string(raw) +} + +// resolveInclude resolves an include directive's target path, as found in +// the file at referencedFrom, into the path Flatten will pass to open. +// An absolute path (leading "/") or a scheme-bearing reference (e.g. +// "https://...", "file://...") is passed through verbatim - open decides +// how to fetch it. Otherwise, target is relative and is joined to +// referencedFrom's directory using slash-based (path package) semantics +// and cleaned, mirroring pip's os.path.join(os.path.dirname(filename), +// req_path) but OS-independent. +func resolveInclude(referencedFrom, target string) string { + if strings.HasPrefix(target, "/") || schemeRE.MatchString(target) { + return target + } + return path.Clean(path.Join(path.Dir(referencedFrom), target)) +} diff --git a/reqtxt/flatten_test.go b/reqtxt/flatten_test.go new file mode 100644 index 0000000..94fe8d5 --- /dev/null +++ b/reqtxt/flatten_test.go @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package reqtxt + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// mapOpener returns an opener (Flatten's "open" parameter) backed by m: a +// lookup for path returns m[path], or an error if path isn't a key. +func mapOpener(m map[string][]byte) func(string) ([]byte, error) { + return func(path string) ([]byte, error) { + content, ok := m[path] + if !ok { + return nil, fmt.Errorf("mapOpener: no such file %q", path) + } + return content, nil + } +} + +func TestFlatten_NestedRequirement(t *testing.T) { + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r a.txt\n"), + "a.txt": []byte("foo\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "foo", re.Requirement.Name) + assert.False(t, re.Constraint) + + assert.Empty(t, f.Includes(), "IncludeEntry should be dropped, not spliced in") +} + +func TestFlatten_RelativeSubdir(t *testing.T) { + var openedPaths []string + base := mapOpener(map[string][]byte{ + "root.txt": []byte("-r sub/a.txt\n"), + "sub/a.txt": []byte("-r b.txt\n"), + "sub/b.txt": []byte("bar\n"), + }) + open := func(path string) ([]byte, error) { + openedPaths = append(openedPaths, path) + return base(path) + } + + f, err := Flatten("root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "bar", re.Requirement.Name) + + // b.txt is referenced bare from sub/a.txt; it must resolve against + // sub/a.txt's directory ("sub"), not root.txt's directory ("."). + assert.Contains(t, openedPaths, "sub/b.txt") +} + +func TestFlatten_AbsoluteIncludeVerbatim(t *testing.T) { + var openedPaths []string + base := mapOpener(map[string][]byte{ + "root.txt": []byte("-r /abs/x.txt\n"), + "/abs/x.txt": []byte("foo\n"), + }) + open := func(path string) ([]byte, error) { + openedPaths = append(openedPaths, path) + return base(path) + } + + f, err := Flatten("root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + assert.Contains(t, openedPaths, "/abs/x.txt") +} + +func TestFlatten_URLIncludeVerbatim(t *testing.T) { + var openedPaths []string + base := mapOpener(map[string][]byte{ + "root.txt": []byte("-r https://h/x.txt\n"), + "https://h/x.txt": []byte("foo\n"), + }) + open := func(path string) ([]byte, error) { + openedPaths = append(openedPaths, path) + return base(path) + } + + f, err := Flatten("root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + assert.Contains(t, openedPaths, "https://h/x.txt") +} + +func TestFlatten_ConstraintPropagation(t *testing.T) { + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-c constraints.txt\n-r r.txt\n"), + "constraints.txt": []byte("bar==1\n"), + "r.txt": []byte("baz\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 2) + + byName := map[string]*RequirementEntry{} + for _, e := range f.Entries { + re, ok := e.(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", e) + byName[re.Requirement.Name] = re + } + + require.Contains(t, byName, "bar") + assert.True(t, byName["bar"].Constraint, "bar came in via -c, should be a constraint") + + require.Contains(t, byName, "baz") + assert.False(t, byName["baz"].Constraint, "baz came in via -r, should not be a constraint") +} + +func TestFlatten_NestedRequirementUnderConstraint(t *testing.T) { + // Design/task-spec default: transitive closure. Once the walk crosses + // a -c edge, constraint-ness stays true for everything below, + // including a further -r nested inside the -c-included file. See the + // code comment on walk's childConstraint computation in flatten.go + // for the verified pip divergence. + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-c c.txt\n"), + "c.txt": []byte("-r more.txt\n"), + "more.txt": []byte("qux\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "qux", re.Requirement.Name) + assert.True(t, re.Constraint, "qux is nested under a -c include, transitive-closure default => Constraint true") +} + +func TestFlatten_DoubleInclusionNoDedup(t *testing.T) { + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r a.txt\n-c a.txt\n"), + "a.txt": []byte("foo\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 2, "no dedup: the same file included twice yields two entries") + + var sawFalse, sawTrue bool + for _, e := range f.Entries { + re, ok := e.(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", e) + assert.Equal(t, "foo", re.Requirement.Name) + if re.Constraint { + sawTrue = true + } else { + sawFalse = true + } + } + assert.True(t, sawFalse, "expected one non-constraint foo (via -r)") + assert.True(t, sawTrue, "expected one constraint foo (via -c)") +} + +func TestFlatten_Cycle(t *testing.T) { + _, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r a.txt\n"), + "a.txt": []byte("-r b.txt\n"), + "b.txt": []byte("-r a.txt\n"), + })) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile)) +} + +func TestFlatten_OpenerErrorWrapped(t *testing.T) { + _, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r missing.txt\n"), + })) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile)) +} + +func TestFlatten_BOMStripped(t *testing.T) { + content := append([]byte{0xEF, 0xBB, 0xBF}, []byte("flask\n")...) + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": content, + })) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "flask", re.Requirement.Name) +} + +func TestFlatten_RootLevelOpenerError(t *testing.T) { + _, err := Flatten("nonexistent.txt", mapOpener(map[string][]byte{})) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidRequirementsFile)) +} From 8d460e8ae911a2098ecea5836c514040d413aa1c Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:30:52 -0400 Subject: [PATCH 12/16] fix(reqtxt): constraint-ness set by immediate include directive, matching 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. --- reqtxt/flatten.go | 33 ++++++++++++++++----------------- reqtxt/flatten_test.go | 33 ++++++++++++++++++++++++++------- 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/reqtxt/flatten.go b/reqtxt/flatten.go index 111bfce..54d36cf 100644 --- a/reqtxt/flatten.go +++ b/reqtxt/flatten.go @@ -50,7 +50,9 @@ func Flatten(root string, open func(path string) ([]byte, error), opts ...ParseO // flattenWalk parses the file at p and recursively expands its includes, // returning the flattened entries it (transitively) contributes. // constraintCtx is true if p was itself reached via a "-c"/"--constraint" -// include (or transitively from one); visited is the set of resolved +// include - specifically the immediate include directive that pulled p in, +// not any ancestor further up the include chain (see childConstraint below); +// visited is the set of resolved // paths on the CURRENT recursion stack, used for cycle detection - a // diamond (the same file reached via two different, non-overlapping // branches) is fine and yields its entries twice (see the double-inclusion @@ -81,22 +83,19 @@ func flattenWalk(p string, constraintCtx bool, visited map[string]bool, open fun case *IncludeEntry: target := resolveInclude(p, v.Path) - // childConstraint: the transitive-closure interpretation - once - // the walk crosses a "-c" edge, every entry below stays a - // constraint, even a further "-r" nested inside the - // "-c"-included file. This is the design's stated default - // (docs/rfds design note, task 7 spec), NOT what pip itself - // does: verified against pip._internal.req.req_file - // (RequirementsFileParser._parse_and_recurse), pip computes - // nested_constraint solely from the include *directive* - // ("-r" vs "-c") that reached the nested file, without OR-ing - // in the ambient constraint flag of the referencing file - so - // pip actually RESETS constraint-ness on a "-r" nested inside - // a "-c" file, rather than inheriting it. This is a deliberate, - // documented divergence for this package; confirm/reconcile - // against pip's exact rule at PPM-cutover time if constraint - // semantics for deeply-nested includes end up load-bearing. - childConstraint := constraintCtx || v.Constraint + // childConstraint is set solely by the immediate include + // directive that reached the nested file, matching pip: + // pip._internal.req.req_file.RequirementsFileParser + // ._parse_and_recurse sets nested_constraint = False for a + // "-r"/"--requirement" directive and nested_constraint = True + // for a "-c"/"--constraint" directive, then recurses with that + // value alone - it is never OR'd with the ambient constraint + // flag of the referencing file. So a "-r" nested inside a + // "-c"-included file RESETS constraint-ness to false for + // everything below it, while a "-c" nested inside a + // "-r"-included file sets it to true regardless of the outer + // context. + childConstraint := v.Constraint children, err := flattenWalk(target, childConstraint, visited, open, opts) if err != nil { diff --git a/reqtxt/flatten_test.go b/reqtxt/flatten_test.go index 94fe8d5..acf3ca6 100644 --- a/reqtxt/flatten_test.go +++ b/reqtxt/flatten_test.go @@ -121,12 +121,13 @@ func TestFlatten_ConstraintPropagation(t *testing.T) { assert.False(t, byName["baz"].Constraint, "baz came in via -r, should not be a constraint") } -func TestFlatten_NestedRequirementUnderConstraint(t *testing.T) { - // Design/task-spec default: transitive closure. Once the walk crosses - // a -c edge, constraint-ness stays true for everything below, - // including a further -r nested inside the -c-included file. See the - // code comment on walk's childConstraint computation in flatten.go - // for the verified pip divergence. +func TestFlatten_NestedRequirementUnderConstraintResets(t *testing.T) { + // Matches pip: constraint-ness is set solely by the immediate include + // directive that pulled a file in, not inherited from an ancestor. A + // -r nested inside a -c-included file RESETS constraint-ness to + // false. See pip._internal.req.req_file.RequirementsFileParser + // ._parse_and_recurse and the code comment on flattenWalk's + // childConstraint computation in flatten.go. f, err := Flatten("root.txt", mapOpener(map[string][]byte{ "root.txt": []byte("-c c.txt\n"), "c.txt": []byte("-r more.txt\n"), @@ -138,7 +139,25 @@ func TestFlatten_NestedRequirementUnderConstraint(t *testing.T) { re, ok := f.Entries[0].(*RequirementEntry) require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) assert.Equal(t, "qux", re.Requirement.Name) - assert.True(t, re.Constraint, "qux is nested under a -c include, transitive-closure default => Constraint true") + assert.False(t, re.Constraint, "qux is nested under -c via a -r directive, which resets Constraint to false") +} + +func TestFlatten_NestedConstraintUnderRequirementSets(t *testing.T) { + // Symmetric case: a -c nested inside a -r-included file sets + // constraint-ness to true, regardless of the outer (non-constraint) + // context. + f, err := Flatten("root.txt", mapOpener(map[string][]byte{ + "root.txt": []byte("-r r.txt\n"), + "r.txt": []byte("-c inner.txt\n"), + "inner.txt": []byte("zap\n"), + })) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "zap", re.Requirement.Name) + assert.True(t, re.Constraint, "zap is nested under -r via a -c directive, which sets Constraint to true") } func TestFlatten_DoubleInclusionNoDedup(t *testing.T) { From 67ba08eda32806bd308695172ccdcc8443f0cdae Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:35:15 -0400 Subject: [PATCH 13/16] docs(reqtxt): correct Constraint field docs to pip immediate-directive semantics (#18639) --- reqtxt/types.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/reqtxt/types.go b/reqtxt/types.go index a413000..b034b93 100644 --- a/reqtxt/types.go +++ b/reqtxt/types.go @@ -32,9 +32,11 @@ type RequirementEntry struct { Requirement requirement.Requirement Hashes []Hash Options []OptionEntry - // Constraint is true if this entry came from a file included via - // "-c"/"--constraint" (or transitively from one), rather than - // "-r"/"--requirement" or the top-level file. + // Constraint is true when the file this entry appears in was included + // via "-c"/"--constraint". Constraint-ness is set by the immediate + // include directive (per pip's req_file._parse_and_recurse); it is NOT + // inherited through nested includes, so a "-r" nested inside a "-c" file + // yields non-constraint entries. Set by Flatten; false after Parse alone. Constraint bool } @@ -63,9 +65,11 @@ type UnnamedEntry struct { EggName string Hashes []Hash Options []OptionEntry - // Constraint is true if this entry came from a file included via - // "-c"/"--constraint" (or transitively from one), rather than - // "-r"/"--requirement" or the top-level file. + // Constraint is true when the file this entry appears in was included + // via "-c"/"--constraint". Constraint-ness is set by the immediate + // include directive (per pip's req_file._parse_and_recurse); it is NOT + // inherited through nested includes, so a "-r" nested inside a "-c" file + // yields non-constraint entries. Set by Flatten; false after Parse alone. Constraint bool } From dca2b8a6bfda5647aabd08e75ab3cc75872d09e7 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:36:38 -0400 Subject: [PATCH 14/16] docs(reqtxt): attribution + package docs (#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. --- NOTICE | 9 +++++++++ README.md | 2 +- reqtxt/doc.go | 21 +++++++++++++++++++-- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/NOTICE b/NOTICE index 3d64019..c285e24 100644 --- a/NOTICE +++ b/NOTICE @@ -67,3 +67,12 @@ The marker/ package's Evaluate adapts the marker-evaluation logic of pypa/packaging (https://github.com/pypa/packaging), specifically packaging/markers.py's `_eval_op` and its operator/specifier dispatch, licensed under the Apache License, Version 2.0. + +The reqtxt/ package adapts pip's requirements-file parsing behavior from +pip (https://github.com/pypa/pip), specifically +pip/_internal/req/req_file.py's `preprocess`/`join_lines` line-joining +pipeline, `break_args_options`, `COMMENT_RE`, `ENV_VAR_RE`, and +`_parse_and_recurse`'s include-following, licensed under the MIT license; +and from Astral's uv (https://github.com/astral-sh/uv), specifically its +uv-requirements crate, dual-licensed under the Apache License, Version +2.0, or the MIT license. diff --git a/README.md b/README.md index d795ee0..4ac3cdd 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Part of [RFD 0001 — Native Go PyPI Dependency Resolution](https://github.com/r | `requirement/` | PEP 508 dependency specifiers (implemented) | | `marker/` | PEP 508 environment markers (implemented) | | `extras/` | PEP 685 extra-name normalization (implemented) | -| `reqtxt/` | pip `requirements.txt` format | +| `reqtxt/` | pip `requirements.txt` format (implemented) | | [`distribution/`](https://github.com/rstudio/python-distribution-parser) | METADATA / wheel parsing | | `wheelname/` | PEP 427 wheel filename → name/version/build/tags (implemented) | | `tags/` | PEP 425/600/656 compatibility tags (server-side, target-parameterized; no host detection) | diff --git a/reqtxt/doc.go b/reqtxt/doc.go index 4db40e7..ecb1184 100644 --- a/reqtxt/doc.go +++ b/reqtxt/doc.go @@ -1,7 +1,24 @@ // SPDX-License-Identifier: Apache-2.0 OR MIT // Package reqtxt parses pip's requirements.txt file format, a superset of -// PEP 508 requirement lines with pip-specific directives. +// PEP 508 requirement lines with pip-specific directives ("-r"/"-c" +// includes, "-e" editables, VCS/URL/local-path targets, global and +// per-requirement options, "${VAR}" environment expansion, and inline +// comments). // -// TODO(#18639): implement the requirements.txt parser. +// Parse takes requirements.txt content as a string and returns an ordered +// *File of typed Entry values (RequirementEntry, IncludeEntry, +// UnnamedEntry, OptionEntry) reflecting pip's own line-classification and +// dispatch rules. Parse is pure: it does no I/O and does not follow "-r"/ +// "-c" includes, so a File's IncludeEntry values name paths the caller +// still has to resolve. Flatten does that: given a root path and a +// caller-supplied opener, it recursively parses and inlines every included +// file's entries in file order, tracking constraint-ness and detecting +// include cycles. WithEnv, a ParseOption accepted by both Parse and +// Flatten, enables "${VAR}" expansion against a caller-supplied lookup. +// File.String() renders a File back to requirements.txt text; reparsing +// that text reproduces the same entries (comments aside). +// +// reqtxt builds on the requirement package for the PEP 508 requirement +// specifiers that make up RequirementEntry.Requirement. package reqtxt From eee395a9296f58416cffa3219e2e3f9ca239686d Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:49:58 -0400 Subject: [PATCH 15/16] fix(reqtxt): guard whole-line comment continuations + round-trip empty 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. --- reqtxt/preprocess.go | 23 ++++++++++++++-- reqtxt/preprocess_test.go | 48 ++++++++++++++++++++++++++++++++++ reqtxt/string.go | 28 +++++++++++++++++++- reqtxt/string_test.go | 55 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 3 deletions(-) diff --git a/reqtxt/preprocess.go b/reqtxt/preprocess.go index 28dcc6a..5768efb 100644 --- a/reqtxt/preprocess.go +++ b/reqtxt/preprocess.go @@ -67,7 +67,16 @@ type logicalLine struct { // 2. Join backslash continuations: a physical line ending in "\" // concatenates directly to the next physical line, with NO separator // inserted (the trailing "\" is simply removed). The joined logical -// line's line number is that of its first physical segment. +// line's line number is that of its first physical segment. A +// WHOLE-LINE comment (one whose first non-whitespace character is "#") +// is never treated as a continuation, even if it ends in "\": pip's +// join_lines guards on COMMENT_RE.match(line) (req_file.py:501) before +// honoring a trailing backslash, so a line like "# note \" ends its own +// logical line (and, being a comment, is then dropped by step 3/4) +// rather than swallowing the next physical line into the comment. An +// INLINE comment ending in "\" (e.g. "django # c \") is unaffected and +// still joins, matching pip: the guard only fires for a line that is a +// comment in its entirety. // 3. Strip comments per commentRE. // 4. Drop logical lines that are empty or all-whitespace once comments // are stripped. @@ -113,7 +122,7 @@ func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { joined.Reset() } - if rest, ok := strings.CutSuffix(physical, `\`); ok { + if rest, ok := strings.CutSuffix(physical, `\`); ok && !isWholeLineComment(physical) { joined.WriteString(rest) continue } @@ -128,6 +137,16 @@ func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { return lines, nil } +// isWholeLineComment reports whether physical is a whole-line comment: its +// first non-whitespace character is "#". This is pip's join_lines guard +// (COMMENT_RE.match(line), req_file.py:501) restated for our purposes: an +// INLINE comment (preceded by non-whitespace content, e.g. "django # c") +// does not match here and is not a whole-line comment, even though +// commentRE itself would still strip it later. +func isWholeLineComment(physical string) bool { + return strings.HasPrefix(strings.TrimLeft(physical, " \t"), "#") +} + // normalizeLineEndings converts "\r\n" and lone "\r" to "\n", matching // Python's universal-newlines splitlines() behavior that pip's preprocess // relies on. diff --git a/reqtxt/preprocess_test.go b/reqtxt/preprocess_test.go index 97a838c..9f46ff4 100644 --- a/reqtxt/preprocess_test.go +++ b/reqtxt/preprocess_test.go @@ -41,6 +41,54 @@ func TestPreprocess_Continuations(t *testing.T) { } } +// TestPreprocess_WholeLineCommentContinuationGuard exercises pip's +// join_lines guard (req_file.py:501): "if not line.endswith('\\') or +// COMMENT_RE.match(line)" - a physical line ending in "\" is NOT a +// continuation when it is itself a whole-line comment (COMMENT_RE matches +// at position 0, i.e. the first non-whitespace character is "#"). Without +// this guard, a trailing "\" on a comment line joins the next physical +// line directly onto the comment text, so by the time comments are +// stripped the entire logical line - including whatever followed the +// comment - is gone: e.g. "# TODO: pin this \" + "django" joins to +// "# TODO: pin this django", which commentRE then strips to nothing, +// silently discarding the "django" requirement pip would still install. +func TestPreprocess_WholeLineCommentContinuationGuard(t *testing.T) { + cases := []struct { + name string + content string + want []logicalLine + }{ + { + name: "whole-line comment ending in backslash does not swallow the next line", + content: "# TODO: pin this \\\ndjango", + want: []logicalLine{{text: "django", line: 2}}, + }, + { + name: "indented whole-line comment ending in backslash does not swallow the next line", + content: " # c \\\nbar", + want: []logicalLine{{text: "bar", line: 2}}, + }, + { + name: "regression: an ordinary continuation still joins", + content: "foo==\\\n1.0", + want: []logicalLine{{text: "foo==1.0", line: 1}}, + }, + { + name: "regression: an inline comment ending in backslash still joins (not a whole-line comment)", + content: "django # c \\\nfoo", + want: []logicalLine{{text: "django", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, parseConfig{}) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + func TestPreprocess_Comments(t *testing.T) { cases := []struct { name string diff --git a/reqtxt/string.go b/reqtxt/string.go index 0846c8c..4b0bebd 100644 --- a/reqtxt/string.go +++ b/reqtxt/string.go @@ -80,14 +80,40 @@ func writeReqOptions(b *strings.Builder, hashes []Hash, options []OptionEntry) { // renderOption renders an OptionEntry (file-level or per-line) as // "=" (quoting value via quoteIfNeeded so it survives shlex -// re-tokenization), or bare "" when Value is empty. +// re-tokenization), or bare "" when Value is empty - unless name +// identifies a value-taking option (isValueTakingOption), in which case an +// empty Value is rendered as the explicit "=\"\"" form instead of a +// bare flag. Without this, an empty value on a value-taking option (e.g. +// Parse("--index-url=") or a per-line "--global-option=") would render +// indistinguishably from a boolean flag, and reparsing the bare form would +// hit that option's "requires a value" arity check - breaking the +// Parse(f.String()) round trip. A genuinely boolean/arity-0 option (or an +// unrecognized bare flag) with Value == "" is unaffected and still renders +// bare, matching its actual on-the-wire form. func renderOption(o OptionEntry) string { if o.Value == "" { + if isValueTakingOption(o.Name) { + return o.Name + `=""` + } return o.Name } return o.Name + "=" + quoteIfNeeded(o.Value) } +// isValueTakingOption reports whether name (an OptionEntry.Name) identifies +// an option that takes a value: a known file-level option with arity 1 +// (knownOptions, defined in parse.go), or a per-requirement value option +// (perLineValueOptions, also parse.go). Both tables are keyed by an +// option's canonical spelling, which is exactly what dispatchFileOption and +// attachReqOptions ever store into OptionEntry.Name, so a direct lookup by +// name is sufficient here. +func isValueTakingOption(name string) bool { + if spec, ok := knownOptions[name]; ok { + return spec.arity == 1 + } + return perLineValueOptions[name] +} + // quoteIfNeeded returns s unchanged if it contains no shlex-significant // whitespace or double quotes; otherwise it wraps s in double quotes, // backslash-escaping any '"' or '\\' so the result re-tokenizes (via diff --git a/reqtxt/string_test.go b/reqtxt/string_test.go index 536e96b..c9abd6d 100644 --- a/reqtxt/string_test.go +++ b/reqtxt/string_test.go @@ -143,6 +143,61 @@ func TestFileString_PerLineOptionRoundTrip(t *testing.T) { assert.Equal(t, "key=val", got.Options[0].Value) } +func TestFileString_EmptyValueOptionRoundTrips(t *testing.T) { + // Regression test: a value-taking option given an explicitly empty + // value (e.g. "--index-url=") must round-trip through the explicit + // '=""' form. Rendering it as a bare "--index-url" would reparse + // as arity-1 with no value supplied at all, which is an error (the + // option "requires a value"), so Parse(f.String()) would fail. + f, err := Parse("--index-url=") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + rendered := f.String() + f2, err := Parse(rendered) + require.NoError(t, err, "reparsing rendered content failed: %q", rendered) + require.Len(t, f2.Entries, 1) + + got, ok := f2.Entries[0].(*OptionEntry) + require.True(t, ok) + assert.Equal(t, "--index-url", got.Name) + assert.Equal(t, "", got.Value) +} + +func TestFileString_EmptyValuePerLineOptionRoundTrips(t *testing.T) { + f, err := Parse("flask --global-option=") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + rendered := f.String() + f2, err := Parse(rendered) + require.NoError(t, err, "reparsing rendered content failed: %q", rendered) + require.Len(t, f2.Entries, 1) + + got, ok := f2.Entries[0].(*RequirementEntry) + require.True(t, ok) + require.Len(t, got.Options, 1) + assert.Equal(t, "--global-option", got.Options[0].Name) + assert.Equal(t, "", got.Options[0].Value) +} + +func TestFileString_BooleanOptionStillRendersBare(t *testing.T) { + // A genuinely boolean (arity-0) option with an empty Value must still + // render as a bare flag, not "--no-index=\"\"": only value-taking + // options need the explicit empty-value form. + f, err := Parse("--no-index") + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + rendered := f.String() + assert.Equal(t, "--no-index", rendered) + + f2, err := Parse(rendered) + require.NoError(t, err) + require.Len(t, f2.Entries, 1) + assert.True(t, f2.NoIndex()) +} + func TestFileString_UnnamedArchive(t *testing.T) { f, err := Parse("foo-1.0.tar.gz") require.NoError(t, err) From 0e5a4ec8583ca3d2ca3306567ae54ce624b4c576 Mon Sep 17 00:00:00 2001 From: Jonathan Yoder Date: Fri, 10 Jul 2026 08:58:47 -0400 Subject: [PATCH 16/16] fix(reqtxt): URL-relative includes, Unicode comment whitespace, case-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=". --- reqtxt/classify.go | 32 ++++++++++++----------- reqtxt/classify_test.go | 11 ++++++++ reqtxt/flatten.go | 21 ++++++++++++--- reqtxt/flatten_test.go | 27 +++++++++++++++++++ reqtxt/preprocess.go | 55 +++++++++++++++++++++++++++++---------- reqtxt/preprocess_test.go | 40 ++++++++++++++++++++++++++++ 6 files changed, 153 insertions(+), 33 deletions(-) diff --git a/reqtxt/classify.go b/reqtxt/classify.go index e01547c..271a7ca 100644 --- a/reqtxt/classify.go +++ b/reqtxt/classify.go @@ -40,13 +40,14 @@ var archiveExtensions = []string{".tar.gz", ".tar.bz2", ".whl", ".tgz", ".tar", // filesystem-dependent fallback, so a bare name with no path/URL/archive // shape (e.g. "flask") always falls through to (_, false) here. func classifyTarget(tok string) (kind Kind, ok bool) { + lower := strings.ToLower(tok) + for _, prefix := range vcsSchemePrefixes { - if strings.HasPrefix(tok, prefix) { + if strings.HasPrefix(lower, prefix) { return KindVCS, true } } - lower := strings.ToLower(tok) for _, scheme := range urlSchemes { if strings.HasPrefix(lower, scheme) { return KindURL, true @@ -67,22 +68,23 @@ func classifyTarget(tok string) (kind Kind, ok bool) { return 0, false } -// eggName returns the value of a "#egg=" fragment on raw (pip's -// legacy way of naming a VCS/URL requirement whose distribution name -// can't otherwise be inferred; see pip's _egg_fragment in -// pip/_internal/req/constructors.py). It returns "" if raw has no such -// fragment. The fragment may be followed by additional "&"-separated -// fragment parameters (e.g. "&subdirectory=..."), which are not part of -// the returned name. +// eggName returns the value of an "egg=" fragment parameter on raw +// (pip's legacy way of naming a VCS/URL requirement whose distribution +// name can't otherwise be inferred; see pip's _egg_fragment in +// pip/_internal/req/constructors.py). It returns "" if raw has no +// fragment, or has a fragment with no "egg" parameter. The fragment +// (the part of raw after the first "#") is treated as "&"-separated +// "key=value" parameters, e.g. "#subdirectory=src&egg=name" - "egg" need +// not be the first parameter. func eggName(raw string) string { - const marker = "#egg=" - i := strings.Index(raw, marker) + i := strings.IndexByte(raw, '#') if i < 0 { return "" } - rest := raw[i+len(marker):] - if j := strings.IndexByte(rest, '&'); j >= 0 { - return rest[:j] + for _, param := range strings.Split(raw[i+1:], "&") { + if name, ok := strings.CutPrefix(param, "egg="); ok { + return name + } } - return rest + return "" } diff --git a/reqtxt/classify_test.go b/reqtxt/classify_test.go index 4d4fa58..e537db2 100644 --- a/reqtxt/classify_test.go +++ b/reqtxt/classify_test.go @@ -112,6 +112,12 @@ func TestClassifyTargetVCSSchemePrefixes(t *testing.T) { } } +func TestClassifyTargetVCSSchemePrefixCaseInsensitive(t *testing.T) { + kind, ok := classifyTarget("Git+https://h/p") + assert.True(t, ok, `expected "Git+https://h/p" to classify as VCS`) + assert.Equal(t, KindVCS.String(), kind.String(), `expected "Git+https://h/p" to be KindVCS`) +} + func TestClassifyTargetArchiveExtensions(t *testing.T) { for _, ext := range []string{".whl", ".tar.gz", ".tgz", ".tar.bz2", ".tar", ".zip"} { tok := "pkg-1.0" + ext @@ -142,6 +148,11 @@ func TestEggName(t *testing.T) { raw: "./x", want: "", }, + { + name: "vcs fragment with subdirectory before egg", + raw: "git+https://h/p#subdirectory=src&egg=name", + want: "name", + }, } for _, c := range cases { diff --git a/reqtxt/flatten.go b/reqtxt/flatten.go index 54d36cf..f506687 100644 --- a/reqtxt/flatten.go +++ b/reqtxt/flatten.go @@ -6,6 +6,7 @@ import ( "bytes" "errors" "fmt" + "net/url" "path" "regexp" "strings" @@ -132,13 +133,25 @@ func decodeUTF8(raw []byte) string { // the file at referencedFrom, into the path Flatten will pass to open. // An absolute path (leading "/") or a scheme-bearing reference (e.g. // "https://...", "file://...") is passed through verbatim - open decides -// how to fetch it. Otherwise, target is relative and is joined to -// referencedFrom's directory using slash-based (path package) semantics -// and cleaned, mirroring pip's os.path.join(os.path.dirname(filename), -// req_path) but OS-independent. +// how to fetch it. Otherwise, target is relative. If referencedFrom is +// itself a URL (scheme-bearing), target is resolved against it using +// net/url reference resolution (RFC 3986), since referencedFrom's +// "directory" isn't a filesystem path: slash-based path.Dir/path.Join +// would mangle the scheme (e.g. turning "https://host/reqs/root.txt" into +// "https:/host/reqs", collapsing the double slash). Otherwise target is +// joined to referencedFrom's directory using slash-based (path package) +// semantics and cleaned, mirroring pip's +// os.path.join(os.path.dirname(filename), req_path) but OS-independent. func resolveInclude(referencedFrom, target string) string { if strings.HasPrefix(target, "/") || schemeRE.MatchString(target) { return target } + if schemeRE.MatchString(referencedFrom) { + if base, err := url.Parse(referencedFrom); err == nil { + if rel, err := url.Parse(target); err == nil { + return base.ResolveReference(rel).String() + } + } + } return path.Clean(path.Join(path.Dir(referencedFrom), target)) } diff --git a/reqtxt/flatten_test.go b/reqtxt/flatten_test.go index acf3ca6..4f1c42e 100644 --- a/reqtxt/flatten_test.go +++ b/reqtxt/flatten_test.go @@ -98,6 +98,33 @@ func TestFlatten_URLIncludeVerbatim(t *testing.T) { assert.Contains(t, openedPaths, "https://h/x.txt") } +func TestFlatten_URLRelativeInclude(t *testing.T) { + // A relative include target nested inside a URL-hosted file must be + // resolved against that URL (net/url reference resolution), not with + // slash-based path.Dir/path.Join - which would collapse "https://" to + // "https:/", producing a broken path. + var openedPaths []string + base := mapOpener(map[string][]byte{ + "https://h/reqs/root.txt": []byte("-r more.txt\n"), + "https://h/reqs/more.txt": []byte("foo\n"), + }) + open := func(path string) ([]byte, error) { + openedPaths = append(openedPaths, path) + return base(path) + } + + f, err := Flatten("https://h/reqs/root.txt", open) + require.NoError(t, err) + require.Len(t, f.Entries, 1) + + re, ok := f.Entries[0].(*RequirementEntry) + require.True(t, ok, "want *RequirementEntry, got %T", f.Entries[0]) + assert.Equal(t, "foo", re.Requirement.Name) + + assert.Contains(t, openedPaths, "https://h/reqs/more.txt") + assert.NotContains(t, openedPaths, "https:/h/reqs/more.txt", "relative target must not be resolved with slash-based path semantics against a URL parent") +} + func TestFlatten_ConstraintPropagation(t *testing.T) { f, err := Flatten("root.txt", mapOpener(map[string][]byte{ "root.txt": []byte("-c constraints.txt\n-r r.txt\n"), diff --git a/reqtxt/preprocess.go b/reqtxt/preprocess.go index 5768efb..942566e 100644 --- a/reqtxt/preprocess.go +++ b/reqtxt/preprocess.go @@ -5,14 +5,38 @@ package reqtxt import ( "regexp" "strings" + "unicode" + "unicode/utf8" ) -// commentRE matches pip's COMMENT_RE (pip/_internal/req/req_file.py): -// "(^|\s+)#.*$". A '#' at the start of the line, or preceded by -// whitespace, begins a comment that runs to end-of-line. A '#' that is -// not whitespace-preceded (e.g. the fragment in -// "git+https://h/p#egg=name") is left alone. -var commentRE = regexp.MustCompile(`(^|\s+)#.*$`) +// commentStartIndex returns the byte index of the '#' that begins a +// comment in s, matching pip's COMMENT_RE (pip/_internal/req/req_file.py): +// "(^|\s+)#.*$". A '#' at the start of s, or immediately preceded by a +// rune for which unicode.IsSpace reports true, begins a comment that runs +// to the end of s. A '#' that is not whitespace-preceded (e.g. the +// fragment in "git+https://h/p#egg=name") is left alone. It returns -1 if +// s contains no comment-starting '#'. +// +// This is implemented as a manual scan rather than a regexp because +// Python's re module's "\s" (which pip's COMMENT_RE relies on) is +// Unicode-aware, while Go's RE2 "\s" is ASCII-only - a regexp built on Go's +// "\s" would miss a comment introduced after e.g. a non-breaking space, +// form feed, or vertical tab. +func commentStartIndex(s string) int { + for i, r := range s { + if r != '#' { + continue + } + if i == 0 { + return i + } + prev, _ := utf8.DecodeLastRuneInString(s[:i]) + if unicode.IsSpace(prev) { + return i + } + } + return -1 +} // envVarRE matches pip's ENV_VAR_RE (pip/_internal/req/req_file.py): // `\$\{([A-Z0-9_]+)\}`. Only the uppercase form is recognized; a @@ -77,7 +101,7 @@ type logicalLine struct { // INLINE comment ending in "\" (e.g. "django # c \") is unaffected and // still joins, matching pip: the guard only fires for a line that is a // comment in its entirety. -// 3. Strip comments per commentRE. +// 3. Strip comments per commentStartIndex. // 4. Drop logical lines that are empty or all-whitespace once comments // are stripped. // 5. Trim remaining surrounding whitespace. @@ -102,7 +126,10 @@ func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { } joining = false - text := commentRE.ReplaceAllString(joined.String(), "") + text := joined.String() + if i := commentStartIndex(text); i >= 0 { + text = text[:i] + } text = strings.TrimSpace(text) if text == "" { return @@ -138,13 +165,13 @@ func preprocess(content string, cfg parseConfig) ([]logicalLine, error) { } // isWholeLineComment reports whether physical is a whole-line comment: its -// first non-whitespace character is "#". This is pip's join_lines guard -// (COMMENT_RE.match(line), req_file.py:501) restated for our purposes: an -// INLINE comment (preceded by non-whitespace content, e.g. "django # c") -// does not match here and is not a whole-line comment, even though -// commentRE itself would still strip it later. +// first non-whitespace (per unicode.IsSpace) character is "#". This is +// pip's join_lines guard (COMMENT_RE.match(line), req_file.py:501) +// restated for our purposes: an INLINE comment (preceded by non-whitespace +// content, e.g. "django # c") does not match here and is not a whole-line +// comment, even though commentStartIndex would still strip it later. func isWholeLineComment(physical string) bool { - return strings.HasPrefix(strings.TrimLeft(physical, " \t"), "#") + return strings.HasPrefix(strings.TrimLeftFunc(physical, unicode.IsSpace), "#") } // normalizeLineEndings converts "\r\n" and lone "\r" to "\n", matching diff --git a/reqtxt/preprocess_test.go b/reqtxt/preprocess_test.go index 9f46ff4..e1387f3 100644 --- a/reqtxt/preprocess_test.go +++ b/reqtxt/preprocess_test.go @@ -110,6 +110,46 @@ func TestPreprocess_Comments(t *testing.T) { content: "git+https://h/p#egg=n", want: []logicalLine{{text: "git+https://h/p#egg=n", line: 1}}, }, + { + name: "inline comment preceded by a non-breaking space is stripped", + content: "foo # a comment", + want: []logicalLine{{text: "foo", line: 1}}, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := preprocess(c.content, parseConfig{}) + require.NoError(t, err) + assert.Equal(t, c.want, got) + }) + } +} + +// TestPreprocess_UnicodeWhitespaceWholeLineComment exercises the same +// join_lines guard as TestPreprocess_WholeLineCommentContinuationGuard, +// but with a whole-line comment led by Unicode (non-ASCII) whitespace - +// form feed and vertical tab - which Go's RE2 "\s" does not recognize but +// Python's (and thus pip's) "\s" does. Without Unicode-aware whole-line +// detection, the leading "#" would not be seen as starting at the first +// non-whitespace rune, the guard would not fire, and the trailing "\" +// would incorrectly join and swallow the next physical line. +func TestPreprocess_UnicodeWhitespaceWholeLineComment(t *testing.T) { + cases := []struct { + name string + content string + want []logicalLine + }{ + { + name: "form-feed-led whole-line comment ending in backslash does not swallow the next line", + content: "\f# c \\\nbar", + want: []logicalLine{{text: "bar", line: 2}}, + }, + { + name: "vertical-tab-led whole-line comment ending in backslash does not swallow the next line", + content: "\v# c \\\nbar", + want: []logicalLine{{text: "bar", line: 2}}, + }, } for _, c := range cases {