diff --git a/CHANGELOG.md b/CHANGELOG.md index 94ec656..409fa34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,42 @@ served it. ## [Unreleased] +### Breaking + +- `pyresolve`'s `--` now works. It never did, in any position: `reorderArgs` consumed the + terminator without re-emitting it, so `flag.Parse` — which does its own scan over the + reordered arguments, and for which `--` is the only stop token — never saw it. A package + named `--json` was parsed as the `--json` flag, and the command then exited **1** + ("usage or file error") reporting `expected exactly one package name argument, got []`, + blaming the caller for a name it had silently eaten. Listed as Breaking because arguments + after `--` are now taken literally, which is the documented behavior but not the previous + one. + +### Fixed + +- `RSFIndex.Metadata` and `RSFIndex.Files` reject an uninitialized (zero-value) + `version.Version` with an explicit error naming it as a caller bug, rather than reporting + `ErrMetadataUnavailable` — which blames the RSF for having no such version when the real + problem is the argument. Deliberately not a new sentinel: there is nothing to branch on, + only code to fix. + + This also closed a crash. Before `go-python-packaging` v0.3.1, `Version.String()` panicked + on a zero value, so `Metadata` died on `decoded[ver.String()]`. `Files` did *not*, because + `fmt` recovers a panic raised inside a `String` method and substitutes + `%!s(PANIC=...)` — so it returned a garbled but plausible-looking error. The bump alone + would have converted the crash into a silent wrong answer; the guard is what keeps it + diagnosable. + +### Changed + +- Requires `go-python-packaging` **v0.3.1** (from v0.3.0), for the zero-value `Version` + fixes above. +- Documented why `walk`'s `ErrMetadataUnavailable` branch is unreachable and kept. It is + unreachable only for `RSFIndex`, whose `Versions`/`Metadata` agreement is a tested + invariant; the `MetadataIndex` contract permits that error for a known sdist-only release + and `MockIndex` already returns it, so deleting the branch would trade dead code for a + latent gap that reappears the moment the command is generalized to the interface. + ## [0.1.0] - 2026-08-07 First release. **Read what is not in it before depending on it.** diff --git a/cmd/pyresolve/common.go b/cmd/pyresolve/common.go index 52c4ef7..79280ff 100644 --- a/cmd/pyresolve/common.go +++ b/cmd/pyresolve/common.go @@ -98,6 +98,20 @@ func newFlagSet(name string) (*flag.FlagSet, *globalFlags) { // // "--" ends flag scanning early, matching flag.Parse's own convention: every // token after it is treated as positional without inspection. +// +// ⚠️ The "--" token is RE-EMITTED, not swallowed. Stopping our own scan is only +// half the job: flag.Parse does its own scan over whatever we return, and "--" +// is the only thing that stops it (flag/flag.go: `if len(s) == 2` terminates the +// flags). Dropping the token therefore un-protected exactly the arguments it was +// written to protect -- `versions -- --json` came back as ["--json"], which +// flag.Parse read as the --json flag, leaving zero positional arguments and +// reporting "expected exactly one package name argument, got []" about a package +// legitimately named "--json". +// +// It never worked in any position, because positional always follows flagArgs in +// the returned slice: `versions pkg -- --json` came back as ["pkg", "--json"], +// where flag.Parse stops at the non-flag "pkg" and hands back two positional +// arguments instead of one. func reorderArgs(fs *flag.FlagSet, args []string) []string { var flagArgs, positional []string @@ -105,7 +119,10 @@ func reorderArgs(fs *flag.FlagSet, args []string) []string { a := args[i] if a == "--" { - positional = append(positional, args[i+1:]...) + // Keep the terminator at the head of the positional run so it + // survives into fs.Parse, which is what actually protects the + // tokens after it. + positional = append(positional, args[i:]...) break } diff --git a/cmd/pyresolve/reorder_test.go b/cmd/pyresolve/reorder_test.go index a900f51..cddd99d 100644 --- a/cmd/pyresolve/reorder_test.go +++ b/cmd/pyresolve/reorder_test.go @@ -5,6 +5,7 @@ package main import ( "bytes" "reflect" + "strings" "testing" ) @@ -44,11 +45,29 @@ func TestReorderArgsEqualsForm(t *testing.T) { } } +// The "--" terminator must survive into the returned slice. This test +// previously asserted the opposite -- want was []string{"pkg", "--json"}, the +// terminator-stripped output -- which pinned the bug rather than the behavior: +// fs.Parse does its own scan over whatever reorderArgs returns, and "--" is the +// only token that stops it, so dropping it un-protected exactly the arguments +// the terminator exists to protect. func TestReorderArgsDoubleDashStopsScanning(t *testing.T) { fs, _ := newFlagSet("versions") got := reorderArgs(fs, []string{"pkg", "--", "--json"}) - want := []string{"pkg", "--json"} + want := []string{"pkg", "--", "--json"} + if !reflect.DeepEqual(got, want) { + t.Errorf("reorderArgs = %v, want %v", got, want) + } +} + +func TestReorderArgsDoubleDashBeforePositional(t *testing.T) { + fs, _ := newFlagSet("versions") + + // A real flag ahead of the terminator still gets hoisted; everything from + // "--" onward is positional and keeps its order. + got := reorderArgs(fs, []string{"--json", "--", "-weird-package"}) + want := []string{"--json", "--", "-weird-package"} if !reflect.DeepEqual(got, want) { t.Errorf("reorderArgs = %v, want %v", got, want) } @@ -65,3 +84,46 @@ func TestRunWalkAcceptsFlagAfterPositional(t *testing.T) { t.Fatalf("exit code = %d, want 0; stderr:\n%s", code, stderr.String()) } } + +// The unit tests above cover reorderArgs in isolation, but the terminator's +// whole purpose is end-to-end: it must reach fs.Parse. There was no test at this +// level, which is how a reorderArgs test asserting the stripped output could +// pass while "--" did not work in any position. +// +// A package literally named "--json" is not in the fixture, so the right answer +// is exit 2, "package not found". Before the fix, "--json" was consumed as the +// --json flag, leaving no positional argument, and the command exited 1 with +// "expected exactly one package name argument, got []" -- blaming the caller for +// a name it had silently eaten. +func TestRunDoubleDashProtectsDashLeadingPackageName(t *testing.T) { + path := standardFixture(t) + + var stdout, stderr bytes.Buffer + code := run([]string{"versions", "--rsf", path, "--", "--json"}, &stdout, &stderr) + + if code == 1 { + t.Fatalf("exit code = 1 (usage error): the terminator did not protect the "+ + "argument, so %q was parsed as a flag; stderr:\n%s", "--json", stderr.String()) + } + if code != 2 { + t.Fatalf("exit code = %d, want 2 (package not found); stderr:\n%s", code, stderr.String()) + } + if !strings.Contains(stderr.String(), "--json") { + t.Errorf("error should name the package it looked for, got:\n%s", stderr.String()) + } +} + +// The same, with a real flag present, to prove the terminator does not disable +// legitimate flag parsing ahead of it. +func TestRunDoubleDashCoexistsWithFlags(t *testing.T) { + path := standardFixture(t) + + var stdout, stderr bytes.Buffer + code := run([]string{"versions", "--rsf", path, "--json", "--", "flask"}, &stdout, &stderr) + if code != 0 { + t.Fatalf("exit code = %d, want 0; stderr:\n%s", code, stderr.String()) + } + if !strings.HasPrefix(strings.TrimSpace(stdout.String()), "{") { + t.Errorf("--json before the terminator should still take effect, got:\n%s", stdout.String()) + } +} diff --git a/cmd/pyresolve/walk.go b/cmd/pyresolve/walk.go index d76e1f9..e25138f 100644 --- a/cmd/pyresolve/walk.go +++ b/cmd/pyresolve/walk.go @@ -188,6 +188,29 @@ func walkCmd(w io.Writer, path string, jsonOut bool, rootArg string, maxDepth in // The package and version exist, but this version's metadata // was not captured — same practical outcome as no versions at // all, and equally not an absent package. + // + // ⚠️ THIS BRANCH IS UNREACHABLE TODAY, AND IS KEPT DELIBERATELY. + // Mutation testing across 8 real walks could not reach it, which + // looks like dead code worth deleting. It is not: + // + // - It is unreachable only for *index.RSFIndex, which is the + // concrete type this command holds. RSFIndex builds Versions + // and Metadata from the same decoded map, and selectHighest + // only ever returns a member of what Versions just returned, + // so Metadata always finds a record. index/dedupe_test.go's + // TestVersionsAndMetadataAgreeOnEveryVersion pins exactly + // that invariant, so this is a guaranteed property of one + // implementation rather than an accident. + // - The MetadataIndex CONTRACT (index/index.go) permits + // ErrMetadataUnavailable for a known version whose metadata + // would need a build (sdist-only), and index.MockIndex + // already returns it. Any index that is not backed purely by + // an RSF -- a JSON or DB index -- will reach this. + // + // So deleting it would trade dead code for a latent gap that + // reappears the moment walkCmd is generalized to the interface, + // and the failure would be a silently wrong walk rather than a + // compile error. noDeps = append(noDeps, item.name) continue } diff --git a/go.mod b/go.mod index 8e3e2c2..f4618a9 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.25.0 require ( github.com/klauspost/compress v1.19.1 - github.com/posit-dev/go-python-packaging v0.3.0 + github.com/posit-dev/go-python-packaging v0.3.1 github.com/rstudio/repository-snapshot-format v0.12.0 ) diff --git a/go.sum b/go.sum index 24461b4..8731204 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,8 @@ github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJn github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posit-dev/go-python-packaging v0.3.0 h1:JGGslJqxOd5i6eRLDr8crIPXVuCMWTEloYPqcONEsqM= -github.com/posit-dev/go-python-packaging v0.3.0/go.mod h1:NkELXOh/eRDT7c+LKFxJd+HkyGpKFsUIxpTYaq5xdkU= +github.com/posit-dev/go-python-packaging v0.3.1 h1:0iFrlgqg/DdE3wo7SKBjAATG11hq9PsHq2/6B4dzo2c= +github.com/posit-dev/go-python-packaging v0.3.1/go.mod h1:NkELXOh/eRDT7c+LKFxJd+HkyGpKFsUIxpTYaq5xdkU= github.com/rstudio/go-version v0.0.2 h1:ihU0xaF+Yuya0p2J6C8dfyB4gu/YehM1d6cTpabf/7A= github.com/rstudio/go-version v0.0.2/go.mod h1:Xfuma+m4R9L0P+Hof8iDDiL4/TJ8VjpdDXWq8qGXHL4= github.com/rstudio/repository-snapshot-format v0.12.0 h1:a6gRfXPLOR+5YxN7irO097lpWGOPMe8ZoATGkC9hcWE= diff --git a/index/rsfindex.go b/index/rsfindex.go index aa2e296..7193c4a 100644 --- a/index/rsfindex.go +++ b/index/rsfindex.go @@ -273,6 +273,10 @@ func (idx *RSFIndex) Metadata(ctx context.Context, pkg PackageName, ver version. return PackageMetadata{}, err } + if err := checkVersionInitialized("Metadata", pkg, ver); err != nil { + return PackageMetadata{}, err + } + decoded, err := idx.deps(pkg) if err != nil { return PackageMetadata{}, err @@ -411,10 +415,40 @@ func (idx *RSFIndex) Metadata(ctx context.Context, pkg PackageName, ver version. // yanked flag, so there is nothing to report. This is the data's shape, not a // missing feature. func (idx *RSFIndex) Files(_ context.Context, pkg PackageName, ver version.Version) ([]DistFile, error) { + if err := checkVersionInitialized("Files", pkg, ver); err != nil { + return nil, err + } return nil, fmt.Errorf("index %q: %q %s: an RSF carries dependency metadata only: %w", idx.origin, pkg, ver, ErrFilesUnavailable) } +// checkVersionInitialized rejects an uninitialized version.Version. +// +// This is a CALLER BUG, not a state of the data, so it is deliberately not one +// of the four sentinels: there is nothing to branch on, only code to fix. Left +// unguarded it would collapse into ErrMetadataUnavailable -- "no metadata for +// that version" -- which blames the RSF for the caller passing a zero value, the +// same class of state collapse this package has already had to fix four times. +// +// The empty rendering is a sound test because go-python-packaging guarantees no +// version Parse accepts renders as "" (the PEP 440 grammar requires a release +// segment, and gpp asserts this), so "" means an uninitialized Version and +// nothing else. +// +// ⚠️ Before gpp v0.3.1 this could not even be checked this way: Version.String() +// PANICKED on a zero value rather than returning "". Metadata crashed on +// decoded[ver.String()], while Files looked healthy because fmt recovers a panic +// raised inside a String method and substitutes "%!s(PANIC=...)" -- which is why +// rstudio/package-manager#19466's F14 reported this against Files, the one call +// site that did not crash. +func checkVersionInitialized(method string, pkg PackageName, ver version.Version) error { + if ver.String() != "" { + return nil + } + return fmt.Errorf("%s(%q): version is uninitialized (the zero value); "+ + "pass a version obtained from Versions or version.Parse", method, pkg) +} + // Len reports how many packages the underlying file carries. func (idx *RSFIndex) Len() int { return idx.file.Len() } diff --git a/index/zero_version_test.go b/index/zero_version_test.go new file mode 100644 index 0000000..4bc1d3b --- /dev/null +++ b/index/zero_version_test.go @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package index + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/posit-dev/go-python-packaging/version" +) + +// An uninitialized version.Version reaching Metadata used to PANIC on +// decoded[ver.String()]. With go-python-packaging v0.3.1 it no longer panics, +// but it would then silently degrade into ErrMetadataUnavailable -- "the RSF has +// no metadata for that version" -- which blames the data for a caller passing a +// zero value. Both outcomes are wrong; this pins the third. +func TestMetadataRejectsUninitializedVersion(t *testing.T) { + idx := openFixtureIndex(t) + + _, err := idx.Metadata(context.Background(), NewPackageName("flask"), version.Version{}) + if err == nil { + t.Fatal("expected an error for an uninitialized version") + } + if !strings.Contains(err.Error(), "uninitialized") { + t.Errorf("error should say the version is uninitialized, got: %v", err) + } + + // ⚠️ Explicitly NOT one of the data-state sentinels. A caller bug must not + // be mistakable for a fact about the RSF, which is the state-collapse class + // this package has already had to fix four times. + for name, sentinel := range map[string]error{ + "ErrMetadataUnavailable": ErrMetadataUnavailable, + "ErrMetadataUnusable": ErrMetadataUnusable, + "ErrPackageNotFound": ErrPackageNotFound, + "ErrFilesUnavailable": ErrFilesUnavailable, + } { + if errors.Is(err, sentinel) { + t.Errorf("uninitialized-version error must not satisfy %s: %v", name, err) + } + } +} + +func TestFilesRejectsUninitializedVersion(t *testing.T) { + idx := openFixtureIndex(t) + + _, err := idx.Files(context.Background(), NewPackageName("flask"), version.Version{}) + if err == nil { + t.Fatal("expected an error for an uninitialized version") + } + if !strings.Contains(err.Error(), "uninitialized") { + t.Errorf("error should say the version is uninitialized, got: %v", err) + } + // ⚠️ Files previously returned an ErrFilesUnavailable whose message embedded + // a RECOVERED panic -- "%!s(PANIC=String method: index out of range...)" -- + // because fmt catches panics raised inside a String method. It looked + // healthy, which is why the original finding named Files rather than + // Metadata. Assert the message is clean. + if strings.Contains(err.Error(), "PANIC") { + t.Errorf("error message embeds a recovered panic: %v", err) + } +} + +// A real version must still reach the normal paths, so the guard cannot be +// over-broad. +func TestInitializedVersionStillWorks(t *testing.T) { + idx := openFixtureIndex(t) + ctx := context.Background() + + meta, err := idx.Metadata(ctx, NewPackageName("flask"), mustVersion(t, "3.0.0")) + if err != nil { + t.Fatalf("Metadata with a real version: %v", err) + } + if meta.Version.String() != "3.0.0" { + t.Errorf("Version = %q, want 3.0.0", meta.Version) + } + + _, err = idx.Files(ctx, NewPackageName("flask"), mustVersion(t, "3.0.0")) + if !errors.Is(err, ErrFilesUnavailable) { + t.Errorf("Files with a real version should be ErrFilesUnavailable, got: %v", err) + } +}