Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
90 changes: 90 additions & 0 deletions reqtxt/classify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT

package reqtxt

import "strings"

// vcsSchemePrefixes are the "<vcs>+" 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) {
lower := strings.ToLower(tok)

for _, prefix := range vcsSchemePrefixes {
if strings.HasPrefix(lower, prefix) {
return KindVCS, true
}
}

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 an "egg=<name>" 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 {
i := strings.IndexByte(raw, '#')
if i < 0 {
return ""
}
for _, param := range strings.Split(raw[i+1:], "&") {
if name, ok := strings.CutPrefix(param, "egg="); ok {
return name
}
}
return ""
}
163 changes: 163 additions & 0 deletions reqtxt/classify_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// 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 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
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: "",
},
{
name: "vcs fragment with subdirectory before egg",
raw: "git+https://h/p#subdirectory=src&egg=name",
want: "name",
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
assert.Equal(t, c.want, eggName(c.raw))
})
}
}
21 changes: 19 additions & 2 deletions reqtxt/doc.go
Original file line number Diff line number Diff line change
@@ -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
Loading