diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a14c8e681..0459c90ab 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2021,7 +2021,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). 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 | +| 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. A `.gitattributes` the patched gem ships inside its own tree likewise wins over the uuid dir's for the files below it, so one whose rules turn a conversion on for a file of the copy (`text` in any form but `-text`, a `filter` or `working-tree-encoding` with a value, `ident`; such as `*.rb text eol=lf` over a file with CRLF line endings) is emptied in the copy too (`vendor_gem_gitattributes_neutralized`), in a gem's own tree and in a platform gem's; one that converts no file of the copy (`merge=ours`, `eol` without `text`, a pattern that matches nothing) and one the patch itself rewrites are kept, and `repair` restores each as the ledger's inventory records it. A copy that 5.2.0 or earlier vendored with such a file as shipped stays as it is, and every in-sync run over it warns `vendor_gem_copy_gitattributes`. 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 | @@ -2919,6 +2919,8 @@ command's integration tests check its output. | `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, 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_gem_copy_gitattributes` | warning | vendor / scan / get `--mode vendored` (a gem vendored by 5.2.0 or earlier), dry run included: the in-sync copy still holds a `.gitattributes` the gem ships whose rules turn a conversion on for a file of the copy (the detail names the files, each under its platform for platform gems), so git may commit or check out other bytes than the ledger records and a fresh clone can fail `vendor --check` with `vendor_inventory_mismatch`; `repair` restores the copy as recorded, rules included. The copy and the ledger are left as they are. Remedy: delete the copy directory the detail names and run `socket-patch scan --mode vendored` again, which vendors the copy with the file emptied (`vendor_artifact_rebuilt`, `vendor_gem_gitattributes_neutralized`), then commit it. Said by every in-sync run until then. | +| `vendor_gem_gitattributes_neutralized` | warning | vendor / scan / get `--mode vendored` (gem): the patched gem ships a `.gitattributes` inside its own tree whose rules would have git change the bytes of files of the vendored copy at commit or checkout (`text` in any form but `-text`, a `filter` or `working-tree-encoding` with a value, `ident`), so the run emptied it in the copy: each one whose rules turn such a conversion on for a file of the copy, in a gem's own tree and in a platform gem's. The detail names the gem and the emptied files (three, then a count of the rest). The gem is vendored; commit the copy. | | `vendor_gem_gitignore_neutralized` | warning | vendor / scan / get `--mode vendored` (gem): the patched gem ships a `.gitignore` inside its own tree whose rules would keep git from committing files of the vendored copy, so the run emptied it in the copy: 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. The detail names the gem and the emptied files (three, then a count of the rest). The gem is vendored; commit the copy. | | `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. | diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index f8652d939..8856e4ced 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -1343,6 +1343,12 @@ pub async fn vendor_gem_builds<'a>( )), } } + // A `.gitattributes` the gem ships that an earlier release + // left as shipped still converts files of the copy (#2483). + warnings.extend( + shipped_attributes_warning(copy_dir, copy_rel, platforms, builds, &record.files) + .await, + ); if *builds_kept { let missing: Vec = platforms .iter() @@ -1760,11 +1766,11 @@ async fn gem_service_archive( /// [`gem_service_archive`], then atomically replace the copy with the /// 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. +/// rules hide a file of the copy, and a `.gitattributes` whose rules +/// convert one, is emptied in it ([`empty_shipped`]). `recorded` is the +/// ledger inventory of the copy being restored, for `repair`: each such +/// file 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>, @@ -1821,16 +1827,22 @@ pub(super) async fn gem_service_copy( ))); } 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}"), - )); - } - }; + let mut emptied: [Vec; 2] = Default::default(); + for (kind, emptied) in SHIPPED_FILES.into_iter().zip(&mut emptied) { + *emptied = match empty_shipped(kind, &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 `{}` the patched gem for {name} ships: {e}", + kind.name() + ), + )); + } + }; + } 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( @@ -1839,16 +1851,8 @@ 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) - ), - )); + for (kind, emptied) in SHIPPED_FILES.into_iter().zip(&emptied) { + warnings.extend(kind.neutralized_warning(name, "gem ships its", "copy", emptied)); } Ok(()) } @@ -1932,6 +1936,7 @@ async fn stage_platform_builds( platforms: &[String], builds: &[GemBuildPatch<'_>], stage: &Path, + recorded: Option<&std::collections::BTreeMap>, ) -> Result<(Vec, Vec), Box> { use futures_util::StreamExt as _; let policy = ServicePolicy::Refused; @@ -2084,7 +2089,7 @@ async fn stage_platform_builds( }) .buffered(PREBUILD_DOWNLOADS_AT_ONCE)); - let mut emptied: Vec = Vec::new(); + let mut emptied: [Vec; 2] = Default::default(); let mut built: Vec = Vec::with_capacity(patches.len()); let mut source_url = String::new(); while let Some(downloaded) = downloads.next().await { @@ -2115,21 +2120,46 @@ async fn stage_platform_builds( format!("cannot extract the patched platform gem for {subject}: {e}"), )); } - 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( - "vendor_prebuilt_write_failed", - format!("cannot empty a `.gitignore` the patched platform gem for {subject} ships: {e}"), - )); - } - } + // The stub is a file of the tree a shipped rule may name, so it is + // written before those rules are read. if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub).await { return Err(policy.hard( "vendor_prebuilt_write_failed", format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), )); } + // The ledger's inventory of this tree, when a copy is restored. + let in_tree: Option> = recorded.map(|all| { + all.iter() + .filter_map(|(file, hash)| { + let file = file.strip_prefix(platform)?.strip_prefix('/')?; + Some((file.to_string(), hash.clone())) + }) + .collect() + }); + for (kind, emptied) in SHIPPED_FILES.into_iter().zip(&mut emptied) { + let which = match kind { + ShippedFile::Gitignore => Shipped::Every, + ShippedFile::Gitattributes => Shipped::Hiding { + recorded: in_tree.as_ref(), + }, + }; + match empty_shipped(kind, &tree, &patch.record.files, which).await { + Ok(files) => { + emptied.extend(files.into_iter().map(|file| format!("{platform}/{file}"))); + } + Err(e) => { + return Err(policy.hard( + "vendor_prebuilt_write_failed", + format!( + "cannot empty a `{}` the patched platform gem for {subject} ships: \ + {e}", + kind.name() + ), + )); + } + } + } // The gem passed the service's digest for this platform's patch // above (`fetch_verified_archive`), which is what vouches for a // tree that ships none of the patched files: only one it does ship @@ -2157,31 +2187,33 @@ async fn stage_platform_builds( format_args!("{name} as patched platform gems ({})", platforms.join(", ")), &source_url, )]; - if !emptied.is_empty() { - warnings.push(VendorWarning::new( - GITIGNORE_NEUTRALIZED, - format!( - "{name}: the patched platform gems ship their own `.gitignore` ({}), whose \ - rules would keep git from committing files of the vendored trees; emptied in \ - the vendored copy (commit it)", - super::npm_dir::summarize_rules(&emptied) - ), + for (kind, emptied) in SHIPPED_FILES.into_iter().zip(&emptied) { + warnings.extend(kind.neutralized_warning( + name, + "platform gems ship their", + "trees", + emptied, )); } Ok((warnings, built)) } -/// The advisory of [`empty_shipped_gitignores`]: the vendored copy differs -/// from the patched gem in the ignore files named. +/// The advisory of [`empty_shipped`] for `.gitignore` files: the vendored +/// copy differs from the patched gem in the ignore files named. const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; -/// Which of the `.gitignore` files a patched gem ships -/// [`empty_shipped_gitignores`] empties. +/// The advisory of [`empty_shipped`] for `.gitattributes` files: the +/// vendored copy differs from the patched gem in the files named. +const GITATTRIBUTES_NEUTRALIZED: &str = "vendor_gem_gitattributes_neutralized"; + +/// Which of the `.gitignore` or `.gitattributes` files a patched gem ships +/// [`empty_shipped`] 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). + /// Those whose rules act on a file of the tree: a `.gitignore` that + /// hides one, a `.gitattributes` that converts one. /// 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, @@ -2224,62 +2256,274 @@ fn hides_a_file(path: &Path, files: &[&str]) -> bool { }) } -/// 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_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()), +/// What git does to a file's bytes at commit or checkout under one +/// conversion attribute, as the lines of a `.gitattributes` leave it. +#[derive(Clone, Copy, PartialEq)] +enum AttrState { + /// `attr` + Set, + /// `-attr` + Unset, + /// `!attr`: whatever was inherited is forgotten. + Unspecified, + /// `attr=value` + Value, +} + +/// The pattern and the attribute words of one `.gitattributes` line, as +/// git splits it: a pattern in double quotes has C-style escapes (octal +/// ones among them) and may hold blanks. `None` for a blank line, a +/// comment, a macro definition (`[attr]`, which git reads only at the top +/// of a repository) and a line git does not take: a negated pattern, or +/// an unfinished quote. +fn attributes_line(line: &str) -> Option<(String, &str)> { + let line = line.trim_start_matches([' ', '\t']).trim_end_matches('\r'); + if line.is_empty() || line.starts_with('#') || line.starts_with("[attr]") { + return None; + } + let (pattern, rest) = match line.strip_prefix('"') { + Some(quoted) => { + let mut pattern: Vec = Vec::new(); + let mut bytes = quoted.bytes().enumerate(); + loop { + match bytes.next()? { + (at, b'"') => { + break ( + String::from_utf8_lossy(&pattern).into_owned(), + "ed[at + 1..], + ); + } + (_, b'\\') => pattern.push(match bytes.next()?.1 { + b'a' => 0x07, + b'b' => 0x08, + b'f' => 0x0c, + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'v' => 0x0b, + first @ b'0'..=b'3' => { + let mut value = u32::from(first - b'0'); + for _ in 0..2 { + match bytes.next()?.1 { + digit @ b'0'..=b'7' => { + value = value * 8 + u32::from(digit - b'0'); + } + _ => return None, + } + } + u8::try_from(value).ok()? + } + other => other, + }), + (_, byte) => pattern.push(byte), + } + } + } + None => { + let end = line.find([' ', '\t']).unwrap_or(line.len()); + (line[..end].to_string(), &line[end..]) + } }; - let shipped = tokio::task::spawn_blocking(move || { - let mut ignores: Vec<(PathBuf, String)> = Vec::new(); + (!pattern.starts_with('!')).then_some((pattern, rest)) +} + +/// Whether the `.gitattributes` text `rules` has git change the bytes of +/// one of `files` (paths relative to the directory that holds it) at +/// commit or checkout, read as git reads it under the uuid dir's +/// `* -text -filter -ident -working-tree-encoding`: for each file the last +/// line that names an attribute decides it, and a file the rules leave +/// alone keeps the uuid dir's. The conversions are `text` in any form but +/// `-text` (`!text` hands the file back to `core.autocrlf`), a `filter` or +/// a `working-tree-encoding` with a value, and `ident`. `eol` alone does +/// nothing to a file that is not text, and `binary` is `-text`. A pattern +/// matches as in a `.gitignore`, except that one naming a directory does +/// not reach the files inside it. +/// +/// Where git's answer depends on the checkout, or the pattern is one this +/// reader cannot match as git does, the rule is taken to convert: letter +/// case is ignored (as git does under `core.ignorecase`, the default on +/// macOS and Windows), and a pattern with a POSIX class (`[[:space:]]`) or +/// one the matcher refuses stands for every file. +fn converts_a_file(rules: &str, files: &[&str]) -> bool { + const TEXT: usize = 0; + const FILTER: usize = 1; + const IDENT: usize = 2; + const ENCODING: usize = 3; + type Assignments = Vec<(usize, AttrState)>; + // `None`: a pattern taken to match every file. + let mut lines: Vec<(Option, Assignments)> = Vec::new(); + // Git skips a byte order mark at the head of the file. + for line in crate::formats::text::strip_bom(rules).lines() { + let Some((pattern, words)) = attributes_line(line) else { + continue; + }; + if pattern.ends_with('/') { + continue; // names directories only + } + let mut assignments: Assignments = Vec::new(); + for word in words.split([' ', '\t']).filter(|word| !word.is_empty()) { + // A value after `-attr` or `!attr` is dropped, as git drops it. + let (name, value) = match word.split_once('=') { + Some((name, _)) => (name, true), + None => (word, false), + }; + let (name, state) = if let Some(name) = name.strip_prefix('-') { + (name, AttrState::Unset) + } else if let Some(name) = name.strip_prefix('!') { + (name, AttrState::Unspecified) + } else if value { + (name, AttrState::Value) + } else { + (name, AttrState::Set) + }; + match name { + "text" => assignments.push((TEXT, state)), + "filter" => assignments.push((FILTER, state)), + "ident" => assignments.push((IDENT, state)), + "working-tree-encoding" => assignments.push((ENCODING, state)), + "binary" if state == AttrState::Set => { + assignments.push((TEXT, AttrState::Unset)); + } + _ => {} + } + } + if assignments.is_empty() { + continue; + } + // The pattern alone is a `.gitignore` line with the same meaning, + // once a leading `#` cannot be read as a comment (a quoted pattern + // may start with one; a negation was ruled out above). + let pattern = match pattern.strip_prefix('#') { + Some(rest) => format!("\\#{rest}"), + None => pattern, + }; + let mut builder = ignore::gitignore::GitignoreBuilder::new(""); + let readable = !pattern.contains("[[:") + && builder.case_insensitive(true).is_ok() + && builder.add_line(None, &pattern).is_ok(); + let matcher = match readable { + true => builder.build().ok(), + false => None, + }; + lines.push((matcher, assignments)); + } + files.iter().any(|file| { + let mut state: [Option; 4] = [None; 4]; + for (matcher, assignments) in &lines { + let matches = matcher + .as_ref() + .is_none_or(|matcher| matcher.matched(Path::new(file), false).is_ignore()); + if matches { + for (attr, value) in assignments { + state[*attr] = Some(*value); + } + } + } + matches!( + state[TEXT], + Some(AttrState::Set | AttrState::Value | AttrState::Unspecified) + ) || state[FILTER] == Some(AttrState::Value) + || state[IDENT] == Some(AttrState::Set) + || state[ENCODING] == Some(AttrState::Value) + }) +} + +/// A file of git's own that a patched gem ships inside its tree, which +/// git reads at any depth and, for the files below it, ahead of the uuid +/// dir's. +#[derive(Clone, Copy)] +enum ShippedFile { + /// `.gitignore`: its rules keep files of the copy out of the commit. + Gitignore, + /// `.gitattributes`: its rules change the bytes git commits or checks + /// out (#2483). + Gitattributes, +} + +/// Both kinds, in the order they are emptied and reported. +const SHIPPED_FILES: [ShippedFile; 2] = [ShippedFile::Gitignore, ShippedFile::Gitattributes]; + +impl ShippedFile { + /// The advisory for the files of this kind (`emptied`) that were + /// emptied in the copy of `name`: `ships` and `copy` word it for the + /// gem's own tree or its platform trees. `None` when none was. + fn neutralized_warning( + self, + name: &str, + ships: &str, + copy: &str, + emptied: &[String], + ) -> Option { + if emptied.is_empty() { + return None; + } + let files = super::npm_dir::summarize_rules(emptied); + Some(match self { + ShippedFile::Gitignore => VendorWarning::new( + GITIGNORE_NEUTRALIZED, + format!( + "{name}: the patched {ships} own `.gitignore` ({files}), whose rules would \ + keep git from committing files of the vendored {copy}; emptied in the \ + vendored copy (commit it)" + ), + ), + ShippedFile::Gitattributes => VendorWarning::new( + GITATTRIBUTES_NEUTRALIZED, + format!( + "{name}: the patched {ships} own `.gitattributes` ({files}), whose rules \ + would have git change the bytes of files of the vendored {copy} at commit \ + or checkout; emptied in the vendored copy (commit it)" + ), + ), + }) + } + + fn name(self) -> &'static str { + match self { + ShippedFile::Gitignore => ".gitignore", + ShippedFile::Gitattributes => ".gitattributes", + } + } + + /// The files of this kind in the tree at `root` that are to be + /// emptied, as path and path relative to `root`: every one (`every`), + /// or each one `recorded` holds empty or, when it does not hold it as + /// shipped, whose rules act on a file of the tree. An empty one and + /// one the patch rewrites (`patched`) are never among them. + fn shipped_in( + self, + root: &Path, + patched: &[String], + every: bool, + recorded: Option<&std::collections::BTreeMap>, + ) -> std::io::Result> { + let mut found: 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() { + for entry in walkdir::WalkDir::new(root).sort_by_file_name() { let entry = entry?; if !entry.file_type().is_file() { continue; } let rel = entry .path() - .strip_prefix(&root) + .strip_prefix(root) .map_err(std::io::Error::other)? .to_string_lossy() .replace('\\', "/"); - if entry.file_name() == ".gitignore" + if entry.file_name() == self.name() && entry.metadata()?.len() != 0 && !patched.contains(&rel) { - ignores.push((entry.path().to_path_buf(), rel.clone())); + found.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)) { + for (path, rel) in found { + let wanted = match recorded.and_then(|inventory| inventory.get(&rel)) { _ if every => true, Some(hash) if *hash == empty_hash => true, Some(hash) @@ -2289,19 +2533,70 @@ async fn empty_shipped_gitignores( } _ => { // The files at or below the directory of this one. - let below = rel.strip_suffix(".gitignore").unwrap_or_default(); + let below = rel.strip_suffix(self.name()).unwrap_or_default(); let files: Vec<&str> = all .iter() .filter_map(|file| file.strip_prefix(below)) .collect(); - hides_a_file(&path, &files) + self.acts_on(&path, &files) } }; if wanted { shipped.push((path, rel)); } } - Ok::<_, std::io::Error>(shipped) + Ok(shipped) + } + + /// Whether the file at `path` acts on one of `files`, the files at or + /// below its directory. An unreadable one does not. + fn acts_on(self, path: &Path, files: &[&str]) -> bool { + match self { + ShippedFile::Gitignore => hides_a_file(path, files), + ShippedFile::Gitattributes => std::fs::read(path) + .is_ok_and(|rules| converts_a_file(&String::from_utf8_lossy(&rules), files)), + } + } +} + +/// The paths a patch record's `files` name, relative to the gem's tree. +fn patched_paths(files: &HashMap) -> Vec { + files + .keys() + .map(|key| normalize_file_path(key).to_string()) + .collect() +} + +/// Empty the `.gitignore` or `.gitattributes` files (`kind`) 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, +/// and a `*.rb text eol=lf` over a file with CRLF line endings would have +/// git commit other bytes than the ledger records, 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. +/// +/// One the patch itself rewrites is left as the patch has it (its hash is +/// the record's); what a `.gitignore` of the patch ignores is then for +/// [`keep_copy_committable`] to refuse. Returns the paths emptied, +/// relative to `tree`. +async fn empty_shipped( + kind: ShippedFile, + tree: &Path, + files: &HashMap, + which: Shipped<'_>, +) -> std::io::Result> { + let root = tree.to_path_buf(); + let patched = patched_paths(files); + let (every, recorded) = match which { + Shipped::Every => (true, None), + Shipped::Hiding { recorded } => (false, recorded.cloned()), + }; + let shipped = tokio::task::spawn_blocking(move || { + kind.shipped_in(&root, &patched, every, recorded.as_ref()) }) .await .map_err(std::io::Error::other)??; @@ -2330,6 +2625,7 @@ pub(super) async fn gem_platform_service_copy( copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, + recorded: Option<&std::collections::BTreeMap>, warnings: &mut Vec, ) -> Result, Box> { let cfg = service @@ -2338,7 +2634,7 @@ pub(super) async fn gem_platform_service_copy( let stage = stage_dir_for(copy_dir); let _ = remove_tree(&stage).await; let (staged, built) = - match stage_platform_builds(cfg, record, name, platforms, builds, &stage).await { + match stage_platform_builds(cfg, record, name, platforms, builds, &stage, recorded).await { Ok(staged) => staged, Err(outcome) => { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; @@ -2473,6 +2769,76 @@ async fn shipped_rules_warning(project_root: &Path, copy_rel: &str) -> Option], + files: &HashMap, +) -> Option { + let copy_dir = copy_dir.to_path_buf(); + let patched = patched_paths(files); + // Each platform's tree with the files its own patch rewrites (the + // gem's patch stands in for a platform the run has no patch for). + let trees: Vec<(String, Vec)> = platforms + .iter() + .map(|platform| { + let own = builds.iter().find(|build| build.platform == platform); + let patched = own.map_or_else( + || patched.clone(), + |build| patched_paths(&build.record.files), + ); + (platform.clone(), patched) + }) + .collect(); + let shipped = tokio::task::spawn_blocking(move || { + let kind = ShippedFile::Gitattributes; + if trees.is_empty() { + let found = kind.shipped_in(©_dir, &patched, false, None)?; + return Ok(found.into_iter().map(|(_, rel)| rel).collect()); + } + let mut shipped: Vec = Vec::new(); + for (platform, patched) in &trees { + let found = kind.shipped_in(©_dir.join(platform), patched, false, None)?; + shipped.extend( + found + .into_iter() + .map(|(_, rel)| format!("{platform}/{rel}")), + ); + } + Ok::<_, std::io::Error>(shipped) + }) + .await + .ok()? + .ok()?; + if shipped.is_empty() { + return None; + } + Some(VendorWarning::new( + COPY_GITATTRIBUTES, + format!( + "git may change the bytes of files of the vendored copy at {copy_rel} at commit or \ + checkout: a `.gitattributes` the gem ships ({}) still applies inside it, so a \ + fresh clone can fail `vendor --check`. Delete {copy_rel} and run `socket-patch scan \ + --mode vendored` again to vendor the copy without those rules, then commit it", + super::npm_dir::summarize_rules(&shipped) + ), + )) +} + /// 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. @@ -2491,7 +2857,7 @@ async fn preview_platform_builds( .ok_or_else(|| Box::new(super::service_fetch::required()))?; let scratch = tempfile::tempdir() .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; - stage_platform_builds(cfg, record, name, platforms, builds, scratch.path()) + stage_platform_builds(cfg, record, name, platforms, builds, scratch.path(), None) .await .map(|_| ()) } @@ -2540,6 +2906,7 @@ async fn materialise_patched_copy( copy_dir, uuid_dir, unwind_uuid_dir, + None, warnings, ) .await?; @@ -12784,6 +13151,17 @@ mod tests { } fn git(root: &Path, args: &[&str]) { + git_with_autocrlf(root, "false", args); + } + + /// Clone the commit of `root` into `dest`, checked out under + /// `core.autocrlf` = `autocrlf`. + fn clone(root: &Path, autocrlf: &str, dest: &Path) { + let dest = dest.to_string_lossy(); + git_with_autocrlf(root, autocrlf, &["clone", "-q", ".", &dest]); + } + + fn git_with_autocrlf(root: &Path, autocrlf: &str, args: &[&str]) { let git = crate::utils::process::resolve_tool("git").expect("git"); let out = std::process::Command::new(git) .arg("-C") @@ -12791,7 +13169,8 @@ mod tests { .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(["-c", &format!("core.autocrlf={autocrlf}")]) + .args(["-c", "commit.gpgsign=false"]) .args(args) .output() .expect("git runs"); @@ -12990,6 +13369,167 @@ mod tests { ); } + /// #2483: a `.gitattributes` the gem ships (solargraph's + /// `*.rb text eol=lf`, over files with CRLF line endings) wins over + /// the uuid dir's `* -text` for the files below it, so git commits + /// other bytes than the ledger records and every clone fails the + /// check. Each one whose rules convert a file of the copy is + /// emptied in it, at any depth, and reported once. One that + /// converts nothing (`merge=ours`, a rule that matches no file) and + /// one the patch rewrites keep their bytes. A clone of the commit + /// holds the recorded bytes, with and without `core.autocrlf`, a + /// second run is in sync, and `repair`'s restore reproduces the + /// same tree. + #[tokio::test] + async fn a_gitattributes_the_gem_ships_is_emptied_in_the_copy() { + const CRLF: &str = "lib/rack/crlf.rb"; + const NESTED: &str = "bin/.gitattributes"; + const TOOL: &str = "bin/tool"; + const MERGE: &str = "lib/rack/.gitattributes"; + const MERGE_RULES: &[u8] = b"version.rb merge=ours\n"; + const TEMPLATE: &str = "lib/site_template/.gitattributes"; + const TEMPLATE_RULES: &[u8] = b"*.md text eol=lf\n"; + const PATCHED_ATTRS: &str = "ext/.gitattributes"; + let (_tmp, root, mut record, _server, cfg) = project_serving(&[ + (".gitattributes", b"*.rb text eol=lf\n"), + (CRLF, b"a\r\nb\r\n"), + (NESTED, b"* text=auto\n"), + (TOOL, b"#!/usr/bin/env ruby\r\n"), + (MERGE, MERGE_RULES), + ("lib/rack/version.rb", b"VERSION = 1\n"), + (TEMPLATE, TEMPLATE_RULES), + ("lib/site_template/index.txt", b"site\r\n"), + (PATCHED_ATTRS, b"# the patch's own\n"), + ]) + .await; + record.files.insert( + PATCHED_ATTRS.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"*.c text\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_gitattributes_neutralized") + .collect(); + assert_eq!(neutralized.len(), 1, "{warnings:?}"); + for file in [".gitattributes", NESTED] { + assert!(neutralized[0].detail.contains(file), "{neutralized:?}"); + } + for file in [PATCHED_ATTRS, TEMPLATE, MERGE] { + assert!(!neutralized[0].detail.contains(file), "{neutralized:?}"); + } + let emptied = |copy: &Path| { + for file in [".gitattributes", NESTED] { + assert_eq!(std::fs::read(copy.join(file)).unwrap(), b"", "{file}"); + } + for (file, rules) in [(TEMPLATE, TEMPLATE_RULES), (MERGE, MERGE_RULES)] { + assert_eq!( + std::fs::read(copy.join(file)).unwrap(), + rules, + "{file}: a `.gitattributes` that converts no file of the copy is the \ + gem's data" + ); + } + assert_eq!( + std::fs::read(copy.join(PATCHED_ATTRS)).unwrap(), + b"# the patch's own\n" + ); + }; + emptied(©(&root)); + 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); + + // The commit holds the bytes the ledger recorded: a clone + // passes the check, whatever its line-ending setting. + git(&root, &["add", "-A"]); + git(&root, &["commit", "-q", "-m", "vendor"]); + let clones = tempfile::tempdir().unwrap(); + for autocrlf in ["false", "true"] { + let cloned = clones.path().join(autocrlf); + clone(&root, autocrlf, &cloned); + for (file, bytes) in [ + (CRLF, &b"a\r\nb\r\n"[..]), + (TOOL, b"#!/usr/bin/env ruby\r\n"), + ] { + assert_eq!( + std::fs::read(cloned.join(copy_rel()).join(file)).unwrap(), + bytes, + "autocrlf={autocrlf}: {file}" + ); + } + assert_eq!( + check_vendored_artifact(&cloned, &entry, &record).await, + ArtifactHealth::Healthy, + "autocrlf={autocrlf}" + ); + } + + 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 + /// `.gitattributes` 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_gitattributes_an_earlier_release_recorded() { + const SHIPPED: &[u8] = b"*.rb text eol=lf\n"; + let (_tmp, root, record, _server, cfg) = project_serving(&[ + (".gitattributes", SHIPPED), + ("lib/rack/crlf.rb", b"a\r\nb\r\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(".gitattributes"), SHIPPED) + .await + .unwrap(); + entry.artifact.file_inventory = Some( + crate::vendor::verify::compute_dir_inventory(©(&root)) + .await + .unwrap(), + ); + + 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(".gitattributes")) + .await + .unwrap(), + SHIPPED + ); + 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. @@ -13052,6 +13592,173 @@ mod tests { assert!(!hides("/tmp\n", &["lib/tmp.rb"])); } + /// The same copy in the checkout of a project that upgraded: an + /// in-sync run says that a `.gitattributes` inside the copy still + /// converts a file of it, and names what vendors it afresh. The + /// copy and its ledger inventory agree as they are, so nothing in + /// it changes. Deleting the copy, as the advisory says, has the + /// next run vendor it with the file emptied, and the advisory is + /// gone. A copy whose shipped rules convert nothing is not named. + #[tokio::test] + async fn a_shipped_gitattributes_an_earlier_release_kept_is_reported() { + const SHIPPED: &[u8] = b"*.rb text eol=lf\n"; + const QUIET: &str = "lib/rack/.gitattributes"; + let (_tmp, root, record, _server, cfg) = project_serving(&[ + (".gitattributes", SHIPPED), + ("lib/rack/crlf.rb", b"a\r\nb\r\n"), + (QUIET, b"version.rb merge=ours\n"), + ]) + .await; + let (mut entry, _) = vendor_and_persist(&root, &record, &cfg).await; + let (_, _, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); + assert_eq!(warnings, [], "a copy vendored now holds no such rules"); + + // As the earlier release left it: the gem's rules, as shipped. + let attrs = copy(&root).join(".gitattributes"); + tokio::fs::write(&attrs, SHIPPED).await.unwrap(); + entry.artifact.file_inventory = Some( + crate::vendor::verify::compute_dir_inventory(©(&root)) + .await + .unwrap(), + ); + ts::persist(&root, PURL, entry).await; + for dry_run in [true, false] { + let (again, entry, warnings) = + unwrap_done(vendor(&root, &record, &cfg, dry_run).await); + assert!(again.success && entry.is_none(), "{:?}", again.error); + let [warning] = warnings.as_slice() else { + panic!("one advisory (dry_run={dry_run}): {warnings:?}"); + }; + assert_eq!(warning.code, "vendor_gem_copy_gitattributes"); + assert!(warning.detail.contains("(.gitattributes)"), "{warning:?}"); + assert!( + warning.detail.contains(&format!("Delete {}", copy_rel())), + "{warning:?}" + ); + assert_eq!(tokio::fs::read(&attrs).await.unwrap(), SHIPPED); + } + + // The remedy: without the copy, the run vendors it afresh. + tokio::fs::remove_dir_all(copy(&root)).await.unwrap(); + let (entry, warnings) = vendor_and_persist(&root, &record, &cfg).await; + assert!( + ts::has_warning(&warnings, "vendor_gem_gitattributes_neutralized"), + "{warnings:?}" + ); + assert_eq!(tokio::fs::read(&attrs).await.unwrap(), b""); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + let (_, _, warnings) = unwrap_done(vendor(&root, &record, &cfg, false).await); + assert_eq!(warnings, []); + } + + /// Which shipped `.gitattributes` converts a file is decided as git + /// decides it under the uuid dir's `* -text`: each rule here is + /// committed below that file and cloned, with and without + /// `core.autocrlf`, and git changes a file's bytes exactly when + /// the rule is called a conversion. The rules git only applies + /// with a filter driver or an encoding it knows are judged by the + /// reader alone. + #[test] + fn a_shipped_gitattributes_is_read_as_git_reads_it() { + const FILES: [(&str, &[u8]); 3] = [ + ("crlf.rb", b"a\r\n$Id$\r\n"), + ("lf.rb", b"a\nb\n"), + ("sub/deep.rb", b"a\r\nb\r\n"), + ]; + // (the rules, whether they convert a file, whether git is asked) + let cases: &[(&str, bool, bool)] = &[ + ("*.rb text eol=lf\n", true, true), + ("*.rb text\n", true, true), + ("*.rb\ttext=auto\n", true, true), + ("*.rb text eol=crlf\n", true, true), + ("*.rb !text\n", true, true), + ("*.rb !text eol=lf\n", true, true), + ("*.rb ident\n", true, true), + ("sub/* text\n", true, true), + ("/crlf.rb text\n", true, true), + ("\"crlf.rb\" text\n", true, true), + ("* -text\n*.rb text\n", true, true), + ("*.rb binary text\n", true, true), + ("\u{feff}*.rb text\n", true, true), + (" *.rb text\r\n", true, true), + ("*.rb !text=auto\n", true, true), + ("\"cr\\154f.rb\" text\n", true, true), + ("\"#crlf.rb\" text\n\"\\143rlf.rb\" ident\n", true, true), + ("[[:alpha:]]rlf.rb text\n", true, true), + ("*.RB text\n", true, false), + ("*.{rb text\n", true, false), + ("*.rb filter=lfs\n", true, false), + ("*.rb working-tree-encoding=UTF-16LE\n", true, false), + ("*.rb eol=lf\n", false, true), + ("*.rb eol=crlf\n", false, true), + ("*.rb crlf\n", false, true), + ("*.rb -text\n", false, true), + ("*.rb -text eol=lf\n", false, true), + ("*.rb binary\n", false, true), + ("*.rb text binary\n", false, true), + ("*.rb text\n* -text\n", false, true), + ("*.rb text\n*.rb -text=auto\n", false, true), + ("\"#crlf.rb\" text\n", false, true), + ("\"!crlf.rb\" text\n", false, true), + ("\"crlf.rb text\n", false, true), + ("*.rb !filter !ident -ident\n", false, true), + ("*.rb merge=ours diff=ruby linguist-vendored\n", false, true), + ("*.md text eol=lf\n", false, true), + ("sub/ text\n", false, true), + ("sub text\n", false, true), + ("/deep.rb text\n", false, true), + ("!*.rb text\n", false, true), + ("# *.rb text\n", false, true), + ("[attr]mine text\n", false, true), + ("*.rb -filter\n", false, false), + ]; + let names: Vec<&str> = FILES.iter().map(|(name, _)| *name).collect(); + for (rules, converts, _) in cases { + assert_eq!(converts_a_file(rules, &names), *converts, "{rules:?}"); + } + + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("project"); + std::fs::create_dir_all(&root).unwrap(); + if ts::git_project(&root, "").is_none() { + return; // no git to ask + } + let asked: Vec<_> = cases.iter().filter(|case| case.2).collect(); + let uuid_dir = root.join("uuid"); + for (at, (rules, _, _)) in asked.iter().enumerate() { + let tree = uuid_dir.join(at.to_string()); + std::fs::create_dir_all(tree.join("sub")).unwrap(); + std::fs::write(tree.join(".gitattributes"), rules).unwrap(); + for (name, bytes) in FILES { + std::fs::write(tree.join(name), bytes).unwrap(); + } + } + std::fs::write( + uuid_dir.join(".gitattributes"), + crate::vendor::npm_dir::UUID_GITATTRIBUTES, + ) + .unwrap(); + git(&root, &["add", "-A"]); + git(&root, &["commit", "-q", "-m", "trees"]); + let mut changed = vec![false; asked.len()]; + for autocrlf in ["false", "true"] { + let cloned = tmp.path().join(autocrlf); + clone(&root, autocrlf, &cloned); + for (at, changed) in changed.iter_mut().enumerate() { + let tree = cloned.join("uuid").join(at.to_string()); + *changed |= FILES + .iter() + .any(|(name, bytes)| std::fs::read(tree.join(name)).unwrap() != *bytes); + } + } + for ((rules, converts, _), changed) in asked.iter().zip(changed) { + assert_eq!(changed, *converts, "git, for {rules:?}"); + } + } + /// 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 @@ -14893,6 +15600,190 @@ mod tests { ); } + /// #2483: a prebuild that ships a `.gitattributes` of its own whose + /// rules convert a file of its tree would have git commit other + /// bytes than the ledger records. It is emptied in the copy and + /// reported; the check passes, a second run is in sync and + /// `repair`'s restore reproduces the tree. A copy an earlier + /// release vendored, whose inventory records the file as shipped, + /// is restored as that release wrote it. + #[tokio::test] + async fn a_gitattributes_a_prebuild_ships_is_emptied_in_the_copy() { + const ATTRS: &str = ".gitattributes"; + const SHIPPED: &[u8] = b"*.rb text eol=lf\n"; + const CRLF: &str = "lib/nokogiri/crlf.rb"; + let shipping = |platform: &'static str| Served { + gem: Some(make_gem(&[ + (RB, RB_PATCHED), + (SO, platform.as_bytes()), + (ATTRS, SHIPPED), + (CRLF, &b"a\r\nb\r\n"[..]), + ])), + ..served(platform) + }; + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, "").is_none() { + return; // no git, nothing to commit + } + let (_server, cfg) = service(UUID, &[shipping(DARWIN), shipping(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let neutralized: Vec<_> = warnings + .iter() + .filter(|w| w.code == "vendor_gem_gitattributes_neutralized") + .collect(); + assert_eq!(neutralized.len(), 1, "{warnings:?}"); + for platform in [DARWIN, LINUX] { + let file = format!("{platform}/{ATTRS}"); + assert!(neutralized[0].detail.contains(&file), "{neutralized:?}"); + } + ts::persist(&root, NOKO, entry.expect("a ledger entry")).await; + let mut entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + + let copy = root.join(rel(UUID)); + let holds = |copy: &Path, bytes: &[u8]| { + for platform in [DARWIN, LINUX] { + let file = copy.join(platform).join(ATTRS); + assert_eq!(std::fs::read(file).unwrap(), bytes, "{platform}"); + } + }; + holds(©, b""); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + let (again, rerun_entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success && rerun_entry.is_none(), "{:?}", again.error); + + tokio::fs::remove_dir_all(copy.join(LINUX)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + holds(©, b""); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + // The entry as an earlier release wrote it: the file as shipped. + for platform in [DARWIN, LINUX] { + std::fs::write(copy.join(platform).join(ATTRS), SHIPPED).unwrap(); + } + entry.artifact.file_inventory = Some( + crate::vendor::verify::compute_dir_inventory(©) + .await + .unwrap(), + ); + tokio::fs::remove_dir_all(copy.join(LINUX)).await.unwrap(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + holds(©, SHIPPED); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + + // An in-sync run over that copy names the files left as shipped. + ts::persist(&root, NOKO, entry).await; + let (again, rerun_entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success && rerun_entry.is_none(), "{:?}", again.error); + let [warning] = warnings.as_slice() else { + panic!("one advisory: {warnings:?}"); + }; + assert_eq!(warning.code, "vendor_gem_copy_gitattributes"); + for platform in [DARWIN, LINUX] { + let file = format!("{platform}/{ATTRS}"); + assert!(warning.detail.contains(&file), "{warning:?}"); + } + holds(©, SHIPPED); + } + + /// The stub gemspec written into each platform tree is a file of + /// the copy like any other: a shipped rule that names only it + /// (`*.gemspec text`) converts a file of the tree, so the + /// `.gitattributes` is emptied. + #[tokio::test] + async fn a_prebuilds_gitattributes_over_the_stub_gemspec_is_emptied() { + let shipping = |platform: &'static str| Served { + gem: Some(make_gem(&[ + (RB, RB_PATCHED), + (SO, platform.as_bytes()), + (".gitattributes", &b"*.gemspec text\n"[..]), + ])), + ..served(platform) + }; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[shipping(DARWIN), shipping(LINUX)]).await; + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + ts::has_warning(&warnings, "vendor_gem_gitattributes_neutralized"), + "{warnings:?}" + ); + for platform in [DARWIN, LINUX] { + let tree = root.join(rel(UUID)).join(platform); + assert!(tree.join("nokogiri.gemspec").is_file(), "{platform}"); + assert_eq!(std::fs::read(tree.join(".gitattributes")).unwrap(), b""); + } + } + + /// A `.gitattributes` a platform's own patch rewrites is that + /// patch's, kept as it has it, whether or not the patch the gem is + /// vendored through lists the file: an in-sync run does not call + /// it one an earlier release left behind. + #[tokio::test] + async fn a_gitattributes_a_platform_patch_rewrites_is_not_reported() { + const ATTRS: &str = ".gitattributes"; + const PATCHED_RULES: &[u8] = b"*.rb text\n"; + let shipping = |platform: &'static str| Served { + gem: Some(make_gem(&[ + (RB, RB_PATCHED), + (SO, platform.as_bytes()), + (ATTRS, PATCHED_RULES), + ])), + ..served(platform) + }; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[shipping(DARWIN), shipping(LINUX)]).await; + let mut records = build_records(&record); + for (_, build) in &mut records { + build.files.insert( + ATTRS.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(b"*.c text\n"), + after_hash: compute_git_sha256_from_bytes(PATCHED_RULES), + mode: None, + }, + ); + } + let builds: Vec> = records + .iter() + .map(|(platform, record)| GemBuildPatch { platform, record }) + .collect(); + let installed = not_installed(&root); + let (result, entry, warnings) = + unwrap_done(vendor_with(&root, &installed, &record, &builds, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + !ts::has_warning(&warnings, "vendor_gem_gitattributes_neutralized"), + "{warnings:?}" + ); + ts::persist(&root, NOKO, entry.expect("a ledger entry")).await; + let (again, rerun_entry, warnings) = + unwrap_done(vendor_with(&root, &installed, &record, &builds, &cfg, false).await); + assert!(again.success && rerun_entry.is_none(), "{:?}", again.error); + assert_eq!(warnings, [], "the patch's own file is not a leftover"); + for platform in [DARWIN, LINUX] { + let file = root.join(rel(UUID)).join(platform).join(ATTRS); + assert_eq!(std::fs::read(file).unwrap(), PATCHED_RULES, "{platform}"); + } + } + /// A platform names a directory under the vendored dir, and the lock /// it is read from is committed data: one that is no plain directory /// name is refused before anything is asked or written. diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 87b968378..6d8e1d639 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -301,6 +301,7 @@ pub async fn restore( &stage, uuid_dir, true, + entry.artifact.file_inventory.as_ref(), &mut warnings, ) .await diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1425438fa..7bc44e4e3 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5801,6 +5801,24 @@ keeps the gem's own `.gitignore` as shipped. When that still hides a file, the r writes the two files says so (`vendor_gem_copy_gitignored`); `git add -f` on the directory it names commits the whole copy. +A `.gitattributes` the gem ships inside itself works the same way: for the files below it, +its rules win over the one written beside the gem. `solargraph` ships `*.rb text eol=lf` +together with `.rb` files that have CRLF line endings, so git would commit those files with +LF and every clone would hold other bytes than the vendor ledger records. Vendored mode +empties each such file whose rules turn a conversion on for a file of the gem +(`vendor_gem_gitattributes_neutralized` names them): `text` in any form but `-text`, a +`filter` or a `working-tree-encoding` with a value, and `ident`. One that converts nothing +(`merge=ours`, `eol` without `text`, a pattern that matches no file of the gem) and one the +patch itself changes are kept as they are. Where git's answer depends on the checkout, +the rule counts as a conversion: letter case is ignored when a pattern is matched, as git +does on macOS and Windows. + +A gem that 5.2.0 or earlier vendored keeps such a `.gitattributes` as shipped, and `repair` +restores it that way. Each vendored run over the copy says so +(`vendor_gem_copy_gitattributes`). To fix it, delete the directory the warning names, run +`socket-patch scan --mode vendored` again and commit the result: the copy is vendored afresh +with the file emptied. + ## Ruby gems: gems vendored mode refuses Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing