diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 209278a1fb..9e4c5503cf 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2020,7 +2020,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked patched platform gem per locked platform, `-//`, each from that platform's own patch and with its gemspec, under the `` of the fix's source patch (the ruby gem's), plus `/.gitignore` (`!*`: re-includes the prebuilt binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a prebuilt platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems of one fix. Each platform gem has a patch of its own (record `pkg:gem/@?platform=`, artifacts `tarball` and `gem-stub-gemspec`, `rebuiltFromUuid` naming the patch of the ruby gem), and the gem is vendored as ONE unit led by that source patch: the vendored dir and the ledger entry carry the source patch's uuid (so the dir does not move when the lock's platforms change). Where the source patch is not among the run's records the unit is led by the patch of the first locked platform instead, and a gem already vendored keeps the lead its ledger entry names while that patch is still one of them, so a copy that works is not moved when the source patch turns up. Whichever leads, the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. The ledger entry records each tree in `gemBuilds`: `{platform, uuid, gemIntegrity, gemspecIntegrity, record}`, the platform's own patch uuid, the sha512 of the `.gem` and of the stub gemspec it was unpacked from, and that patch's record. Events: as in hosted mode, the gem's outcome (`applied`, `skipped` / `already_vendored`, a skip or a failure) is one event per platform gem that has a patch (`purl` with its `platform` qualifier, its own `uuid`), each counted in `summary`, with `details.gemFix` (the uuid of the patch the gem is vendored through) tying the events of one gem together; the human lines and the vendored count of telemetry take the gem as one package. The patch the gem is vendored through has an event of its own only when no platform gem has a patch. `vendor --check` reports its verdict per platform gem the same way. Every locked platform needs a usable patch of the same fix: while one has none the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A re-run of a copy whose locked platforms no longer all have a patch, while the committed trees still match the ledger, keeps the copy and reports `vendor_gem_builds_kept`; a lock that gained a platform entry under the vendored `PATH` section gets that platform's tree added in the same directory. An entry an earlier development build wrote names the platforms alone (`gemPlatforms`, read-only): it still verifies against its one patch, is attested by it, reverts byte for byte, is kept (`vendor_gem_builds_kept`) while the platforms have no patch, and is rebuilt in place from the per-platform patches, with `gemBuilds` recorded, by the first run that has one for every locked platform. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked patched platform gem per locked platform, `-//`, each from that platform's own patch and with its gemspec, under the `` of the fix's source patch (the ruby gem's). Either way, plus `/.gitignore` (`!*`: re-includes the files of the copy against the project's ignores, such as the `.rspec` rule of GitHub's `Rails.gitignore`, or a `*.so` or `*.bundle` rule over prebuilt binaries) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule, or a line-ending conversion, does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing, which is also how a copy that 5.1 or earlier vendored without the pair gets it. A `.gitignore` the patched gem ships inside its own tree would hide files below the uuid dir's `!*`, so it is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept): every one in a platform gem's tree, and in a gem's own tree each one whose rules match a file of the copy (a `.gitignore` that hides nothing, such as a template the gem copies into new projects, is kept byte for byte). `repair` restores each as the ledger's inventory records it, so a copy that 5.1 or earlier vendored with the gem's `.gitignore` as shipped comes back that way; the in-sync run that writes the pair for such a copy warns `vendor_gem_copy_gitignored` when git would still leave a file of it out. Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems of one fix. Each platform gem has a patch of its own (record `pkg:gem/@?platform=`, artifacts `tarball` and `gem-stub-gemspec`, `rebuiltFromUuid` naming the patch of the ruby gem), and the gem is vendored as ONE unit led by that source patch: the vendored dir and the ledger entry carry the source patch's uuid (so the dir does not move when the lock's platforms change). Where the source patch is not among the run's records the unit is led by the patch of the first locked platform instead, and a gem already vendored keeps the lead its ledger entry names while that patch is still one of them, so a copy that works is not moved when the source patch turns up. Whichever leads, the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform; EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. The ledger entry records each tree in `gemBuilds`: `{platform, uuid, gemIntegrity, gemspecIntegrity, record}`, the platform's own patch uuid, the sha512 of the `.gem` and of the stub gemspec it was unpacked from, and that patch's record. Events: as in hosted mode, the gem's outcome (`applied`, `skipped` / `already_vendored`, a skip or a failure) is one event per platform gem that has a patch (`purl` with its `platform` qualifier, its own `uuid`), each counted in `summary`, with `details.gemFix` (the uuid of the patch the gem is vendored through) tying the events of one gem together; the human lines and the vendored count of telemetry take the gem as one package. The patch the gem is vendored through has an event of its own only when no platform gem has a patch. `vendor --check` reports its verdict per platform gem the same way. Every locked platform needs a usable patch of the same fix: while one has none the gem is skipped (`vendor_prebuilt_platform_pending`, no failure) with nothing written. A re-run of a copy whose locked platforms no longer all have a patch, while the committed trees still match the ledger, keeps the copy and reports `vendor_gem_builds_kept`; a lock that gained a platform entry under the vendored `PATH` section gets that platform's tree added in the same directory. An entry an earlier development build wrote names the platforms alone (`gemPlatforms`, read-only): it still verifies against its one patch, is attested by it, reverts byte for byte, is kept (`vendor_gem_builds_kept`) while the platforms have no patch, and is rebuilt in place from the per-platform patches, with `gemBuilds` recorded, by the first run that has one for every locked platform. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no prebuilt tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2910,8 +2910,9 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | -| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | +| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel, or a file of a gem's copy, still reads as ignored, the run refuses and removes the uuid dir it created. | +| `vendor_gem_copy_gitignored` | warning | vendor (a gem vendored as its own directory by 5.1 or earlier): the in-sync run that writes the missing `/.gitignore` and `.gitattributes` asks git about every file of the copy, and a `.gitignore` the gem ships, which that release kept as shipped, still keeps a file out of the commit (the detail names the rule and the file), so a fresh clone would fail `vendor --check` with `vendor_inventory_mismatch`. The copy and the ledger are left as they are. Remedy: `git add -f ` and commit. Said once, by the run that writes the pair. | +| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet, every PyPI flavor and gems): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | | `vendor_variant_ambiguous` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): the package is not installed and the manifest holds several release variants of it (`?artifact_id=` / `?platform=`), none of which the vendor ledger records, so nothing says which distribution to vendor; install the package or keep one release variant. A variant the ledger records (at any patch uuid) is taken as the wired one and its siblings are left out without an event. | diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 5f19fb83fa..4a2056dd77 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -510,16 +510,18 @@ impl VendoredBackend<'_> { entry }; let health = check_vendored_artifact(&common.cwd, &entry, &record).await; - // An npm-family `/.gitignore` and `.gitattributes` are not - // part of the artifact: a missing, edited or older one is - // simply rewritten, and git must still commit the artifact with - // them. A broken artifact gets both after its redownload. + // An npm-family or gem `/.gitignore` and `.gitattributes` + // are not part of the artifact: a missing, edited or older one + // is simply rewritten, and git must still commit the artifact + // with them. A broken artifact gets both after its redownload. if !common.dry_run && (health == ArtifactHealth::Healthy || health.is_workspace_copy_issue()) { - if let Err(e) = - vendor::redownload::restore_npm_uuid_metadata(&entry, &common.cwd).await - { + let metadata = async { + vendor::redownload::restore_npm_uuid_metadata(&entry, &common.cwd).await?; + vendor::redownload::restore_gem_uuid_metadata(&entry, &common.cwd).await + }; + if let Err(e) = metadata.await { fail( env, common.json, diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index b0dbb2aa2b..79487a8799 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -4121,6 +4121,198 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert!(!proj.join(".socket/vendor").exists()); } +// ── a vendored gem dir through a real commit and clone (#2348) ──────── + +/// `git ` in `cwd`, with an identity of its own and the machine's +/// git config kept out; panics on failure. +fn git(cwd: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(cwd) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .args(["-c", "user.name=e2e", "-c", "user.email=e2e@example.com"]) + .args([ + "-c", + "init.defaultBranch=main", + "-c", + "protocol.file.allow=always", + ]) + .args(args) + .output() + .expect("failed to run git"); + assert!( + out.status.success(), + "git {args:?} failed:\n{}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +/// A project whose `.gitignore` has a rule that matches a file the gem +/// ships: diff-lcs 1.5.1 ships `.rspec`, which GitHub's stock +/// `Rails.gitignore` names. The vendoring checkout holds the file either +/// way, so the proof is a real `git commit` and `git clone`: the clone +/// holds the whole copy, `vendor --check` passes there as it does in the +/// checkout that vendored, and a frozen `bundle install` loads the patched +/// gem. +#[test] +#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +fn gem_vendor_file_a_project_rule_ignores_reaches_a_git_clone() { + const GEM: &str = "diff-lcs"; + const VERSION: &str = "1.5.1"; + const RB: &str = "lib/diff/lcs.rb"; + // Lines of GitHub's `Rails.gitignore`, and the gem home of this test. + const RULES: &str = "*.rbc\n.rspec\n/log/*\n/coverage/\n/vendor/bundle\n"; + let Some(bundler) = gate("gitignored-file") else { + return; + }; + if Command::new("git").arg("--version").output().is_err() { + println!("SKIP e2e_vendor_gem_build: no git on PATH"); + return; + } + + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\n\ngem \"{GEM}\", \"{VERSION}\"\n"), + ) + .unwrap(); + let path_config = argv(&bundler.config_local_args("path", "vendor/bundle")) + .iter() + .map(|arg| arg.to_string()) + .collect::>(); + let config = bundle(&proj, &argv(&path_config), false); + let install = bundle(&proj, &["install"], false); + if !config.status.success() || !install.status.success() { + println!( + "SKIP e2e_vendor_gem_build: could not install {GEM} {VERSION} (registry \ + unreachable?):\n{}", + String::from_utf8_lossy(&install.stderr) + ); + return; + } + git(&proj, &["init", "-q"]); + std::fs::write(proj.join(".gitignore"), RULES).unwrap(); + + let mut ruby = Command::new("ruby"); + ruby.args(["-e", "puts Gem.ruby_api_version"]); + cache_env::isolate(&mut ruby); + let api = ruby.output().expect("failed to run ruby"); + let api = String::from_utf8_lossy(&api.stdout).trim().to_string(); + let gem_dir = proj + .join("vendor/bundle/ruby") + .join(&api) + .join("gems") + .join(format!("{GEM}-{VERSION}")); + assert!( + gem_dir.join(".rspec").is_file(), + "{GEM} {VERSION} ships .rspec (test premise)" + ); + let orig = std::fs::read(gem_dir.join(RB)).expect("the installed file"); + let marker = format!( + "\nmodule Diff\n module LCS\n SOCKET_PATCH_VENDOR_E2E = \"{UUID}\"\n end\nend\n" + ); + let patched: Vec = [orig.as_slice(), marker.as_bytes()].concat(); + let purl = format!("pkg:gem/{GEM}@{VERSION}"); + stage_patch_with_vuln(&proj, &purl, RB, &orig, &patched); + + let cwd = proj.to_str().unwrap(); + let (code, stdout, stderr) = + run_socket(&proj, &["vendor", "--json", "--offline", "--cwd", cwd]); + assert_eq!( + code, 0, + "vendor failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["summary"]["applied"], 1, "one package vendored: {env}"); + + // What the vendoring checkout says: every file of the copy is one git + // commits, and the check passes. + let uuid_dir = format!(".socket/vendor/gem/{UUID}"); + let copy_rel = format!("{uuid_dir}/{GEM}-{VERSION}"); + assert_eq!( + std::fs::read_to_string(proj.join(&uuid_dir).join(".gitignore")).unwrap(), + "!*\n" + ); + assert!(proj.join(&uuid_dir).join(".gitattributes").is_file()); + let ignored = git(&proj, &["status", "--short", "--ignored", "--", ".socket"]); + assert!( + !ignored.lines().any(|line| line.starts_with("!!")), + "git ignores files under .socket/:\n{ignored}" + ); + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + assert_eq!( + code, 0, + "check in the vendoring checkout:\n{stdout}\n{stderr}" + ); + + // Commit what the next steps name and clone it. + git(&proj, &["add", "-A"]); + git(&proj, &["commit", "-q", "-m", "vendor"]); + let clone = tmp.path().join("clone"); + git(tmp.path(), &["clone", "-q", cwd, clone.to_str().unwrap()]); + assert!( + !clone.join("vendor").exists(), + "the clone must not carry an installed tree (test bug)" + ); + assert!( + clone.join(©_rel).join(".rspec").is_file(), + "the clone lost the file the project's rule matches" + ); + + let clone_cwd = clone.to_str().unwrap(); + let (code, stdout, stderr) = run_socket(&clone, &["vendor", "--check", "--cwd", clone_cwd]); + assert_eq!( + code, 0, + "vendor --check must pass in a fresh clone.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert!( + !format!("{stdout}{stderr}").contains("vendor_inventory_mismatch"), + "{stdout}\n{stderr}" + ); + + // The clone installs frozen from the vendored path and loads the + // patched file. + let config = bundle(&clone, &argv(&path_config), false); + assert!(config.status.success(), "bundle config in the clone"); + let lock_committed = std::fs::read(clone.join("Gemfile.lock")).unwrap(); + let ci = bundle(&clone, &["install"], true); + assert!( + ci.status.success(), + "frozen `bundle install` in the clone.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&ci.stdout), + String::from_utf8_lossy(&ci.stderr) + ); + assert_eq!( + std::fs::read(clone.join("Gemfile.lock")).unwrap(), + lock_committed + ); + let probe = bundle( + &clone, + &[ + "exec", + "ruby", + "-e", + "require \"diff/lcs\"\nputs Diff::LCS::SOCKET_PATCH_VENDOR_E2E\n\ + puts $LOADED_FEATURES.grep(%r{/diff/lcs\\.rb\\z})", + ], + false, + ); + let probe_out = String::from_utf8_lossy(&probe.stdout).into_owned(); + assert!( + probe.status.success() && probe_out.contains(UUID), + "the clone must load the patched gem.\nstdout:\n{probe_out}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stderr) + ); + assert!( + probe_out.contains(&format!("{copy_rel}/{RB}")), + "loaded from the vendored path:\n{probe_out}" + ); +} + /// #2435: a gem vendored as platform gems without the patch of the ruby /// gem (not offered to the run) is vendored through the patch of the first /// platform the lock names, whose uuid names its directory. When that diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index c2f4373daa..f8652d9392 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -848,8 +848,10 @@ async fn gem_prelude( // ignores the dir itself (`.socket/`) cannot be overridden from inside // it, so the commit would drop the trees the lock names: refused here, // dry run or not, before anything is downloaded. Rules that ignore - // single files are for [`keep_platform_trees_committable`], once the - // trees are known. + // single files are for [`keep_copy_committable`], once the trees are + // known. (A gem vendored as its own tree is asked the same in + // [`vendor_gem_builds`], once a gem committed as its archive for a + // Bazel hub, which has a check of its own, is out of the way.) let in_sync = lock_wired && copy_ok; if !locked.platforms.is_empty() && !in_sync { if let Some((code, detail)) = @@ -1293,6 +1295,20 @@ pub async fn vendor_gem_builds<'a>( (copy_rel.as_str(), uuid_dir.as_path(), copy_dir.as_path()); let (lock_wired, copy_ok) = (*lock_wired, *copy_ok); + // ── a copy git would not commit ─────────────────────────────────────── + // The check `gem_prelude` makes for platform gems, for a gem vendored + // as its own tree (#2348): short of the in-sync no-op, a rule that + // ignores the uuid dir itself refuses the gem, dry run or not, before + // anything is downloaded. + if platforms.is_empty() && !(lock_wired && copy_ok) { + let uuid_dir_rel = copy_rel.rsplit_once('/').map_or(copy_rel, |(dir, _)| dir); + if let Some((code, detail)) = + super::npm_dir::ignored_root_refusal(project_root, uuid_dir_rel).await + { + return refused(code, detail); + } + } + // ── idempotent hot path ────────────────────────────────────────────── // Copy (incl. the gemspec) already carries every afterHash and both files // already reference the uuid path → touch nothing. `entry` stays `None`: @@ -1301,19 +1317,30 @@ pub async fn vendor_gem_builds<'a>( if lock_wired { if copy_ok { // The uuid dir's `.gitignore` / `.gitattributes` are not part - // of the copy: one that was deleted (or never written) is put - // back, or a project `*.so` rule drops the binaries from the - // next commit. + // of the copy: one that was deleted (or never written, by a + // release that gave a gem's own tree none) is put back, or a + // project rule (`*.so`, `.rspec`) drops files of the copy from + // the next commit. let mut warnings: Vec = Vec::new(); - if !platforms.is_empty() && !dry_run { - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - warnings.push(VendorWarning::new( + if !dry_run { + match restore_uuid_metadata(uuid_dir).await { + // The pair was missing: a copy of the gem's own tree + // that an earlier release vendored may still hold a + // `.gitignore` the gem ships, which the pair does not + // override. Said once, with the run that writes it. + Ok(true) if platforms.is_empty() => { + if let Some(warning) = shipped_rules_warning(project_root, copy_rel).await { + warnings.push(warning); + } + } + Ok(_) => {} + Err(e) => warnings.push(VendorWarning::new( super::npm_dir::GITIGNORE_UNCHECKED, super::npm_dir::gitignore_unchecked_detail( copy_rel, &format!("cannot write the vendored dir's git metadata: {e}"), ), - )); + )), } } if *builds_kept { @@ -1464,27 +1491,23 @@ pub async fn vendor_gem_builds<'a>( } result.package_path = copy_dir.display().to_string(); - // ── prebuilt trees git would not commit ────────────────────────────── + // ── files of the copy git would not commit ─────────────────────────── // Asked before either project file is written (see - // `keep_platform_trees_committable`). The inventory taken for it is - // the entry's, below. - let mut platform_inventory = None; - if !platforms.is_empty() { - let inventory = - inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; - if let Err(refusal) = keep_platform_trees_committable( - project_root, - copy_rel, - inventory.as_ref(), - &mut warnings, - ) - .await - { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - return refusal; - } - platform_inventory = Some(inventory); + // `keep_copy_committable`). The inventory taken for it is the entry's, + // below. + let file_inventory = + inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; + if let Err(refusal) = keep_copy_committable( + project_root, + copy_rel, + file_inventory.as_ref(), + &mut warnings, + ) + .await + { + let _ = remove_tree(uuid_dir).await; + prune_empty_vendor_levels(uuid_dir).await; + return refusal; } // ── Gemfile edit ───────────────────────────────────────────────────── @@ -1625,10 +1648,6 @@ pub async fn vendor_gem_builds<'a>( // The whole tree, stub gemspec included: no lockfile integrity covers a // path source's bytes. - let file_inventory = match platform_inventory { - Some(inventory) => inventory, - None => inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await, - }; let entry = gem_entry( base_purl, record, @@ -1740,7 +1759,13 @@ async fn gem_service_archive( } /// [`gem_service_archive`], then atomically replace the copy with the -/// unpacked gem and its stub gemspec. +/// unpacked gem and its stub gemspec. A `.gitignore` the gem ships whose +/// rules hide a file of the copy is emptied in it +/// ([`empty_shipped_gitignores`]). `recorded` is the ledger inventory of +/// the copy being restored, for `repair`: each `.gitignore` it names is +/// restored as it records it, so a copy an earlier release vendored comes +/// back as that release wrote it. +#[allow(clippy::too_many_arguments)] pub(super) async fn gem_service_copy( service: Option<&VendorServiceConfig>, record: &PatchRecord, @@ -1748,6 +1773,7 @@ pub(super) async fn gem_service_copy( copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, + recorded: Option<&std::collections::BTreeMap>, warnings: &mut Vec, ) -> Result<(), Box> { let (mut archive, stub) = gem_service_archive(service, record, name).await?; @@ -1794,6 +1820,17 @@ pub(super) async fn gem_service_copy( (patched files absent at their recorded paths)" ))); } + let which = Shipped::Hiding { recorded }; + let emptied = match empty_shipped_gitignores(&stage, &record.files, which).await { + Ok(emptied) => emptied, + Err(e) => { + cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + return Err(policy.hard( + "vendor_prebuilt_write_failed", + format!("cannot empty a `.gitignore` the patched gem for {name} ships: {e}"), + )); + } + }; if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; return Err(policy.hard( @@ -1802,6 +1839,17 @@ pub(super) async fn gem_service_copy( )); } warnings.push(archive.downloaded_warning(name)); + if !emptied.is_empty() { + warnings.push(VendorWarning::new( + GITIGNORE_NEUTRALIZED, + format!( + "{name}: the patched gem ships its own `.gitignore` ({}), whose rules would \ + keep git from committing files of the vendored copy; emptied in the vendored \ + copy (commit it)", + super::npm_dir::summarize_rules(&emptied) + ), + )); + } Ok(()) } @@ -2067,7 +2115,7 @@ async fn stage_platform_builds( format!("cannot extract the patched platform gem for {subject}: {e}"), )); } - match empty_shipped_gitignores(&tree, &patch.record.files).await { + match empty_shipped_gitignores(&tree, &patch.record.files, Shipped::Every).await { Ok(files) => emptied.extend(files.into_iter().map(|file| format!("{platform}/{file}"))), Err(e) => { return Err(policy.hard( @@ -2123,38 +2171,95 @@ async fn stage_platform_builds( Ok((warnings, built)) } -/// The advisory of [`empty_shipped_gitignores`]: the vendored trees differ -/// from the prebuilds in the ignore files named. +/// The advisory of [`empty_shipped_gitignores`]: the vendored copy differs +/// from the patched gem in the ignore files named. const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; -/// Empty every `.gitignore` a prebuild ships inside `tree`. Git reads one -/// at any depth, and for the files below it its rules win over the uuid -/// dir's `!*`: a `*.so` rule the gem's own repository used would leave the -/// binary out of the commit, with no rule of the project's to remove. The -/// file stays, empty, so the tree keeps the gem's file list — the way the -/// Composer backend neutralises the filters of a mirrored copy. Done while -/// the tree is staged, so the ledger's inventory and `repair`'s restore -/// see the same bytes. +/// Which of the `.gitignore` files a patched gem ships +/// [`empty_shipped_gitignores`] empties. +#[derive(Clone, Copy)] +enum Shipped<'a> { + /// Every one: the trees of a gem vendored as platform gems. + Every, + /// Those whose rules match a file of the tree (the gem's own tree). + /// A gem may ship a `.gitignore` as data (a template it copies into a + /// new project), and one that hides nothing is kept byte for byte. + /// `recorded`, an inventory of the tree when the ledger has one, + /// decides for the files it names: one it holds empty is emptied and + /// one it holds as shipped is kept, whatever the rules say. + Hiding { + recorded: Option<&'a std::collections::BTreeMap>, + }, +} + +/// Whether a rule of the `.gitignore` at `path` matches one of `files` +/// (paths relative to the directory that holds it), as git reads it: for +/// the files below it, with a later rule and a negation having the last +/// word, and with a file under an ignored directory ignored whatever a +/// negation says of the file itself (git does not look inside such a +/// directory). An unreadable file hides nothing. +fn hides_a_file(path: &Path, files: &[&str]) -> bool { + let Some(dir) = path.parent() else { + return false; + }; + let mut builder = ignore::gitignore::GitignoreBuilder::new(dir); + if builder.add(path).is_some() { + return false; + } + let Ok(rules) = builder.build() else { + return false; + }; + files.iter().any(|file| { + // Top-down, as git walks: the first ignored directory settles it. + let file = Path::new(file); + let mut dirs: Vec<&Path> = file + .ancestors() + .skip(1) + .filter(|dir| !dir.as_os_str().is_empty()) + .collect(); + dirs.reverse(); + dirs.into_iter() + .any(|dir| rules.matched(dir, true).is_ignore()) + || rules.matched(file, false).is_ignore() + }) +} + +/// Empty the `.gitignore` files a patched gem ships inside `tree` (the +/// gem's own tree, or one platform gem's) that `which` names. Git reads +/// one at any depth, and for the files below it its rules win over the +/// uuid dir's `!*`: a `*.so` or `*.lock` rule the gem's own repository +/// used would leave a file of the copy out of the commit, with no rule of +/// the project's to remove. The file stays, empty, so the tree keeps the +/// gem's file list — the way the Composer backend neutralises the filters +/// of a mirrored copy. Done while the tree is staged, so the ledger's +/// inventory and `repair`'s restore see the same bytes. /// /// A `.gitignore` the patch itself rewrites is left as the patch has it /// (its hash is the record's); what it ignores is then for -/// [`keep_platform_trees_committable`] to refuse. Returns the paths -/// emptied, relative to `tree`. +/// [`keep_copy_committable`] to refuse. Returns the paths emptied, +/// relative to `tree`. async fn empty_shipped_gitignores( tree: &Path, files: &HashMap, + which: Shipped<'_>, ) -> std::io::Result> { let root = tree.to_path_buf(); + let patched: Vec = files + .keys() + .map(|key| normalize_file_path(key).to_string()) + .collect(); + let (every, recorded) = match which { + Shipped::Every => (true, None), + Shipped::Hiding { recorded } => (false, recorded.cloned()), + }; let shipped = tokio::task::spawn_blocking(move || { - let mut shipped: Vec<(PathBuf, String)> = Vec::new(); + let mut ignores: Vec<(PathBuf, String)> = Vec::new(); + let mut all: Vec = Vec::new(); // Links are not followed (and none is extracted): only the // regular files of the tree itself. for entry in walkdir::WalkDir::new(&root).sort_by_file_name() { let entry = entry?; - if entry.file_name() != ".gitignore" - || !entry.file_type().is_file() - || entry.metadata()?.len() == 0 - { + if !entry.file_type().is_file() { continue; } let rel = entry @@ -2163,7 +2268,38 @@ async fn empty_shipped_gitignores( .map_err(std::io::Error::other)? .to_string_lossy() .replace('\\', "/"); - shipped.push((entry.into_path(), rel)); + if entry.file_name() == ".gitignore" + && entry.metadata()?.len() != 0 + && !patched.contains(&rel) + { + ignores.push((entry.path().to_path_buf(), rel.clone())); + } + all.push(rel); + } + let empty_hash = crate::utils::digest::sha256_hex_of(b""); + let mut shipped: Vec<(PathBuf, String)> = Vec::new(); + for (path, rel) in ignores { + let wanted = match recorded.as_ref().and_then(|inventory| inventory.get(&rel)) { + _ if every => true, + Some(hash) if *hash == empty_hash => true, + Some(hash) + if *hash == crate::utils::digest::sha256_hex_of(&std::fs::read(&path)?) => + { + false + } + _ => { + // The files at or below the directory of this one. + let below = rel.strip_suffix(".gitignore").unwrap_or_default(); + let files: Vec<&str> = all + .iter() + .filter_map(|file| file.strip_prefix(below)) + .collect(); + hides_a_file(&path, &files) + } + }; + if wanted { + shipped.push((path, rel)); + } } Ok::<_, std::io::Error>(shipped) }) @@ -2171,9 +2307,6 @@ async fn empty_shipped_gitignores( .map_err(std::io::Error::other)??; let mut emptied = Vec::new(); for (path, rel) in shipped { - if files.keys().any(|key| normalize_file_path(key) == rel) { - continue; - } atomic_write_bytes_preserving_mode(&path, b"").await?; emptied.push(rel); } @@ -2253,31 +2386,32 @@ pub(super) fn recorded_builds(entry: &VendorEntry) -> Result/.gitignore` of a gem vendored as platform gems: re-includes -/// everything under the uuid dir against the project's own ignore rules. -/// A prebuild's tree holds the compiled extension (`*.so`, `*.bundle`, -/// `*.dll`, a JRuby gem's `*.jar`), which stock ignore templates name; a -/// gem vendored as its own tree is source files and gets none. +/// `/.gitignore` of a vendored gem: re-includes everything under +/// the uuid dir against the project's own ignore rules. A prebuild's tree +/// holds the compiled extension (`*.so`, `*.bundle`, `*.dll`, a JRuby +/// gem's `*.jar`), which stock ignore templates name, and so do files a +/// gem's own tree ships (the `.rspec` of GitHub's `Rails.gitignore`, +/// #2348). const UUID_GITIGNORE: &str = "!*\n"; /// Rewrite `/.gitignore` ([`UUID_GITIGNORE`]) and -/// `/.gitattributes` of a gem vendored as platform gems when absent -/// or different, with the writer every backend that commits binaries -/// shares: the attributes keep a project rule such as `*.so filter=lfs`, -/// or an EOL conversion, from changing the bytes git commits. Neither file -/// is part of the copy, so writing them is no rebuild. `true` when either -/// was rewritten. +/// `/.gitattributes` of a vendored gem when absent or different, +/// with the writer every backend that commits binaries shares: the +/// attributes keep a project rule such as `*.so filter=lfs`, or an EOL +/// conversion, from changing the bytes git commits. Neither file is part +/// of the copy, so writing them is no rebuild. `true` when either was +/// rewritten. pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result { super::npm_dir::write_uuid_metadata(uuid_dir, UUID_GITIGNORE).await } -/// Ask git whether it would commit every file of the platform trees just -/// written (`inventory`: the copy's files) and the uuid dir's `.gitignore` -/// and `.gitattributes`. A rule the `.gitignore` cannot override refuses -/// `vendor_artifact_gitignored`, and the caller unwinds; git failing to -/// answer is only a warning. Nothing is asked without an inventory, whose -/// absence is already reported. -async fn keep_platform_trees_committable( +/// Ask git whether it would commit every file of the copy just written +/// (`inventory`: the copy's files, the gem's own tree or its platform +/// trees) and the uuid dir's `.gitignore` and `.gitattributes`. A rule the +/// `.gitignore` cannot override refuses `vendor_artifact_gitignored`, and +/// the caller unwinds; git failing to answer is only a warning. Nothing is +/// asked without an inventory, whose absence is already reported. +async fn keep_copy_committable( project_root: &Path, copy_rel: &str, inventory: Option<&std::collections::BTreeMap>, @@ -2310,6 +2444,35 @@ async fn keep_platform_trees_committable( } } +/// A copy of the gem's own tree that git would not commit whole. +const COPY_GITIGNORED: &str = "vendor_gem_copy_gitignored"; + +/// The advisory for a copy (`copy_rel`) of a gem's own tree that an +/// earlier release vendored, when git would still leave a file of it out +/// of the commit now that the uuid dir has its `.gitignore`: a +/// `.gitignore` the gem ships, which that release kept as shipped, wins +/// below it. The copy and its ledger inventory agree as they are, so +/// nothing is rewritten; `git add -f` commits the files. `None` when git +/// would commit every file, or cannot say. +async fn shipped_rules_warning(project_root: &Path, copy_rel: &str) -> Option { + let inventory = super::verify::compute_dir_inventory(&project_root.join(copy_rel)) + .await + .ok()?; + let paths: Vec = inventory + .keys() + .map(|file| format!("{copy_rel}/{file}")) + .collect(); + let rules = super::npm_dir::gitignored(project_root, &paths).await?; + Some(VendorWarning::new( + COPY_GITIGNORED, + format!( + "git would not commit every file of the vendored copy at {copy_rel} ({rules}): a \ + `.gitignore` the gem ships still applies inside it, so a fresh clone would fail \ + `vendor --check`. Run `git add -f {copy_rel}` and commit to keep the whole copy" + ), + )) +} + /// A dry run's check of a gem the lock pins as platform gems: the whole /// download, verification and unpacking of [`gem_platform_service_copy`], /// into a scratch directory. @@ -2336,9 +2499,9 @@ async fn preview_platform_builds( /// Acquire a verified service copy without replacing the prior copy on /// failure: the gem's own tree, or one patched platform gem's tree per /// platform in `platforms` when the lock pins the gem as platform gems, -/// each from its own patch in `builds` (with the uuid dir's git metadata, -/// see [`restore_uuid_metadata`]). Returns what the ledger records of -/// those trees (none for the gem's own tree). +/// each from its own patch in `builds`; then the uuid dir's git metadata +/// (see [`restore_uuid_metadata`]). Returns what the ledger records of +/// the platform trees (none for the gem's own tree). #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, @@ -2362,6 +2525,7 @@ async fn materialise_patched_copy( copy_dir, uuid_dir, unwind_uuid_dir, + None, warnings, ) .await? @@ -2379,21 +2543,21 @@ async fn materialise_patched_copy( warnings, ) .await?; - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - if unwind_uuid_dir { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - } - return Err(ServicePolicy::Refused.hard( - "vendor_prebuilt_write_failed", - format!( - "cannot write the git metadata of {}: {e}", - uuid_dir.display() - ), - )); - } } } + if let Err(e) = restore_uuid_metadata(uuid_dir).await { + if unwind_uuid_dir { + let _ = remove_tree(uuid_dir).await; + prune_empty_vendor_levels(uuid_dir).await; + } + return Err(ServicePolicy::Refused.hard( + "vendor_prebuilt_write_failed", + format!( + "cannot write the git metadata of {}: {e}", + uuid_dir.display() + ), + )); + } Ok((already_patched_result(purl, copy_dir, &record.files), built)) } @@ -12536,6 +12700,492 @@ mod tests { ); } + /// A gem vendored as its own directory is committed whole (#2348): the + /// files of the copy that an ignore rule matches are kept in the + /// commit, or the gem is refused, as for a gem vendored as platform + /// gems. + mod committable_gem_trees { + use super::*; + use crate::vendor::test_support as ts; + use crate::vendor::{check_vendored_artifact, ArtifactHealth}; + + const AT: &str = "2026-06-09T00:00:00Z"; + /// The line of GitHub's stock `Rails.gitignore` that matches a file + /// gems ship, and one more of its patterns. + const RAILS_RULES: &str = ".rspec\n*.log\n"; + const RSPEC: &str = ".rspec"; + + fn copy(root: &Path) -> PathBuf { + root.join(copy_rel()) + } + + fn uuid_dir(root: &Path) -> PathBuf { + root.join(format!(".socket/vendor/gem/{UUID}")) + } + + /// A project and a service that serves a gem of `files` beside the + /// patched `lib/rack.rb`. + async fn project_serving( + files: &[(&str, &[u8])], + ) -> ( + tempfile::TempDir, + PathBuf, + PatchRecord, + wiremock::MockServer, + VendorServiceConfig, + ) { + let (tmp, root, _installed, _blobs, record) = + fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let mut data = vec![("lib/rack.rb", PATCHED)]; + data.extend_from_slice(files); + let gem = make_gem(&data); + let server = wiremock::MockServer::start().await; + let stub = Some((SERVICE_STUB, sri_sha512(SERVICE_STUB))); + let stub = stub.as_ref().map(|(bytes, sri)| (*bytes, sri.as_str())); + mount_gem_granted(&server, &gem, &sri_sha512(&gem), stub).await; + let cfg = gem_service_cfg(&server.uri(), VendorSource::Service, false); + (tmp, root, record, server, cfg) + } + + async fn vendor( + root: &Path, + record: &PatchRecord, + cfg: &VendorServiceConfig, + dry_run: bool, + ) -> VendorOutcome { + let blobs = root.join("no-blobs"); + let sources = PatchSources::blobs_only(&blobs); + let install = missing_install(root); + ts::vendor_gem( + PURL, + &install, + root, + record, + &sources, + AT, + dry_run, + false, + Some(cfg), + ) + .await + } + + /// Vendor, persist the entry, and hand back the ledger's copy. + async fn vendor_and_persist( + root: &Path, + record: &PatchRecord, + cfg: &VendorServiceConfig, + ) -> (VendorEntry, Vec) { + let (result, entry, warnings) = unwrap_done(vendor(root, record, cfg, false).await); + assert!(result.success, "{:?}", result.error); + ts::persist(root, PURL, entry.expect("a ledger entry")).await; + let entry = crate::vendor::load_state(root).await.unwrap().entries[PURL].clone(); + (entry, warnings) + } + + fn git(root: &Path, args: &[&str]) { + let git = crate::utils::process::resolve_tool("git").expect("git"); + let out = std::process::Command::new(git) + .arg("-C") + .arg(root) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_SYSTEM", "/dev/null") + .args(["-c", "user.name=t", "-c", "user.email=t@example.com"]) + .args(["-c", "core.autocrlf=false", "-c", "commit.gpgsign=false"]) + .args(args) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + } + + fn metadata() -> [(&'static str, &'static str); 2] { + [ + (".gitignore", "!*\n"), + (".gitattributes", crate::vendor::npm_dir::UUID_GITATTRIBUTES), + ] + } + + async fn text(path: PathBuf) -> String { + tokio::fs::read_to_string(&path) + .await + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) + } + + /// The report's gem case: a project rule (`.rspec`, from GitHub's + /// `Rails.gitignore`) matches a file the gem ships. The uuid dir's + /// own `.gitignore` re-includes it, so the commit holds the whole + /// copy and a fresh clone passes the check the vendoring checkout + /// passes. + #[tokio::test] + async fn a_file_a_project_rule_ignores_reaches_a_fresh_clone() { + let (tmp, root, record, _server, cfg) = + project_serving(&[(RSPEC, b"--color\n"), ("spec/run.log", b"ok\n")]).await; + if ts::git_project(&root, RAILS_RULES).is_none() { + return; // no git, nothing to commit + } + let (entry, warnings) = vendor_and_persist(&root, &record, &cfg).await; + assert!( + !warnings.iter().any(|w| w.code.contains("gitignore")), + "{warnings:?}" + ); + for (file, want) in metadata() { + assert_eq!(text(uuid_dir(&root).join(file)).await, want, "{file}"); + } + let ignored: Vec = [RSPEC, "spec/run.log"] + .iter() + .map(|file| format!("{}/{file}", copy_rel())) + .collect(); + assert_eq!( + crate::vendor::npm_dir::gitignored(&root, &ignored).await, + None, + "git commits every file of the copy" + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + git(&root, &["add", "-A"]); + git(&root, &["commit", "-q", "-m", "vendor"]); + let clone = tmp.path().join("clone"); + git( + tmp.path(), + &[ + "clone", + "-q", + root.to_str().unwrap(), + clone.to_str().unwrap(), + ], + ); + assert_eq!( + tokio::fs::read(copy(&clone).join(RSPEC)).await.unwrap(), + b"--color\n", + "the clone holds the file the project rule matches" + ); + let cloned = crate::vendor::load_state(&clone).await.unwrap().entries[PURL].clone(); + assert_eq!( + check_vendored_artifact(&clone, &cloned, &record).await, + ArtifactHealth::Healthy + ); + } + + /// A rule that ignores the vendored dir itself cannot be overridden + /// from inside it: the gem is refused before anything is downloaded + /// or written, in a dry run as in a wet one. + #[tokio::test] + async fn a_rule_that_ignores_the_vendored_dir_refuses_the_gem() { + let (_tmp, root, record, server, cfg) = project_serving(&[]).await; + if ts::git_project(&root, "/.socket/vendor/gem/\n").is_none() { + return; // no git, nothing to commit + } + let before = ts::tree_snapshot(&root); + for dry_run in [true, false] { + let (code, detail) = unwrap_refused(vendor(&root, &record, &cfg, dry_run).await); + assert_eq!( + code, "vendor_artifact_gitignored", + "dry_run={dry_run}: {detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); + } + assert_eq!(ts::request_count(&server).await, 0); + assert!(!root.join(".socket/vendor").exists()); + } + + /// A `.gitignore` the gem ships (its repository's, listed by + /// `git ls-files`) wins over the uuid dir's `!*` for the files + /// below it. Each one whose rules match a file of the copy is + /// emptied in it, at any depth, and reported once. One that hides + /// nothing (a template the gem copies into new projects) and one + /// the patch rewrites keep their bytes. The ledger's inventory is + /// of the copy as vendored, a second run is in sync, and + /// `repair`'s restore reproduces the same tree. + #[tokio::test] + async fn a_gitignore_the_gem_ships_is_emptied_in_the_copy() { + const NESTED: &str = "spec/.gitignore"; + const FIXTURE: &str = "spec/fixtures/big.json"; + const PATCHED_IGNORE: &str = "ext/.gitignore"; + const TEMPLATE: &str = "lib/site_template/.gitignore"; + const TEMPLATE_RULES: &[u8] = b"_site\n.sass-cache\nvendor\n"; + let (_tmp, root, mut record, _server, cfg) = project_serving(&[ + (".gitignore", b"*.lock\n"), + ("Gemfile.lock", b"GEM\n"), + (NESTED, b"fixtures/\n"), + (FIXTURE, b"{}\n"), + (TEMPLATE, TEMPLATE_RULES), + ("lib/site_template/index.md", b"# site\n"), + (PATCHED_IGNORE, b"# the patch's own\n"), + ]) + .await; + record.files.insert( + PATCHED_IGNORE.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"*.o\n"), + after_hash: compute_git_sha256_from_bytes(b"# the patch's own\n"), + mode: None, + }, + ); + if ts::git_project(&root, "").is_none() { + return; // no git, nothing to commit + } + let (entry, warnings) = vendor_and_persist(&root, &record, &cfg).await; + let neutralized: Vec<_> = warnings + .iter() + .filter(|w| w.code == "vendor_gem_gitignore_neutralized") + .collect(); + assert_eq!(neutralized.len(), 1, "{warnings:?}"); + for file in [".gitignore", NESTED] { + assert!(neutralized[0].detail.contains(file), "{neutralized:?}"); + } + for file in [PATCHED_IGNORE, TEMPLATE] { + assert!(!neutralized[0].detail.contains(file), "{neutralized:?}"); + } + let emptied = |copy: &Path| { + for file in [".gitignore", NESTED] { + assert_eq!(std::fs::read(copy.join(file)).unwrap(), b"", "{file}"); + } + assert_eq!( + std::fs::read(copy.join(TEMPLATE)).unwrap(), + TEMPLATE_RULES, + "a `.gitignore` that hides no file of the copy is the gem's data" + ); + assert_eq!( + std::fs::read(copy.join(PATCHED_IGNORE)).unwrap(), + b"# the patch's own\n" + ); + }; + emptied(©(&root)); + let shipped: Vec = ["Gemfile.lock", FIXTURE] + .iter() + .map(|file| format!("{}/{file}", copy_rel())) + .collect(); + assert_eq!( + crate::vendor::npm_dir::gitignored(&root, &shipped).await, + None, + "git commits the files the gem's own rules named" + ); + let inventory = entry.artifact.file_inventory.as_ref().expect("inventory"); + assert_eq!( + inventory.get(NESTED).map(String::as_str), + Some(crate::utils::digest::sha256_hex_of(b"").as_str()) + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + let (again, rerun_entry, _) = unwrap_done(vendor(&root, &record, &cfg, false).await); + assert!(again.success && rerun_entry.is_none(), "{:?}", again.error); + + tokio::fs::remove_dir_all(copy(&root)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + emptied(©(&root)); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// A copy an earlier release vendored holds the gem's `.gitignore` + /// as shipped, and its ledger inventory says so. `repair`'s restore + /// reproduces that copy, byte for byte, so the entry still verifies. + #[tokio::test] + async fn restore_keeps_a_shipped_gitignore_an_earlier_release_recorded() { + const SHIPPED: &[u8] = b"*.lock\n"; + let (_tmp, root, record, _server, cfg) = + project_serving(&[(".gitignore", SHIPPED), ("Gemfile.lock", b"GEM\n")]).await; + let (mut entry, _) = vendor_and_persist(&root, &record, &cfg).await; + // The entry as the earlier release wrote it. + tokio::fs::write(copy(&root).join(".gitignore"), SHIPPED) + .await + .unwrap(); + entry.artifact.file_inventory = Some( + crate::vendor::verify::compute_dir_inventory(©(&root)) + .await + .unwrap(), + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + tokio::fs::remove_dir_all(copy(&root)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + assert_eq!( + tokio::fs::read(copy(&root).join(".gitignore")) + .await + .unwrap(), + SHIPPED + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + + /// Which shipped `.gitignore` hides a file is decided as git + /// decides it: a negation cannot re-include a file whose directory + /// is ignored, a later rule has the last word, and rules that match + /// nothing hide nothing. + #[test] + fn a_shipped_gitignore_is_read_as_git_reads_it() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join(".gitignore"); + let hides = |rules: &str, files: &[&str]| { + std::fs::write(&path, rules).unwrap(); + hides_a_file(&path, files) + }; + assert!(hides( + "fixtures/\n!fixtures/keep.json\n", + &["fixtures/keep.json"] + )); + assert!(hides("/spec/tmp\n", &["spec/tmp/a/b.txt"])); + assert!(hides("*.lock\n", &["Gemfile.lock"])); + assert!(!hides("*.lock\n!Gemfile.lock\n", &["Gemfile.lock"])); + assert!(!hides("_site\nvendor\n", &["index.md", "lib/x.rb"])); + assert!(!hides("/tmp\n", &["lib/tmp.rb"])); + } + + /// The same copy in the checkout of a project that upgraded: the + /// in-sync run that writes the uuid dir's pair says, once, that a + /// `.gitignore` inside the copy still keeps a file out of the + /// commit, and names the command that commits it. The copy and its + /// ledger inventory agree as they are, so nothing in it changes. + #[tokio::test] + async fn a_shipped_gitignore_an_earlier_release_kept_is_reported_once() { + const SHIPPED: &[u8] = b"*.lock\n"; + let (_tmp, root, record, _server, cfg) = + project_serving(&[(".gitignore", SHIPPED), ("Gemfile.lock", b"GEM\n")]).await; + if ts::git_project(&root, "").is_none() { + return; // no git, nothing to commit + } + vendor_and_persist(&root, &record, &cfg).await; + // As the earlier release left it: the gem's rules, no pair. + tokio::fs::write(copy(&root).join(".gitignore"), SHIPPED) + .await + .unwrap(); + for (file, _) in metadata() { + std::fs::remove_file(uuid_dir(&root).join(file)).unwrap(); + } + + let (again, entry, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); + assert!(again.success && entry.is_none(), "{:?}", again.error); + let [warning] = warnings.as_slice() else { + panic!("one advisory: {warnings:?}"); + }; + assert_eq!(warning.code, "vendor_gem_copy_gitignored"); + let hidden = format!("{}/Gemfile.lock", copy_rel()); + assert!(warning.detail.contains(&hidden), "{warning:?}"); + assert!( + warning + .detail + .contains(&format!("git add -f {}", copy_rel())), + "{warning:?}" + ); + assert_eq!( + tokio::fs::read(copy(&root).join(".gitignore")) + .await + .unwrap(), + SHIPPED + ); + // The remedy is the one git takes: forced, the file is tracked + // and stays committed whatever the rule says. + git(&root, &["add", "-f", ©_rel()]); + git(&root, &["commit", "-q", "-m", "vendor"]); + let tracked = std::process::Command::new("git") + .arg("-C") + .arg(&root) + .args(["ls-files", "--", &hidden]) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&tracked.stdout).trim(), hidden); + + let (_, _, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); + assert!(warnings.is_empty(), "said once: {warnings:?}"); + } + + /// `repair` puts the pair back for a copy that is healthy, through + /// [`crate::vendor::redownload::restore_gem_uuid_metadata`]: `true` + /// when it wrote, `false` when the pair is as it should be, and + /// nothing for an entry of another ecosystem. + #[tokio::test] + async fn repair_writes_the_missing_metadata_of_a_healthy_copy() { + use crate::vendor::redownload::restore_gem_uuid_metadata; + let (_tmp, root, record, _server, cfg) = project_serving(&[]).await; + let (entry, _) = vendor_and_persist(&root, &record, &cfg).await; + assert!(!restore_gem_uuid_metadata(&entry, &root).await.unwrap()); + for (file, _) in metadata() { + std::fs::remove_file(uuid_dir(&root).join(file)).unwrap(); + } + let mut other = entry.clone(); + other.ecosystem = "cargo".to_string(); + assert!(!restore_gem_uuid_metadata(&other, &root).await.unwrap()); + assert!(!uuid_dir(&root).join(".gitignore").exists()); + assert!(restore_gem_uuid_metadata(&entry, &root).await.unwrap()); + for (file, want) in metadata() { + assert_eq!(text(uuid_dir(&root).join(file)).await, want, "{file}"); + } + } + + /// The uuid dir's `.gitignore` and `.gitattributes` are not part of + /// the copy. An in-sync re-run puts back a pair that is missing (a + /// copy an earlier release vendored has none), asking the service + /// nothing; a dry run writes nothing; and `repair`'s restore, which + /// swaps in the copy alone, writes the pair again. + #[tokio::test] + async fn the_uuid_dir_metadata_is_put_back_by_a_rerun_and_by_restore() { + let (_tmp, root, record, server, cfg) = project_serving(&[(RSPEC, b"--color\n")]).await; + let (entry, _) = vendor_and_persist(&root, &record, &cfg).await; + let requests = ts::request_count(&server).await; + let drop_metadata = || { + for (file, _) in metadata() { + std::fs::remove_file(uuid_dir(&root).join(file)).unwrap(); + } + }; + + drop_metadata(); + let lost = ts::tree_snapshot(&root); + let (preview, ..) = unwrap_done(vendor(&root, &record, &cfg, true).await); + assert!(preview.success, "{:?}", preview.error); + assert_eq!(ts::tree_snapshot(&root), lost, "a dry run writes nothing"); + let (again, rerun_entry, warnings) = + unwrap_done(vendor(&root, &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + for (file, want) in metadata() { + assert_eq!( + text(uuid_dir(&root).join(file)).await, + want, + "re-run: {file}" + ); + } + assert_eq!(ts::request_count(&server).await, requests); + + drop_metadata(); + tokio::fs::remove_dir_all(copy(&root)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + for (file, want) in metadata() { + assert_eq!( + text(uuid_dir(&root).join(file)).await, + want, + "restore: {file}" + ); + } + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + } + } + /// A gem bundler locked as precompiled platform gems (see the module /// docs): vendored from the patch service's prebuilds, one tree per /// locked platform. diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 923fb65db9..87b968378f 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -285,6 +285,7 @@ pub async fn restore( &stage, uuid_dir, true, + entry.artifact.file_inventory.as_ref(), &mut warnings, ) .await @@ -445,11 +446,10 @@ pub async fn restore( .map_err(|e| e.to_string())?; } } - // Likewise a gem vendored as platform gems: only the artifact dir was - // swapped in from the stage, and without the uuid dir's own metadata a - // `*.so` / `*.bundle` rule drops the prebuilt binaries from the commit. - let archive = super::gem::bazel::is_archive(entry); - if entry.ecosystem == "gem" && (archive || !entry.gem_tree_platforms().is_empty()) { + // Likewise a gem: only the artifact dir was swapped in from the stage, + // and without the uuid dir's own metadata a project rule (`*.so`, + // `*.bundle`, `.rspec`) drops files of the copy from the commit. + if entry.ecosystem == "gem" { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await @@ -488,6 +488,27 @@ pub async fn restore_npm_uuid_metadata(entry: &VendorEntry, root: &Path) -> std: super::npm_dir::restore_uuid_metadata(&root.join(uuid_dir)).await } +/// [`restore_npm_uuid_metadata`] for a gem entry (its own tree, platform +/// trees or the archive kept for a Bazel hub): a copy that 5.1 or earlier +/// vendored as the gem's own tree has neither file, and a project rule +/// then drops files of it from the commit (#2348). `Ok(true)` when either +/// was rewritten; a no-op for other ecosystems and for a vendor dir +/// reached through a symlink. +pub async fn restore_gem_uuid_metadata(entry: &VendorEntry, root: &Path) -> std::io::Result { + if entry.ecosystem != "gem" + || super::path::vendor_dir_symlink(root, "gem", Some(&entry.uuid)).is_some() + { + return Ok(false); + } + let Some(uuid_dir) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) else { + return Err(std::io::Error::other(format!( + "`{}` is not a canonical patch uuid", + entry.uuid + ))); + }; + super::gem::restore_uuid_metadata(&root.join(uuid_dir)).await +} + /// Would git commit an npm-family entry's artifact and its uuid-dir /// metadata? Asked after repair rewrote them, since a rule the /// `/.gitignore` cannot override (`.socket/`) still drops them from diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1a83dce0b0..9fba9c2172 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5718,6 +5718,30 @@ a Dockerfile in another directory or under another name. A `.dockerignore` that Hosted mode needs only the two files in that step (the patched gems come from the patch registry), and agent mode changes neither file. +## Ruby gems: vendored gems and `.gitignore` + +A vendored gem is only portable when git commits every file of its directory. Two kinds of +ignore rule can keep a file out: a rule of the project (GitHub's `Rails.gitignore` has +`.rspec`, which gems such as `rest-client` ship), and a `.gitignore` the gem ships inside +itself. The checkout that vendored the gem holds every file either way, so the loss shows +only in a fresh clone, where `vendor --check` and `vex` report `vendor_inventory_mismatch`. + +Vendored mode therefore writes a `.gitignore` (`!*`) and a `.gitattributes` beside the gem, +in `.socket/vendor/gem//`, so that the project's rules and filters do not apply +below it, and it empties each `.gitignore` the gem ships whose rules match a file of the gem +(`vendor_gem_gitignore_neutralized` names them). One that matches none of the gem's files, +such as a template the gem copies into new projects, and one the patch itself changes are +kept as they are. The vendor ledger records the copy as vendored. A rule that ignores `.socket/`, `.socket/vendor/` or the gem's directory as a whole +cannot be overridden from inside it: the gem is refused with `vendor_artifact_gitignored` +before anything is downloaded, and so is a gem with a file git would still leave out once +the copy is written. + +A gem that an earlier release vendored has neither file. The next vendored run, or +`repair`, writes them; commit them with the rest of `.socket/vendor/`. Such a copy also +keeps the gem's own `.gitignore` as shipped. When that still hides a file, the run that +writes the two files says so (`vendor_gem_copy_gitignored`); `git add -f` on the directory +it names commits the whole copy. + ## Ruby gems: gems vendored mode refuses Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing