diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml index dfb5e1475..c28b174c8 100644 --- a/.github/workflows/bazel-maven.yml +++ b/.github/workflows/bazel-maven.yml @@ -1,14 +1,19 @@ name: Bazel patch compatibility (Maven) # The Maven flows of the real-Bazel tests (`maven::` in `e2e_bazel_build`): -# a hosted patch of an artifact in a workspace whose rules_jvm_external hub -# builds that artifact from a pinned lock, on each Bazel release below. The +# a hosted and a vendored patch of an artifact in a workspace whose +# rules_jvm_external hub builds that artifact from a pinned lock, on each +# Bazel release below. The # patch is one block in MODULE.bazel that puts a repository with the # patched jar in the place of the hub's own (`override_repo`): the flows # hold the block's text, the patched build and its sha256 check, the undo, # a hosted scan that finds the artifact in the hub's lock, a version bump -# of the patched artifact, and a hub the block cannot patch. -# bazel-compatibility.yml holds the legs and what every ecosystem +# of the patched artifact, and a hub the block cannot patch. In vendored +# mode that repository is a directory of the checkout with the committed +# jar: the flows hold the build from the checkout alone with no host to +# ask, the audit of the committed jar, the undo, and the way from hosted +# to vendored and back. bazel-compatibility.yml holds the legs and what +# every ecosystem # shares; this file says when the Maven legs run and on which releases. # # Each major release has an era of its own, because the ruleset decides @@ -58,11 +63,14 @@ on: # pom walk under it (the hosted lane pins only where Maven selects the # patch's version), the crawler that says where the Maven local # repository is, lock discovery and the upstream restore of `rollback` - # (for a pom and for the block of MODULE.bazel), and what socket-patch - # reads and writes only in a Bazel workspace (`bazel/`: the hubs of - # MODULE.bazel, their locks and the block). Nothing another ecosystem's - # flow owns is here, so a change to one ecosystem starts that - # ecosystem's legs only. + # (for a pom and for the block of MODULE.bazel), the vendored Maven + # backend, which writes the hub's jar and its entry, the dispatch that + # hands a vendored command the hub's declines (vendor/refusals.rs), and what + # socket-patch reads and writes only in a Bazel workspace (`bazel/`: the + # hubs of MODULE.bazel, their locks and the block). Nothing another + # ecosystem's flow owns is here but that dispatch, which the Composer + # legs watch too, so a change to one ecosystem starts that ecosystem's + # legs only. # # What it does not cover: shared engine code (`rewrite_maven_pom` is in # patch/redirect/mod.rs, the file of every ecosystem's rewriter; hosted/, @@ -88,6 +96,8 @@ on: - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' + - 'crates/socket-patch-core/src/vendor/maven_repo.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' push: branches: [main] @@ -114,6 +124,8 @@ on: - 'crates/socket-patch-core/src/vex/discover/bazel_maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/maven.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/bazel_maven.rs' + - 'crates/socket-patch-core/src/vendor/maven_repo.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 795dba303..bc390b2e6 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -422,7 +422,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Throttling: bounded retry, then a reported failure.** Every patch-API JSON call (the batch query, the per-package patch lists, patch views and VEX record fetches, hosted package references) retries an HTTP `429` or `503` answer up to 3 times (`SOCKET_API_MAX_RETRIES=`, `0`-`10`; `0` = no retry). The wait honors `Retry-After` (delta-seconds or HTTP-date); a `Retry-After` over 30 s is not waited out — the answer is final at once — and one under the jittered first backoff step (`0`, a past date) waits that step instead. Without one it backs off 0.5 s / 1 s / 2 s (each step up to 8 s, with jitter in its upper half). All retries in one run share a 60 s wall-clock window that opens with the run's first retry: a retry whose wait would end after it closes is refused and the answer is final. Parallel requests wait in parallel, so each still gets its retries while the run adds at most about 60 s. Nothing else is retried (401/403 still drive the proxy fallback on the first answer; the public proxy's permanent `503 "Patch API is not configured"` is never retried on any path — the batch query still degrades to the per-package path at once, and a per-package lookup or patch view answering it is the same non-throttle failure it always was, which on the legacy per-package path leaves that package unanswered, see above), and a retried answer folds exactly where the first attempt's would have, so output is identical to an unthrottled run's. A request still throttled after that is a failure in the channel its siblings use: a failed batch is the human `Warning: API batch of failed: ` line and, under `--json`, a run-level `warnings[]` entry `{code: "api_batch_failed", detail: "API batch of failed: "}` (additive; `status` stays `success`, exit 0 — the other batches' packages are reported); a failed per-package patch-list query in the agent / hosted / vendored flows is the human `Warning: could not fetch details for : ` line and, under `--json`, `{code: "patch_details_failed", detail: "could not fetch details for : "}`. When every batch (or every patch-list query) fails, the existing all-failed error envelope and exit 1 apply. The error names the exhausted retry: `Rate limit exceeded (HTTP 429, gave up after 3 retries). Please try again later.` / `API request failed with status 503: (gave up after 3 retries)` (or `(Retry-After s exceeds the 30 s retry cap)` / `(the run's 60 s retry window has closed)`); with retries off it is the pre-retry text. On the token-less legacy per-package proxy path (a proxy without `POST /patch/batch`), a package still throttled (429 / over-capacity 503) after its retries is an unanswered package (see "No patches" needs an answer above): the batch's answered packages are used and it is reported as `patch_lookup_failed` (`partialFailure`, exit 1); when it leaves no package of its batch answered, the batch fails through the batch-failure channel above. Only a PURL the service itself refuses (its own `400`) is skipped individually. Pinned by `tests/scan_api_retry_e2e.rs` and the core crate's `tests/api_retry_e2e.rs`. -**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". +**Lockfile supplement (v3.4)**: `scan` discovery is no longer limited to installed trees. The project's lockfiles (`package-lock.json`/`npm-shrinkwrap.json`, `pnpm-lock.yaml` v9, `yarn.lock` classic + berry, `bun.lock`, `vlt-lock.json` (registry nodes, Socket-hosted pins included; vendored `file` nodes are left to the vendor ledger), `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`, `uv.lock`/`poetry.lock`/pinned `requirements.txt`) are inventoried and dependencies with NO installed copy join discovery — counts, the API lookup, the rows of what a hosted or vendored run patches (an agent or report-only run, which patches installed copies, gets a stderr note that they are not installed), and the prune "scanned" set (a wiped node_modules no longer prunes lockfile-listed entries). JSON gains a top-level `lockfileOnlyPackages` count and an additive `notInstalled: true` on matching `packages[]` entries. Agent mode partitions lockfile-only patches out BEFORE download (calm `skipped`/`package_not_installed` events — never an error exit, never a manifest write); vendored mode passes them through to the vendor engine's server download. Vendored-ledger entries likewise stay discoverable on a fresh clone (the committed artifact is the dependency). The `Gemfile.lock` inventory lists a gem by its ruby-platform entry; a gem the lock resolves ONLY as precompiled platform builds (`nokogiri (1.18.10-arm64-darwin)`, no `nokogiri (1.18.10)`) joins the supplement of a hosted run alone (`scan` / `get --mode hosted`, and the in-memory hosted engine), which can redirect it to its per-platform prebuilds from the lock; agent and vendored runs see it only through an installed copy, as before. Global scans (`--global`) get no supplement. **Rush monorepos** (no root lockfile, `rush.json` present): the npm-lock inventory falls back to the Rush source-of-truth locks — `common/config/rush/pnpm-lock.yaml` plus every `common/config/subspaces/*/pnpm-lock.yaml` (`read_dir`-sorted, repo-relative paths preserved) — so a Rush repo's dependencies still join discovery. **Plug'n'Play layouts are an explicit refusal, not an empty inventory**: a `.pnp.*` loader means the npm packages are structurally unreachable in EVERY mode (under yarn PnP the installed-tree crawl is empty too — no `node_modules/`), so `scan` surfaces an additive top-level `warnings[]` array (`{code, detail}` objects, omitted when empty) carrying `yarn_pnp_unsupported` (same code as apply's refusal; remedy `yarn patch `) or `pnpm_pnp_unsupported` (pnpm's `node-linker=pnp` twin; pnpm remedies), plus a stderr `Warning: …` line on the human path. Exit code and `status` are deliberately unchanged (exit 0 / `success` — the same posture as hosted refusals, which exit 0 with no `applied` event); the warning is the machine-readable signal that nothing was checked. Pinned by `tests/e2e_safety_yarn_pnp.rs`. **A Bundler lock socket-patch cannot read is likewise a warning, not an empty inventory**: when the project holds gem files but bundler loads no `Gemfile.lock` / `gems.locked` socket-patch reads (`BUNDLE_GEMFILE` or bundler 4's `BUNDLE_LOCKFILE` naming another file, or a `Gemfile` + `gems.rb` twin, whose loaded pair depends on the bundler major that runs), `warnings[]` carries the additive `gem_lock_unsupported` (detail names the setting or the twin) and its lockfile-only gems are not discovered. Same exit-0 / `success` posture. **The jars of a pinned rules_jvm_external hub join the supplement of a hosted run at the root of a Bazel workspace (additive)**: `scan --mode hosted` (the inferred default included) and `get --mode hosted` take, for each hub of the root `MODULE.bazel` that names a lock (`maven_install.json`), the jar without a classifier of each artifact the hub fetches, at the lock's version, as a Maven package of the project: it counts in `scannedPackages`, and in `lockfileOnlyPackages` with `notInstalled: true` unless a crawl found that version installed, and a patch found for it is pinned in the block of `MODULE.bazel` (the `maven_bazel_*` rows below). A jar whose repository has no known name is such a package too (a patch found for it gets `maven_bazel_artifact`). No jar is guessed for a hub that was not read with certainty: `warnings[]` then carries `maven_bazel_hub_not_read` once, and the jars of the hubs that were read are still looked up. A patch of a hub's jar is a patch of the run like any other, so the run writes for it what `get --mode hosted` writes in that checkout: beside a Gradle build the hosted Gradle pin too (`settings.gradle` and the files under `.socket/gradle/`, with that pin's warnings), and beside a `pom.xml` what the pom lane pins or says (`redirect_maven_version_not_selected`, `redirect_maven_selection_undetermined`, which speak of `pom.xml` alone). **A stale entry of the block is taken out by `scan --mode hosted` (additive)**: when every hub was read and none fetches the jar of an entry at its version any more (the lock moved on, so Bazel stops at the entry), the scan restores it before the rewrite as the withdrawn-pin sweep above restores a pin: the entry alone, under the apply lock, `--dry-run` previewing it, one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "maven_bazel_entry_stale"` and `details.mode: "hosted"`, also on a scan that finds no package; a pin of the same patch in a `pom.xml` or Gradle file stays; a restore that fails is the `redirect_withdrawn_restore_failed` warning. `get` takes no stale entry out, and no scan takes out a stale entry of vendored mode (a `local_repository` over `.socket/vendor/maven//`): its directory and its ledger entry are vendored mode's, so it stays for `rollback `, `remove ` or `vendor --revert`, which take all three out, and `vendor --check` names it. No other mode, no run whose `--ecosystems` leaves Maven out, no `--global` run and no run of a project below the Bazel root takes a package from a hub, gives that warning or takes a stale entry out: its packages are those of the run without the workspace. A run of a project in no Bazel workspace is, byte for byte, the run it was. See docs/ecosystems.md "Bazel workspaces: Maven". **Server artifact acquisition (v5.0)**: vendoring downloads the patched artifact for the selected UUID, including on a fresh checkout with no installed package. The CLI no longer downloads pristine packages, stages patch blobs, applies patches to vendor copies, or constructs archives. Backend lock and package-identity checks still run before acquisition; git and custom-registry Cargo sources are refused with `vendor_source_unsupported`. Healthy committed artifacts are reused offline. A changed UUID downloads a fresh server artifact; an unhealthy artifact at the recorded UUID uses the exact redownload procedure below, except that a directory copy whose ledger entry has no file inventory (vendored before v5.0) is rebuilt by its backend from a fresh verified download, and a missing or stale Bun workspace mirror over a healthy canonical tarball is rewritten from that tarball by the backend; those cases report the backend's own failure codes. @@ -430,7 +430,7 @@ Pinned by `tests/scan/scan_proxy_fallback_e2e.rs`, `tests/cli/api_client_errors_ **Rewritten file ownership**: a hosted or vendored rewrite of a project file that already exists (its lockfiles, package manifests and `.npmrc`, and their `rollback` / `remove` / `vendor --revert` restores; not socket-patch's own `.socket/` records) replaces it with a staged file that keeps the old file's permission bits and, best-effort, its owner and group, like npm's write-file-atomic. A root run (a Docker bind mount, `sudo`) leaves a user's `poetry.lock` owned by that user. An unprivileged run can't give a file to another user; it keeps the old group when it belongs to that group, and otherwise the file takes the runner's owner and group, with no warning. -**Vendored group commit (v5.0)**: `vendor`, `scan --mode vendored` and `get --mode vendored` capture every lockfile / manifest / config edit and every ledger save of the run in memory (reads inside the run see them) and commit them ONCE after the per-package loop — including the packages that succeeded in a run where others failed, so a completed run leaves the same files per-package commits would. Captured: every file under the project root outside `.socket/` and outside any git directory (`.socket` and `.git` are matched under every spelling a filesystem folds onto them, such as `.GIT` or `git~1`; no backend writes into a git directory), plus `.socket/vendor/state.json` and `.socket/vendor/redirect-state.json`; artifacts are written directly (see the durability note). A multi-file commit goes through a roll-forward journal, `.socket/vendor/.commit-journal.json` (the new bytes of every changed file, plus the bytes each replaces and their sha256; deleted once the commit completes). **Crash semantics**: before the journal is durable, nothing is committed — the lockfiles and ledgers are the pre-run ones and the run's artifacts are unreferenced orphans; after it, the next command that takes the apply lock replays the journal before reading anything (files already at their new bytes are left alone), so a locked command never observes a half-committed run. **A replay is never silent**: the command that performed it prints `Warning: an interrupted vendored run's commit was finished from its journal: rolled forward ; …` on stderr (in every output mode, `--silent` and `--json` included), and under `--json` the envelope it goes on to print carries the same sentence as a `vendor_commit_recovered` entry in `warnings[]` (an error envelope printed before the command reached its own work may omit the entry; stderr always has the line). **`--dry-run` replays nothing**: a dry run that takes the lock and finds a journal exits 1 with the top-level error `vendor_commit_pending` (the message names the journal and the files it covers), having written nothing; the journal and every file it covers stay as the interruption left them, and the same command without `--dry-run` (or any other lock-taking command) finishes the commit. A journal that matches neither side of some file (edited by hand since the crash) is renamed to `.socket/vendor/.commit-journal.set-aside-.json` (keeping every file's pre-commit bytes) and stderr says what was done (`Warning: an interrupted vendored run's commit could not be finished as written: …`; under `--json` also a `vendor_commit_set_aside` entry in `warnings[]`): the edited files are never written over; when they all still carry the commit's own lines the rest of the commit is finished around them, when none of them does the files the crash had already replaced are put back to their pre-commit bytes, and otherwise nothing is applied. The journal is a file in the working tree, so a checkout can carry one that no crash wrote (a pull request can commit it); a replay therefore writes only what a commit could have journaled. A journal that is unreadable, names a path outside the captured set (an absolute path, a path with a `..` component, an artifact or any other uncaptured file under `.socket/`, anything inside a `.git` directory), or would write through a symbolic link is set aside with nothing applied, not even its other entries. A replay that fails on I/O keeps the journal and fails the lock acquire (`lock_io`, naming the journal). Read-only commands that take no lock (`vex`, `list`, and the lock-free `--dry-run` previews of `scan` and `get`) may observe the interrupted state until then. A re-vendor under a newer uuid removes the replaced uuid's dir only after the commit (its `vendor_stale_artifact_removed` event follows the run's per-package events), and a golang takeover removes the `.socket/go-patches/` copy only after the commit that repoints `go.mod`. A commit never renames over a symbolic link: when a changed file is a symlink, the whole commit is refused before anything is written, with the top-level error `redirect_symlinked_file_unsupported` (exit 1; a `--dry-run` predicts it with a `vendor_would_refuse_symlinked_file` advisory) — the artifact dirs the run's loop added under `.socket/vendor/` are removed, and every package it vendored is reported as a `failed` event with that code instead of `applied` (its per-package `skipped` advisories from the same run, such as `vendor_prebuilt_downloaded`, are dropped). A commit write failure is the top-level error `vendor_commit_failed` (exit 1; the pre-run lockfiles and ledger stay, the artifact dirs the run added are removed and its vendored packages are `failed` events with that code, the same way — unless putting back the files already replaced failed too, in which case the journal is kept, the next locked command finishes the commit, and the per-package events stand). `repair`, `vendor --revert` and `rollback` still save per entry. +**Vendored group commit (v5.0)**: `vendor`, `scan --mode vendored` and `get --mode vendored` capture every lockfile / manifest / config edit and every ledger save of the run in memory (reads inside the run see them) and commit them ONCE after the per-package loop — including the packages that succeeded in a run where others failed, so a completed run leaves the same files per-package commits would. Captured: every file under the project root outside `.socket/` and outside any git directory (`.socket` and `.git` are matched under every spelling a filesystem folds onto them, such as `.GIT` or `git~1`; no backend writes into a git directory), plus `.socket/vendor/state.json` and `.socket/vendor/redirect-state.json`; artifacts are written directly (see the durability note). A multi-file commit goes through a roll-forward journal, `.socket/vendor/.commit-journal.json` (the new bytes of every changed file, plus the bytes each replaces and their sha256; deleted once the commit completes). **Crash semantics**: before the journal is durable, nothing is committed — the lockfiles and ledgers are the pre-run ones and the run's artifacts are unreferenced orphans; after it, the next command that takes the apply lock replays the journal before reading anything (files already at their new bytes are left alone), so a locked command never observes a half-committed run. **A replay is never silent**: the command that performed it prints `Warning: an interrupted vendored run's commit was finished from its journal: rolled forward ; …` on stderr (in every output mode, `--silent` and `--json` included), and under `--json` the envelope it goes on to print carries the same sentence as a `vendor_commit_recovered` entry in `warnings[]` (an error envelope printed before the command reached its own work may omit the entry; stderr always has the line). **`--dry-run` replays nothing**: a dry run that takes the lock and finds a journal exits 1 with the top-level error `vendor_commit_pending` (the message names the journal and the files it covers), having written nothing; the journal and every file it covers stay as the interruption left them, and the same command without `--dry-run` (or any other lock-taking command) finishes the commit. A journal that matches neither side of some file (edited by hand since the crash) is renamed to `.socket/vendor/.commit-journal.set-aside-.json` (keeping every file's pre-commit bytes) and stderr says what was done (`Warning: an interrupted vendored run's commit could not be finished as written: …`; under `--json` also a `vendor_commit_set_aside` entry in `warnings[]`): the edited files are never written over; when they all still carry the commit's own lines the rest of the commit is finished around them, when none of them does the files the crash had already replaced are put back to their pre-commit bytes, and otherwise nothing is applied. The journal is a file in the working tree, so a checkout can carry one that no crash wrote (a pull request can commit it); a replay therefore writes only what a commit could have journaled. A journal that is unreadable, names a path outside the captured set (an absolute path, a path with a `..` component, an artifact or any other uncaptured file under `.socket/`, anything inside a `.git` directory), or would write through a symbolic link is set aside with nothing applied, not even its other entries. A replay that fails on I/O keeps the journal and fails the lock acquire (`lock_io`, naming the journal). Read-only commands that take no lock (`vex`, `list`, and the lock-free `--dry-run` previews of `scan` and `get`) may observe the interrupted state until then. A re-vendor under a newer uuid removes the replaced uuid's dir only after the commit (its `vendor_stale_artifact_removed` event follows the run's per-package events), and a golang takeover removes the `.socket/go-patches/` copy only after the commit that repoints `go.mod`. A commit never renames over a symbolic link: when a changed file is a symlink, the whole commit is refused before anything is written, with the top-level error `redirect_symlinked_file_unsupported` (exit 1; a `--dry-run` predicts it with a `vendor_would_refuse_symlinked_file` advisory) — the artifact dirs the run's loop added under `.socket/vendor/` are removed, and every package it vendored is reported as a `failed` event with that code instead of `applied` (its per-package `skipped` advisories from the same run, such as `vendor_prebuilt_downloaded`, are dropped). A commit write failure is the top-level error `vendor_commit_failed` (exit 1; the pre-run lockfiles and ledger stay, the artifact dirs the run added are removed and its vendored packages are `failed` events with that code, the same way — unless putting back the files already replaced failed too, in which case the journal is kept, the next locked command finishes the commit, and the per-package events stand). `repair`, `vendor --revert` and `rollback` still save per entry. One undo commits a group of its own (additive): that of a vendored Maven patch whose jar a pinned rules_jvm_external hub of a Bazel workspace takes too (an entry in the block of `MODULE.bazel`), run by `vendor --revert`, `rollback`, `remove` or a scan's prune. The files of the Maven or Gradle build and `MODULE.bazel` are captured and written together, through the journal when they are more than one: a write that fails puts the files already replaced back and fails that entry's undo with every file as it was (the journal is kept when they could not be put back, and the next locked command finishes the commit); a file among them that is a symbolic link fails it before anything is written; the vendored tree and the hub's directory are removed after the commit, and the ledger entry after that. A run that is killed between two of the files leaves the journal with nothing removed: the next locked command finishes the files, and the undo run again removes the rest. See docs/ecosystems.md "Bazel workspaces: Maven". `scan --sync` is sugar for `--mode agent --prune` — the canonical single-flag agent-mode bot invocation. `scan --json --sync` discovers, applies, and reconciles state in one pass. @@ -2453,7 +2453,7 @@ command's integration tests check its output. | `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. | | `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (` of packages could not be checked for patches (…): `); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. | | `offline_missing_sources` / `blob_corrupt` | `failed` (artifact-level: `details.{hash,state}`, no purl) | repair `--offline`: a blob the manifest references is absent (`state: "missing"`; `afterHash` blobs only, as `beforeHash` blobs are fetched on demand) or on disk with bytes that no longer hash to its name (`state: "corrupt"`: a line-ending-converting checkout, a truncated file; `afterHash` and `beforeHash` blobs). Nothing is fetched offline, so each is a failure of the run (exit 1; human: `Error: N blobs are missing|corrupt (offline mode - not downloading):` on stderr, even under `--silent`); a corrupt file is left in place. Online, both kinds are downloaded (a corrupt entry is replaced whole) and the `downloaded` / dry-run `verified` carrier adds `details.corrupt` (how many were corrupt) when non-zero. `apply` and `rollback` name a corrupt blob in their `apply_failed` / `rollback_failed` error (`blob is corrupt … Run \`socket-patch repair\``); they hash a blob only when about to write its bytes. | -| `cleanup_failed` | `skipped` (warning) | repair: an orphan-sweep pass (blobs, diff or package archives) failed mid-way (e.g. permission error). The run continues and exits 0; human mode carries the warning on stderr (not muted by `--silent`). v5.0: `rollback`'s default GC and `remove`'s GC surface the same condition in their run-level `warnings[]` (`remove`: also on stderr in human mode) — same posture, never affects the exit. | +| `cleanup_failed` | `skipped` (warning) | repair: an orphan-sweep pass (blobs, diff or package archives) failed mid-way (e.g. permission error). The run continues and exits 0; human mode carries the warning on stderr (not muted by `--silent`). v5.0: `rollback`'s default GC and `remove`'s GC surface the same condition in their run-level `warnings[]` (`remove`: also on stderr in human mode) — same posture, never affects the exit. A hosted `scan` / `get` gives it, in `warnings[]`, when its entry took the place of a vendored one in the block of a Bazel hub and the directory that vendored mode kept for that jar (`.socket/vendor/maven//`) could not be deleted. | | `rollback_failed` | `failed` | remove/rollback: file restore could not complete (rollback: no blocking file names a more specific code). The copy is left patched, as it was: restores are staged and deletes planned before the first file changes, and a failure puts the files already changed back (`apply_failed`'s rule; `Cannot roll back: - ` / `Failed to delete : `). | | `already_original` | `skipped` | rollback (v5.0): every file of the copy already matches its `beforeHash`. | | `hash_mismatch` / `file_not_found` / `missing_blob` | `failed` | rollback (v5.0): the copy's first blocking file drifted from both hashes, is missing, or its before-blob is unavailable (`details.filesVerified` names each file). | @@ -2708,19 +2708,19 @@ command's integration tests check its output. | `redirect_withdrawn_check_failed` | `warnings[]` (warning; human: `Warning: …`) | scan `--mode hosted`: the reference lookup for the uuids the lockfiles pin failed, so the run could not tell whether any was withdrawn. Every pin is kept; status and exit unchanged. See "Withdrawn pins". | | `redirect_withdrawn_restore_failed` | `warnings[]` (warning; human: `Warning: …` / `Error: …`) | scan `--mode hosted`: a pin whose patch is `withdrawn` / `not_found` could not be restored to its upstream registry entry (the restore refused it, writing the restored files failed, or the apply lock was held). The pin is kept and no `rolledBack` event is recorded for it; the detail names the remedy (`git checkout -- `, or re-run / `socket-patch rollback `). A write failure is one warning naming every pin it kept. Status and exit unchanged, unless the failed write could not put a file back: see `lockfile_write_failed`. Also for a stale entry of a Bazel workspace's block that could not be taken out (`maven_bazel_entry_stale`). | | `patch_withdrawn` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted`: the lockfile pinned a patch the server reports `withdrawn` or `not_found`; the pin was restored (dry run: would be) to its upstream registry entry. `reason` names the uuid and status. See "Withdrawn pins". | -| `maven_bazel_entry_stale` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the block in `MODULE.bazel` held an entry for a jar that no pinned rules_jvm_external hub fetches at that version any more, at which Bazel stops ("does not generate repository"); the entry was taken out (dry run: would be), and with the last entry the block. Only when every hub was read, and not in a root, or for a package, that the `socket.yml` policy filters. A pin of the same patch in another build's files (a `pom.xml`, the hosted Gradle index) stays. `reason` names the uuid. A restore that fails keeps the entry with a `redirect_withdrawn_restore_failed` warning; one that leaves a file half written stops the run (`lockfile_write_failed`, exit 1), also when the scan has no package. See the lockfile supplement and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_entry_stale` | `rolledBack` / `verified` (hosted event) | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the block in `MODULE.bazel` held an entry of hosted mode for a jar that no pinned rules_jvm_external hub fetches at that version any more, at which Bazel stops ("does not generate repository"); the entry was taken out (dry run: would be), and with the last entry the block. Only when every hub was read, and not in a root, or for a package, that the `socket.yml` policy filters. A pin of the same patch in another build's files (a `pom.xml`, the hosted Gradle index) stays, and so does a stale entry of vendored mode (the lockfile supplement says who takes that one out). `reason` names the uuid. A restore that fails keeps the entry with a `redirect_withdrawn_restore_failed` warning; one that leaves a file half written stops the run (`lockfile_write_failed`, exit 1), also when the scan has no package. See the lockfile supplement and docs/ecosystems.md "Bazel workspaces: Maven". | | `vendor_prebuilt_stub_invalid` | `failed` | RubyGems: the server stub lacks required attributes or is otherwise invalid; no local stub fallback is permitted. | -| `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, and Cargo vendored mode under a rules_rust crate hub, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` and out of the crates under `.socket/vendor/cargo`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | +| `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, Cargo vendored mode under a rules_rust crate hub, and Maven vendored mode, in a Bazel workspace (additive): the `.bazelignore` at the Bazel root, which keeps Bazel and gazelle out of the module copies under `.socket/vendor/golang` and `.socket/go-patches` out of the crates under `.socket/vendor/cargo`, and out of the jars vendored for a rules_jvm_external hub under `.socket/vendor/maven`, was not updated. It could not be read or written (a symbolic link or a directory in its place, a read-only directory, a read-only file). The detail names the line to add, or says that the lines of a copy that is gone can be deleted; the command's patch or undo stands and its exit code is unchanged. See docs/ecosystems.md "Bazel workspaces: `.bazelignore`". | | `redirect_cargo_bazel_config_unread` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_rust crate_universe hub (`crate.from_cargo` in `MODULE.bazel` or a file it includes, or `crates_repository` in the `WORKSPACE` file) reads the project's `Cargo.lock` or one of its `Cargo.toml` files, or may read them (its `cargo_lockfile` or `manifests` is not written out as strings, or a use of the extension may hide a call), and its `cargo_config` is not one string that is the label of the cargo config hosted mode writes (`.cargo/config.toml`, or the project's `.cargo/config`). cargo-bazel runs cargo with the config its hub names and no other, so the registry of a pin would be unknown to it and `bazel build` would fail (`registry index was not found in any configuration`). The crate is not pinned: nothing is written for it, its event is `skipped` / `redirect_unconfirmed` (a vendored crate that the scan would take over stays vendored: `skipped` with this code, and `redirect_takeover_kept_vendored`), and status and exit code are unchanged. One warning per crate; the detail names the hub's file and line, the config to commit (created with a comment line in it where the project has none), the attribute to give the hub (`cargo_config = "//:.cargo/config.toml"`; the label is written in the package of the hub's own labels), after which the same command pins the crate, and `--mode vendored`. A hub that names that config is still in the way while the file is there and holds nothing: `rollback` deletes a cargo config it leaves empty, and the hub fails on the missing file; the detail asks for a comment line in it. For a use of the extension that may hide a call the detail names that line to rewrite and no attribute: the next run pins the crate or names the hub that is in the way. A `WORKSPACE` call (`crates_repository`, also under the name a `load` of that file gives it) counts only when no hub of the module files reads the project's Cargo files and the checkout names no Bazel 9 or later. The rewriter's own refusals answer first and keep their codes. A pin that is in place already stays `applied`, and no warning is given for it. Nothing is read or changed in no Bazel workspace, or where no such hub is seen to read the project's Cargo files. See docs/ecosystems.md "Bazel workspaces: Cargo". | -| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, vendored and agent mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch that this run vendored or applied, or tried to (`vendor`, `apply`, and `get` / `scan` in those modes; in agent mode only for a package it found installed; never under `--global`), and the block that hosted mode keeps in `MODULE.bazel` holds no entry for that jar. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build: these modes patch no hub. One warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub. The events, the exit code and every written file are those of the same run without the workspace. A `vendor` whose `--ecosystems` leaves Maven out gives none. A vendored run that takes a hosted pin over (`vendor`, `scan` / `get --mode vendored`, `vendor --revert`) leaves the block's entry for it as it is. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | -| `maven_bazel_unreadable` | vendored / agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning) | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in vendored and agent mode (hosted mode gives `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in vendored and agent mode, a `maven.override` of the artifact (hosted mode gives `maven_bazel_no_effect`). Hosted mode also gives it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | +| `maven_bazel_hub_unpatched` | run-level `warnings[]` (human: `Warning: …`) | Maven in a Bazel workspace, agent and vendored mode (additive): a pinned rules_jvm_external hub of the root `MODULE.bazel` fetches the jar of a Maven patch of this run, and the block that hosted and vendored mode keep in `MODULE.bazel` holds no entry for that jar after it. The hub builds the jar its own lock (`maven_install.json`) names, so the patch does not reach the Bazel build. Agent mode (`apply`, and `get` / `scan` in that mode; only for a package it found installed; never under `--global`) patches no hub: one warning per purl; the detail names the lock, the hub, the file and line of its `maven.install`, and the hosted command that patches a pinned hub; the events, the exit code and every written file are those of the same run without the workspace. Vendored mode (`vendor`, and `get` / `scan` in that mode) patches a pinned hub (below), and gives this code only for a jar it could have written an entry for and vendored nothing for, because the package failed or was skipped for another reason (never in a dry run); a jar it cannot write an entry for gets the `maven_bazel_*` code of the reason instead. A `vendor` whose `--ecosystems` leaves Maven out gives none. A hosted run never gives it: see the `maven_bazel_*` rows below and docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_unreadable` | agent: run-level `warnings[]` (human: `Warning: …`); scan/get `--mode hosted`: `warnings[]` (warning); vendored: as `maven_bazel_not_at_root` | Maven in a Bazel workspace (additive): whether a rules_jvm_external hub builds the jar of a Maven patch could not be told, because something could not be read with certainty: a hub without `lock_file` in agent mode (hosted and vendored mode give `maven_bazel_not_pinned`), a `maven.artifact` or `maven.from_toml` tag that cannot be read, a lock that is missing, empty, not format 2 or 3, larger than 16 MiB (or past the 64 MiB of locks that are read for one workspace) or no JSON, a `WORKSPACE` file that calls `maven_install` or cannot be read while `.bazeliskrc` or `.bazelversion` at the Bazel root names no release of Bazel 9 or later, a `maven.install` whose `name` or `lock_file` is not a plain string, a construct of `MODULE.bazel` the reader does not follow, and, in agent mode, a `maven.override` of the artifact (hosted and vendored mode give `maven_bazel_no_effect`). Hosted and vendored mode also give it for a hub on an isolated `use_extension`, an rc file that cannot be read (also one that an import takes from outside the workspace by a relative path, and one with a line whose reading Bazel's own source calls an oversight: a quote that is never closed, a `\` with nothing after it), a `MODULE.bazel` that is a symbolic link, and a block of `MODULE.bazel` that was changed by hand (also in its first line alone), and then writes no entry for the hub. One warning per purl; the detail names the file, the line and the reason. | | `maven_bazel_hub_not_read` | scan run-level `warnings[]` (human: `Warning: …`); `get --mode hosted`: `warnings[]` | scan `--mode hosted` at the root of a Bazel workspace, with Maven in scope (additive): the scan takes the jars that the pinned rules_jvm_external hubs fetch for packages of the project (the lockfile supplement above), and something of the hubs could not be read with certainty, so it does not know every Maven artifact that Bazel builds through a hub. Given once per run, for the first thing that was not read, whatever the packages: a hub without `lock_file` (the detail then ends with how to pin it), or one of the reasons of `maven_bazel_unreadable` that concern reading the hubs (a tag or a lock that cannot be read, a `maven_install` of a `WORKSPACE` file that Bazel may read, a construct of `MODULE.bazel` the reader does not follow, a block that was changed by hand). `[:]: , so socket-patch does not know every Maven artifact that Bazel builds here through a rules_jvm_external hub: it looks for patches of the ones in the hub locks it read, and of no other`. No jar is guessed for what was not read; the jars of the hubs that were read are scanned, and a patch found for one of them gets no entry while the doubt stands (`maven_bazel_not_pinned` / `maven_bazel_unreadable` below). With no package at all a person reads `No packages found (see the warning).`. Exit code and `status` unchanged. A hosted `get` by advisory, which keeps the releases the project has by the same supplement, gives it too when the advisory has a patch of a Maven artifact. Only in a workspace that has to do with the ruleset: a call in `MODULE.bazel` or a file it includes names `rules_jvm_external`, the `WORKSPACE` file calls `maven_install`, or a `maven_install.json` lies at the Bazel root. In another Bazel workspace a file that cannot be read gives no such warning, and the run is the one without the workspace. | -| `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. See docs/ecosystems.md "Bazel workspaces: Maven". | +| `maven_bazel_not_at_root` | `warnings[]` (warning; human: `Warning: …`) | scan/get `--mode hosted` in a Bazel workspace (additive): a rules_jvm_external hub builds the jar of a Maven patch, and the project is below the root of its Bazel workspace, in whose `MODULE.bazel` the patch of a hub is written. Like the five codes below and `maven_bazel_unreadable` in hosted mode, it means that the run wrote no entry for the jar in the block of the root `MODULE.bazel`, because it could not show from the checkout that the entry works. One warning per purl, in the place of `redirect_maven_no_pom` for that purl; the detail says why and ends with what the block of the root holds for the jar, which is read for a project below the root too (the detail then names the file as "the MODULE.bazel at the root"). Nothing: "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the upstream jar". The event is the one of the same run without the hub: `skipped` / `redirect_unconfirmed` in a tree only Bazel builds, `applied` beside a `pom.xml` or Gradle pin that landed. The entry of the patch, from an earlier run: that entry stays, the event is `applied`, and the detail ends "socket-patch left the entry that MODULE.bazel holds for it as it is". The entry of another patch of the same jar: it stays too, the event is the one without the hub, and the detail ends "socket-patch wrote nothing to MODULE.bazel for it: the entry of patch remains there, and where the block is in effect the Bazel build takes that patch's jar". Exit code unchanged. With none of these codes the run writes the block: `redirect.rewrittenFiles` holds `MODULE.bazel`, the event is `applied`, and `rollback` / `remove` take the entry out. **Vendored mode** (`vendor`, and `scan` / `get --mode vendored`; additive) gives the same codes, but for `maven_bazel_download`, with the same detail, for a jar whose entry it does not write. In a project with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the event is `failed` with the code as its `errorCode` and the detail, without the purl in front, as its `error`, nothing is written and the run exits 1, as for any vendored refusal (before, such a project failed with `vendor_jvm_shape_unsupported`, which a jar that no hub builds still does). Beside such a build that was vendored, the code is a run-level `warnings[]` entry (human: `Warning: …`), the event is `applied` and the exit code is unchanged. With none of these codes vendored mode commits the patched jar under `.socket/vendor/maven//` (`REPO.bazel`, `file/BUILD.bazel`, `file/-.jar`, `.gitignore`), writes the entry that names that directory into the block, in the place of a hosted entry for the same jar, adds the directory's line to `.bazelignore`, and records the patch in the vendor ledger (in a project with no other JVM build: `ecosystem` `maven`, `flavor` `bazel`, the committed jar as `artifact`, no `wiring`); the event is `applied`. `vendor --check` then also fails (`vendor_check_failed`) when that jar is not, byte for byte, the vendored jar the ledger records (beside a Maven or Gradle build the hub's jar is a copy of it), when `REPO.bazel` / `file/BUILD.bazel` is not the file that was written, when the block no longer names the directory or was changed by hand, and when no pinned hub takes the jar at that version any more (the reason names `socket-patch rollback `) or an rc file switches the entry off. `vendor --revert` / `rollback` / `remove` take the entry, the directory and the line out, and a hosted run that puts its entry in the place of the vendored one removes the directory and the line. See docs/ecosystems.md "Bazel workspaces: Maven". | | `maven_bazel_not_pinned` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: a hub of the workspace has no `lock_file` (also one that only `maven.artifact` or `maven.from_toml` tags make), so Bazel resolves its jars when it builds and none can be replaced. Also given beside a pinned hub that holds the artifact. The detail names the hub's file and line and how to pin it. | | `maven_bazel_release` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the Bazel release is not known to be 7.4.0 or later, the first with `override_repo` (`.bazeliskrc` or `.bazelversion` names an older one, or neither names a release of three numbers and `MODULE.bazel.lock` is missing or of a format before the one Bazel 7.5.0 writes), or the rules_jvm_external release Bazel selected is not known to be one of 6.4 to 7.2 (`MODULE.bazel.lock` holds the `source.json` of no release of it or of more than one, of a release outside that range, of an older one than the `bazel_dep` of `MODULE.bazel` asks for, or of another one than a `single_version_override` there pins; or an `archive_override`, `git_override`, `local_path_override` or `multiple_version_override` of the ruleset, or a `single_version_override` whose version is no plain string, leaves the release unknown). Versions are compared as Bazel compares them. The detail names the remedy (a `.bazelversion`, one build so that Bazel writes its lock, or an update of socket-patch) or the line of the override. | | `maven_bazel_artifact` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the repository through which the hub fetches this jar has no known name (a character other than letters, digits, `.`, `_` and `-` in its group, artifact or version), the lock lists no repository for the jar (`m2local`), or the patch comes without the version it is served under or without a sha256. | | `maven_bazel_no_effect` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: the build would pass on the upstream jar with the block in place. The root has a `maven.override` for the artifact, or an rc file of the checkout (`.bazelrc` and what it imports with `import`, `try-import` and `try-import-if-bazel-version`, by a path under `%workspace%/` or a relative one; each read as Bazel reads an rc file: lines joined at a `\` before a line break, comments from a `#`, words without their quotes and escapes) names `--ignore_dev_dependency` without switching it off, or names `enable_bzlmod` other than switched on (Bazel reads `false`, `0`, `no`, `f`, `n` in any case and a `no` before the name as off) while the checkout names no Bazel 9 or later. The detail names the file and the line. | -| `maven_bazel_download` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`: an rc file of the checkout names a downloader config, `--repository_disable_download` or `--vendor_dir`, under which Bazel may not be able to download the patched jar from the Socket patch host. The detail names the file, the line and the option. | +| `maven_bazel_download` | `warnings[]` (warning; human: `Warning: …`) | As `maven_bazel_not_at_root`, in hosted mode only (a vendored jar is in the checkout): an rc file of the checkout names a downloader config, `--repository_disable_download` or `--vendor_dir`, under which Bazel may not be able to download the patched jar from the Socket patch host. The detail names the file, the line and the option. | | `vendor_*` / `pypi_*` / `gemfile_*` / `lock_*` / `locked_version_mismatch` / `user_authored_*` / `native_extensions_unsupported` / `platform_gem_unsupported` | `failed`/`skipped` | vendor: per-ecosystem refusal + drift vocabulary; see the Vendor command contract section. New tags are additive (MINOR). | `user_patch_conflict` is a `skipped` event and a scan/apply run warning for packages diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 048fc571e..7bfeaba0a 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1985,7 +1985,8 @@ pub(crate) async fn run_locked( run_warnings.extend(user_patch_warnings.iter().cloned()); run_warnings.extend(unsupported_warning); let patched = results.iter().map(|r| r.package_key.as_str()); - run_warnings.extend(super::bazel_maven_notices(&args.common, patched, false).await); + run_warnings + .extend(super::bazel_maven_notices(&args.common, patched, false, false).await); run_warnings.extend(results.iter().flat_map(|r| { let note = r.error.as_deref().filter(|_| r.success).unwrap_or_default(); socket_patch_core::patch::apply::advisory_warning_codes(note) diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index cc1b5386e..93bd32267 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -56,13 +56,14 @@ pub(crate) fn project_state_in_scope(common: &crate::args::GlobalArgs) -> bool { } /// In a Bazel workspace the root's `.bazelignore` names the directories of -/// the project's patched Go module copies, and of the vendored crates a -/// crate hub builds, so that Bazel and gazelle read no package there +/// the project's patched Go module copies, of the vendored crates a crate +/// hub builds, and of the patched Maven jars that vendored mode keeps for a +/// rules_jvm_external hub, so that Bazel and gazelle read no package there /// (`socket_patch_core::bazel::ignore`). A command that can write or /// remove such a copy calls this once, after the last step that can change /// a copy or take one back and before it gives up its apply lock. Nothing /// is done in a dry run or a `--global` run, and a run whose `--ecosystems` -/// leaves `golang` or `cargo` out only takes away that ecosystem's pair of +/// leaves `golang`, `cargo` or `maven` out only takes away that ecosystem's pair of /// a copy that is gone. So does the prune pass of a scan, which comes here /// after its scan has (`adds` false) and can only have removed a copy: a /// file it cannot write is left to the next command's warning. @@ -74,7 +75,7 @@ pub(crate) async fn sync_bazelignore( adds: bool, ) -> Vec { use socket_patch_core::bazel::ignore; - use socket_patch_core::crawlers::Ecosystem::{Cargo, Golang}; + use socket_patch_core::crawlers::Ecosystem::{Cargo, Golang, Maven}; let mut warnings = Vec::new(); if common.dry_run || common.is_global() { return warnings; @@ -86,9 +87,10 @@ pub(crate) async fn sync_bazelignore( projects.push(common.project_root()); } let (loud, mut told) = (!common.json && !common.silent, Vec::new()); - let [go, cargo] = [Golang, Cargo].map(|eco| adds && common.ecosystem_selected(eco)); + let [go, cargo, maven] = + [Golang, Cargo, Maven].map(|eco| adds && common.ecosystem_selected(eco)); for project in projects { - match ignore::sync(&project, go, cargo).await { + match ignore::sync(&project, go, cargo, maven).await { Ok(Some((file, copies))) if loud => { // A root that both projects are under is named once for // each kind of copy whose lines changed there. @@ -135,24 +137,31 @@ pub(crate) async fn sync_bazelignore( /// /// With `tell`, a human run is told here, as [`sync_bazelignore`] tells /// it. A command that prints the warnings of its run itself passes -/// `false`. +/// `false`. A `vendored` run patches a pinned hub itself: it is warned of +/// the jars it wrote no entry for, each with the reason. pub(crate) async fn bazel_maven_notices<'a>( common: &crate::args::GlobalArgs, purls: impl Iterator, tell: bool, + vendored: bool, ) -> Vec { if common.is_global() { return Vec::new(); } let purls = purls.map(str::to_string).collect(); - let said = socket_patch_core::bazel::maven::notices(&common.cwd, purls).await; + use socket_patch_core::bazel::maven::{notices, HUB_UNPATCHED}; + let said = notices(&common.cwd, purls, vendored).await; + // A vendored dry run wrote no entry for any jar: the ones it would + // write are not unpatched. + let would_write = |code: &str| vendored && common.dry_run && code == HUB_UNPATCHED; + let said = said.into_iter().filter(|(code, _)| !would_write(code)); let warning = |(code, detail): (&str, String)| { if tell && !common.json && !common.silent { eprintln!("Warning: {detail}"); } crate::json_envelope::RunWarning::new(code, detail) }; - said.into_iter().map(warning).collect() + said.map(warning).collect() } /// The vendor-ledger keys (`ledger`, the project's diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index ac2c3a38f..b8635d05b 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2753,6 +2753,15 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let gc_bytes_freed = gc.map_or(0, |gc| gc.bytes_freed); // ── run-level warnings ─────────────────────────────────────── + // The jar that vendored mode kept for a Bazel hub alone is in + // no installed tree: the next Bazel build takes the hub's own. + let of_hub = |key: &String| { + let flavor = socket_patch_core::vendor::maven_repo::HUB_FLAVOR; + let hub = |(k, e): &(String, socket_patch_core::vendor::VendorEntry)| { + k == key && e.flavor.as_deref() == Some(flavor) + }; + vendor_entries.iter().any(hub) + }; let advised = ReinstallAdvised::of( vendored_leg .warnings @@ -2775,6 +2784,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let still_patched = vendored_leg .reverted .iter() + .filter(|key| !of_hub(key)) .chain(vendored_leg.preserved.iter()) .chain(hosted_leg.reverted.iter()) .filter(|key| { diff --git a/crates/socket-patch-cli/src/commands/scan/discovery.rs b/crates/socket-patch-cli/src/commands/scan/discovery.rs index bc21c2268..478df431a 100644 --- a/crates/socket-patch-cli/src/commands/scan/discovery.rs +++ b/crates/socket-patch-cli/src/commands/scan/discovery.rs @@ -129,8 +129,9 @@ pub(crate) async fn lockfile_supplement( /// workspace fetch when `--cwd` is its root, what was not read of its hubs /// and the entries of its block that are stale /// ([`socket_patch_core::bazel::maven::hub_jars`]). Only for a hosted run -/// with Maven in scope: no other mode patches a hub. The callers are runs -/// of a project, never of the global installs. +/// with Maven in scope: a vendored scan does not look for a hub's jars, +/// and patches the hub of a package it found elsewhere. The callers are +/// runs of a project, never of the global installs. pub(crate) async fn hub_jars(common: &GlobalArgs, hosted: bool) -> HubJars { if !hosted || !common.ecosystem_selected(Ecosystem::Maven) { return HubJars::default(); diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 221a21068..19759632a 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2284,6 +2284,19 @@ async fn run_redirect_selected_untracked( )); return 1; } + // A hosted entry that took the place of a vendored one in the block of + // a Bazel hub leaves the directory of that entry without a reader. + let mut unit_warnings: Vec = Vec::new(); + if let (false, Some(module), Ok(state)) = ( + common.dry_run, + rewrite.files.get(socket_patch_core::bazel::maven::FILE), + &vendor_state, + ) { + let left = + socket_patch_core::vendor::maven_repo::drop_unnamed_units(&common.cwd, module, state); + let warning = |detail| RunWarning::new("cleanup_failed", detail); + unit_warnings.extend(left.await.into_iter().map(warning)); + } // A pnpm-workspace.yaml a hosted run created, which this run emptied of // its registry route: deleted, not left as a bare `packages` list. The // rewrite carries writes only, so the file goes once they have landed. @@ -2635,6 +2648,7 @@ async fn run_redirect_selected_untracked( warnings.extend(vlt_stale.warnings.iter().map(run_warning_of)); warnings.extend(takeover_pre_warnings.iter().map(run_warning_of)); warnings.extend(takeover_warnings.iter().cloned()); + warnings.extend(unit_warnings); warnings.extend(prune_warnings.iter().cloned()); warnings.extend(workspace_warning); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index d90e89e11..f0a5b1c86 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1439,6 +1439,12 @@ async fn run_check(args: &VendorArgs) -> i32 { Err(e) => failure = Some(e), } } + // The copy of the patch that a hub of a Bazel workspace builds, + // beside the artifact the entry records or as that artifact. + let hub = vendor::jvm::layout::ledger_ecosystem(&entry.ecosystem) == "maven"; + if failure.is_none() && hub { + failure = vendor::maven_repo::check_hub(root, entry).await.err(); + } // The npm check names the exact unwired lock entry, so it runs // before the generic liveness rule below. if failure.is_none() && entry.ecosystem == "npm" { @@ -1739,31 +1745,46 @@ pub(crate) async fn gem_takeover_refusals_for<'a>( refusals } -/// The hosted pins a vendored run takes over, of `pins`. Vendored mode -/// patches no rules_jvm_external hub of a Bazel workspace, so the entry -/// that hosted mode keeps for a pin in the block of the root -/// `MODULE.bazel` is none of its wiring: the entry stays as it is, and the -/// Bazel build keeps the patched jar. A pin that only such an entry wires -/// is no takeover at all. `rollback` and `remove` take the entry out. +/// The file of the block that hosted and vendored mode keep for the hubs +/// of a Bazel workspace. +use socket_patch_core::bazel::maven::FILE as BLOCK_FILE; + +/// The hosted pins whose upstream entry a vendored run restores before it +/// vendors, of `pins`. The entry that hosted mode keeps for a pin in the +/// block of the root `MODULE.bazel` is not restored: where vendored mode +/// patches the hub, it puts its own entry in the place of that one, and +/// where it cannot, the entry stays as it is and the Bazel build keeps the +/// patched jar. A pin that only such an entry wires is no takeover at all. fn takeover_pins(pins: Vec) -> Vec { let beside_the_hub = |mut pin: HostedPin| { - pin.files - .retain(|file| file != socket_patch_core::bazel::maven::FILE); + pin.files.retain(|file| file != BLOCK_FILE); (!pin.files.is_empty()).then_some(pin) }; pins.into_iter().filter_map(beside_the_hub).collect() } -/// The hosted pins of an eject: those a vendored run takes over -/// ([`takeover_pins`]) whose ecosystem `--ecosystems` selects. +/// The hosted pins of an eject, of those whose ecosystem `--ecosystems` +/// selects: the ones a vendored run takes over ([`takeover_pins`]), and, +/// in a project whose only build is the hub of a Bazel workspace, the ones +/// that only the block of `MODULE.bazel` wires, with that file: the eject +/// takes the hosted entry out, as it restores any pin, and the vendored +/// one takes its place in the same commit. Beside a Maven or Gradle build +/// such a pin is none of the eject's: its entry stays hosted, unless the +/// run vendors the same patch for that build (a patch of the manifest, or +/// a pin that the build's own files hold too), which puts the vendored +/// entry in its place. fn hosted_pins_in_scope(common: &GlobalArgs, pins: Vec) -> Vec { - takeover_pins(pins) - .into_iter() - .filter(|pin| { - socket_patch_core::utils::purl::purl_parts(&pin.purl) - .is_some_and(|(eco, _, _)| ecosystem_in_scope(common, &eco)) - }) - .collect() + let in_scope = |pin: &HostedPin| { + socket_patch_core::utils::purl::purl_parts(&pin.purl) + .is_some_and(|(eco, _, _)| ecosystem_in_scope(common, &eco)) + }; + let (of_the_block, mut pins): (Vec, Vec) = + pins.into_iter().partition(|pin| pin.files == [BLOCK_FILE]); + pins = takeover_pins(pins); + if !of_the_block.is_empty() && vendor::maven_repo::hub_alone(&common.cwd) { + pins.extend(of_the_block); + } + pins.into_iter().filter(in_scope).collect() } /// What a wet eject can touch, captured before it touches anything: every @@ -2082,7 +2103,10 @@ async fn run_eject( let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); // The refusals that rest on the Bazel workspace need no record and no // registry, so they are asked before either is fetched: the pins stay - // hosted whatever the network says. + // hosted whatever the network says. The hub of a Bazel workspace is + // asked about the checkout as it is here, where its hosted entry + // stands: the reason of an entry that vendored mode would not write + // then says that the hosted one stays. let pairs: Vec<(&str, &str)> = pins .iter() .map(|pin| (pin.purl.as_str(), pin.uuid.as_str())) @@ -4399,6 +4423,12 @@ pub(crate) async fn vendor_records_reusing( } else if let Some(tool) = jvm_wiring_tool(&entry.wiring) { wired_flavors.insert(tool.to_string()); } + // Beside this build, a hub of a Bazel workspace got a + // copy of the jar: its files belong to the commit too. + let jvm = vendor::jvm::apply::is_jvm_entry(&entry); + if jvm && vendor::maven_repo::hub_wired(&common.cwd, &entry.uuid).await { + wired_flavors.insert(HUB_BESIDE.to_string()); + } let (save_failed, stale) = record_vendor_entry( common, env, &mut state, candidate, entry, detached, record, ) @@ -4683,10 +4713,18 @@ pub(crate) async fn vendor_records_reusing( } // A hub of a Bazel workspace builds the jar of its own lock, whatever - // this run vendored for the Maven or the Gradle build. - let vendored = vendorable.iter().map(String::as_str); - env.warnings - .extend(crate::commands::bazel_maven_notices(common, vendored, true).await); + // this run vendored for the Maven or the Gradle build: the jars it + // wrote no entry for. One refused for the hub alone has said why. + let refused = |purl: &&String| { + let hub = |code: &str| code.starts_with("maven_bazel_"); + let about = |event: &&PatchEvent| event.purl.as_ref() == Some(*purl); + let mut events = env.events[events_start..].iter().filter(about); + events.any(|event| event.error_code.as_deref().is_some_and(hub)) + }; + let vendored = vendorable.iter().filter(|purl| !refused(purl)); + let vendored: Vec<&str> = vendored.map(String::as_str).collect(); + let notices = crate::commands::bazel_maven_notices(common, vendored.into_iter(), true, true); + env.warnings.extend(notices.await); // A rolled-back eject's summary would describe a vendoring that was // undone: the eject prints it itself once it knows the outcome (#1005). @@ -4761,9 +4799,13 @@ fn print_vendor_closing( .all(|f| JVM_TOOLS.contains(&f.as_str())); let reinstall = if jvm_only { let cmds: Vec = installs.iter().map(|c| format!("`{c}`")).collect(); + // The block of a hub is in a file of the checkout's own. + let how = match installs == [HUB_BUILD] { + true => format!("{BLOCK_FILE} names their directory"), + false => "the generated root file points it at .socket/vendor/".to_string(), + }; format!( - "Run {} so the build resolves the vendored artifacts (the generated root \ - file points it at .socket/vendor/)", + "Run {} so the build resolves the vendored artifacts ({how})", cmds.join(" and ") ) } else if installs.is_empty() { @@ -4842,8 +4884,18 @@ pub(crate) struct EjectCapture { } /// The pseudo-flavors of vendored JVM builds whose wiring is a generated -/// root file rather than a lockfile. -const JVM_TOOLS: &[&str] = &["sbt", "scala-cli"]; +/// root file rather than a lockfile, and the flavor of a patch that only +/// the hub of a Bazel workspace takes, whose wiring is the block of +/// `MODULE.bazel`. +const JVM_TOOLS: &[&str] = &["sbt", "scala-cli", HUB_FLAVOR]; +use socket_patch_core::vendor::maven_repo::HUB_FLAVOR; + +/// Among the flavors a run wired: a hub of a Bazel workspace got a copy of +/// a jar that the run vendored for a Maven or Gradle build. Its files are +/// committed with that build's, and no step of its own follows. +const HUB_BESIDE: &str = "bazel-hub-copy"; +/// What takes the committed jar of a hub: the next Bazel build. +const HUB_BUILD: &str = "bazel build //..."; /// `sbt` / `scala-cli` when `wiring` is that vendored backend's (a ledger /// entry of either records ecosystem `maven` and no flavor). @@ -4888,6 +4940,9 @@ fn commit_hint(wired: &HashSet, pnpm_workspace: bool) -> String { if wired.contains("scala-cli") { roots.push(socket_patch_core::vendor::jvm::scala_cli::ROOT_FILE); } + if wired.contains(HUB_FLAVOR) || wired.contains(HUB_BESIDE) { + roots.extend([BLOCK_FILE, ".bazelignore"]); + } let lockfiles = wired.iter().any(|f| !JVM_TOOLS.contains(&f.as_str())) || roots.is_empty(); match (roots.is_empty(), lockfiles) { (true, _) => { @@ -4937,6 +4992,8 @@ fn flavor_install_command(flavor: &str) -> Option<&'static str> { // Not an install: the JVM build re-resolves from the vendored tree. "sbt" => Some("sbt update"), "scala-cli" => Some("scala-cli compile --test ."), + // Nor here: the next Bazel build takes the jar of the checkout. + HUB_FLAVOR => Some(HUB_BUILD), _ => None, } } @@ -4947,6 +5004,9 @@ fn flavor_install_command(flavor: &str) -> Option<&'static str> { fn flavor_revert_install_command(flavor: &str) -> Option<&'static str> { match flavor { "bun" => Some("bun install --force"), + // No tree holds the jar of a hub: the next Bazel build takes the + // hub's own, with nothing to resync. + HUB_FLAVOR => None, other => flavor_install_command(other), } } @@ -7582,6 +7642,47 @@ mod gc_tests { ); } + /// The directory of the jar that vendored mode keeps for the hub of a + /// Bazel workspace is the unit `maven/` of its patch. Beside a + /// Maven or Gradle build the JVM ledger entry of that patch owns it, so + /// no sweep takes it for an orphan; without an entry it is kept while + /// `MODULE.bazel` names it, and goes once nothing does. + #[tokio::test] + async fn orphan_sweep_keeps_the_jar_of_a_bazel_hub() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let uuid = "1a2b3c4d-5e6f-4a1b-8c2d-9e0f1a2b3c4d"; + let unit = format!(".socket/vendor/maven/{uuid}"); + let jar = root.join(&unit).join("file/a-1.jar"); + std::fs::create_dir_all(jar.parent().unwrap()).unwrap(); + std::fs::write(&jar, b"jar").unwrap(); + let artifact = VendorArtifact { + yarn_berry10c0: None, + path: ".socket/vendor/maven2/g/a/1-socket.1a2b3c4d/a-1-socket.1a2b3c4d.jar".into(), + sha256: String::new(), + size: None, + platform_locked: None, + file_inventory: None, + }; + let purl = "pkg:maven/g/a@1".to_string(); + let entry = VendorEntry::new("jvm".into(), purl.clone(), uuid.into(), artifact, vec![]); + let mut owned = VendorState::default(); + owned.entries.insert(purl, entry); + let sweep = sweep_orphan_vendor_dirs(root, &owned, false).await; + assert!(sweep.removed.is_empty() && sweep.still_wired.is_empty()); + assert!(jar.is_file()); + + let named = format!("socket_patch_local_repository(\n path = \"{unit}\",\n)\n"); + std::fs::write(root.join("MODULE.bazel"), named).unwrap(); + let sweep = sweep_orphan_vendor_dirs(root, &VendorState::default(), false).await; + assert_eq!((sweep.still_wired.len(), sweep.removed.len()), (1, 0)); + assert!(jar.is_file()); + std::fs::remove_file(root.join("MODULE.bazel")).unwrap(); + let sweep = sweep_orphan_vendor_dirs(root, &VendorState::default(), false).await; + assert_eq!(sweep.removed.len(), 1); + assert!(!jar.exists()); + } + /// (c) uuid dirs with no owning ledger entry are swept (wet) / counted /// (dry). #[tokio::test] @@ -7779,10 +7880,11 @@ mod gc_tests { mod scope_and_hint_tests { use super::*; - /// A vendored run takes over what wires a hosted pin in a build it - /// can vendor into, and never the entry of a Bazel hub: that file is - /// no file of the pin it restores, and a pin of that entry alone is - /// none of its pins. + /// A vendored run restores what wires a hosted pin in a build it can + /// vendor into, and never the entry of a Bazel hub, which it replaces + /// where it can: that file is no file of the pin it restores. A pin + /// of that entry alone is ejected only where the hub is the project's + /// one build, and is none of the pins of a project that Maven builds. #[test] fn a_takeover_leaves_the_entry_of_a_bazel_hub() { let pin = |purl: &str, files: &[&str]| HostedPin { @@ -7802,7 +7904,14 @@ mod scope_and_hint_tests { pins[2].clone(), ]; assert_eq!(takeover_pins(pins.clone()), taken); - let common = GlobalArgs::default(); + let project = tempfile::tempdir().unwrap(); + let common = GlobalArgs { + cwd: project.path().to_path_buf(), + ..GlobalArgs::default() + }; + let alone = [taken.clone(), vec![pins[1].clone()]].concat(); + assert_eq!(hosted_pins_in_scope(&common, pins.clone()), alone); + std::fs::write(project.path().join("pom.xml"), "").unwrap(); assert_eq!(hosted_pins_in_scope(&common, pins), taken); } @@ -7826,6 +7935,13 @@ mod scope_and_hint_tests { flavor_install_command("scala-cli"), Some("scala-cli compile --test .") ); + // A patch of a Bazel hub alone: the block and the ignore file are + // what a commit must not leave out. + assert_eq!(flavor_install_command("bazel"), Some("bazel build //...")); + let wired: HashSet = ["bazel".to_string()].into(); + let hint = commit_hint(&wired, false); + let named = "MODULE.bazel, .bazelignore and .socket/vendor/ to make the patches portable"; + assert!(hint.starts_with(named), "{hint}"); } /// A Rush run wires three kinds of file, and a commit that leaves one diff --git a/crates/socket-patch-cli/src/commands/vendor_orphans.rs b/crates/socket-patch-cli/src/commands/vendor_orphans.rs index 2cf6cf779..629ae90ca 100644 --- a/crates/socket-patch-cli/src/commands/vendor_orphans.rs +++ b/crates/socket-patch-cli/src/commands/vendor_orphans.rs @@ -50,10 +50,15 @@ pub(crate) async fn sweep_orphan_vendor_dirs_where( dry_run: bool, select: impl Fn(&vendor::path::SweptVendorDir) -> bool, ) -> OrphanSweep { + // A JVM entry owns the `maven/` unit of its patch too: the + // directory of the jar that a hub of a Bazel workspace builds. let recorded_units: HashSet<(&str, &str)> = state .entries .values() - .map(|e| (e.ecosystem.as_str(), e.uuid.as_str())) + .map(|e| { + let eco = vendor::jvm::layout::ledger_ecosystem(&e.ecosystem); + (eco, e.uuid.as_str()) + }) .collect(); let mut candidates: Vec = vendor::path::sweep_vendor_dirs(cwd) .await 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 8d563a33e..5f19fb83f 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -189,13 +189,16 @@ async fn scan_vendor_references_folding( /// ([`registry::VENDORED`]: `nuget.config`, `pom.xml` and `hatch.toml` /// included), vlt importer manifests, a Rush repository's locks, configs /// and project manifests, the Python -/// locks the root lists (and their scripts) and the requirements `-r` -/// include tree. Sorted and deduplicated; entries need not exist. +/// locks the root lists (and their scripts), the requirements `-r` +/// include tree, and the `MODULE.bazel` whose block names the directory of +/// a jar vendored for a hub of a Bazel workspace. Sorted and deduplicated; +/// entries need not exist. async fn wiring_files(project_root: &Path) -> Vec { let mut files: Vec = registry::paths_with(registry::VENDORED) .into_iter() .map(str::to_string) .collect(); + files.push(socket_patch_core::bazel::maven::FILE.to_string()); files.extend(vendor::vlt_lock::vlt_importer_package_jsons(project_root).await); files.extend(vendor::rush_wiring_files(project_root).await); if let Ok(paths) = socket_patch_core::utils::python_lock::python_lock_paths(project_root) { @@ -272,10 +275,15 @@ pub(crate) async fn unledgered_vendor_references( .await .into_iter() .filter(|(eco, uuid, _)| { + // A JVM entry owns the `maven/` unit of its patch too + // (the jar that a hub of a Bazel workspace builds). + let owns = |entry: &vendor::VendorEntry| { + vendor::jvm::layout::ledger_ecosystem(&entry.ecosystem) == eco + }; !state .entries .values() - .any(|entry| entry.ecosystem == *eco && entry.uuid == *uuid) + .any(|entry| owns(entry) && entry.uuid == *uuid) }) .collect() } @@ -756,10 +764,15 @@ impl VendoredBackend<'_> { // ── Lockfile references no ledger entry owns ───────────────────── // Reported, never re-synthesized: the pre-vendor originals a revert // replays are not recoverable from the rewired lockfile. + // A JVM entry owns the `maven/` unit of its patch too, which + // `MODULE.bazel` names for a hub of a Bazel workspace. let covered: HashSet<(String, String)> = state .entries .values() - .map(|e| (e.ecosystem.clone(), e.uuid.clone())) + .map(|e| { + let eco = vendor::jvm::layout::ledger_ecosystem(&e.ecosystem); + (eco.to_string(), e.uuid.clone()) + }) .collect(); for (eco, uuid, path) in req.references { if covered.contains(&(eco.clone(), uuid.clone())) || !ecosystem_in_scope(common, eco) { diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 50f56bab3..f650a8199 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -713,10 +713,16 @@ pub(crate) async fn plan( } } let mut took_over = false; + // A JVM entry is attested from its own tree, as it is without the + // copy of its jar that the block of a Bazel hub names. + let of_tree = cand + .vendor_entry + .as_ref() + .is_some_and(socket_patch_core::vendor::jvm::apply::is_jvm_entry); let basis = if let Some(vref) = cand .discovered .iter() - .find(|r| r.mode == WiringMode::Vendored) + .find(|r| r.mode == WiringMode::Vendored && !of_tree) { Basis::Vendored(Box::new(vendored_entry_for(&cand, vref))) } else if cand.discovered.iter().any(|r| r.mode == WiringMode::Hosted) { diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs index d0fdc9917..dea1f4b94 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -718,10 +718,28 @@ impl StandIn { .enable_all() .build() .expect("a runtime for the stand-in"); - let server = runtime.block_on(MockServer::start()); + // A server of its own, not one of wiremock's pool: it stops when + // the stand-in is dropped. + let server = runtime.block_on(MockServer::builder().start()); StandIn { server, runtime } } + /// Stops the server: nothing answers at its origin any more, which is + /// what this gives. + pub fn stop(self) -> String { + let origin = self.origin(); + drop(self); + let address = origin.trim_start_matches("http://").to_string(); + let answers = || std::net::TcpStream::connect(&address).is_ok(); + for _ in 0..100 { + if !answers() { + return origin; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + panic!("the stand-in still answers at {origin}"); + } + /// `http://127.0.0.1:`. pub fn origin(&self) -> String { self.server.uri() @@ -930,6 +948,14 @@ impl Cell { self.downloads = Some(rules.to_vec()); } + /// Whether the repository cache of this cell, which its twins share, + /// holds a download with the sha256 `sha256`: what Bazel's downloader + /// keeps of a file it fetched under a checksum. + pub fn cached(&self, sha256: &str) -> bool { + let files = self.scratch.repository_cache.join("content_addressable"); + files.join("sha256").join(sha256).exists() + } + /// Write a file of the workspace copy. pub fn write(&self, rel: &str, bytes: impl AsRef<[u8]>) { let path = self.scratch.workspace.join(rel); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs index f0b4166fe..c1ab67684 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -49,6 +49,29 @@ //! (`maven_bazel_no_effect`), and the build prints that target's marker //! before and after. //! +//! - [`a_vendored_patch_in_a_tree_only_bazel_builds`]: vendored mode in the +//! checkout without a `pom.xml`. `socket-patch get --mode vendored +//! --yes` downloads the patched jar once, from Socket's patch service, +//! and commits it: the jar and the two files that make its directory a +//! Bazel repository under `.socket/vendor/maven/`, the block of +//! [`vendored_block`] in `MODULE.bazel`, which puts that directory in the +//! place of the hub's repository, the directory's line in `.bazelignore` +//! and the vendor ledger. The same build prints the marker of the patched +//! jar and asks no host for it; `bazel query //...` lists no package +//! under `.socket`; a `--lockfile_mode=error` build passes; `vex` attests +//! the patch. `vendor --check` passes, and fails for a committed jar +//! that is not the patched one, which Bazel builds all the same: nothing +//! checks a directory at build time. A second machine, with the +//! stand-in stopped, builds the patched jar from the checkout alone, and +//! the repository cache holds no copy of it. `vendor --revert` puts +//! every file back byte for byte, and the upstream build with them. +//! - [`a_hub_goes_from_hosted_to_vendored_and_back`]: after the hosted +//! command, `socket-patch vendor` puts the vendored entry in the place +//! of the hosted one, and the build takes the jar of the checkout; the +//! hosted command then takes the vendored entry, its directory and its +//! ledger entry out again, and the checkout is the one the first hosted +//! command left; `rollback` undoes a vendored patch to the byte. +//! //! A command that writes the block gives no warning. One that does not //! gives one, in the place of "no pom.xml", with the reason and the words //! that the Bazel build keeps the upstream jar. The lock each ruleset @@ -96,14 +119,19 @@ use std::io::Write as _; use std::time::Instant; +use base64::Engine as _; + use serde_json::{json, Value}; use sha1::Sha1; -use sha2::{Digest, Sha256}; +use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::bazel::maven::{Lock, Pinned as Jar}; +use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as git_sha256; use crate::envelope::{event_for, event_triples}; -use crate::harness::{changed, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING}; -use crate::hosted_memory_common::Patch; +use crate::harness::{ + changed, rewrite, Cell, Claim, Fixture, How, Ran, StandIn, Tree, CONSUMER, NOTHING, +}; +use crate::hosted_memory_common::{Patch, ORG}; /// The workspace the tests build, and the ruleset each Bazel release /// builds it with. One era per way the ruleset names an artifact's @@ -241,6 +269,9 @@ struct Granted { /// stand-in. url: String, route: String, + /// The route of the same jar as vendored mode downloads it: the path of + /// the grant's own URL for it on the patch host. + archive: String, /// What `//:consumer` prints with the patched jar. marker: String, } @@ -251,7 +282,12 @@ struct Granted { /// on `standin` answers with `tampered`, or with the jar the grant pins. /// Gives the patch for the API of the stand-in too, which takes every /// patch it grants in one call ([`StandIn::api`]). -fn grant(standin: &StandIn, version: &str, tampered: Option<&[u8]>) -> (Granted, Patch) { +/// +/// Vendored mode downloads that jar from the grant's own URL for it, whose +/// host a flow sends to the stand-in, and holds it to the record of the +/// patch, which the stand-in serves: the one file that differs from the +/// upstream jar of the run `run` at that version. +fn grant(standin: &StandIn, run: &str, version: &str, tampered: Option<&[u8]>) -> (Granted, Patch) { let uuid = uuid::Uuid::new_v4().to_string(); let token = uuid::Uuid::new_v4().to_string(); let purl = format!("pkg:maven/{GROUP}/{VICTIM}@{version}"); @@ -261,9 +297,12 @@ fn grant(standin: &StandIn, version: &str, tampered: Option<&[u8]>) -> (Granted, let file = repo_path(VICTIM, &suffixed, "jar"); let route = format!("/{registry}/{file}"); standin.serve(5, &route, tampered.unwrap_or(&jar)); - let artifact = format!( - "https://{PATCH_HOST}/patch/maven/{GROUP}/{VICTIM}/{version}/{token}/{uuid}/{VICTIM}-{suffixed}.jar" - ); + let archive = + format!("/patch/maven/{GROUP}/{VICTIM}/{version}/{token}/{uuid}/{VICTIM}-{suffixed}.jar"); + standin.serve(5, &archive, &jar); + let artifact = format!("https://{PATCH_HOST}{archive}"); + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + let sha512 = format!("sha512-{}", b64(&Sha512::digest(&jar))); let reference = json!({ "status": "granted", "url": artifact, @@ -271,7 +310,7 @@ fn grant(standin: &StandIn, version: &str, tampered: Option<&[u8]>) -> (Granted, "artifacts": [{ "kind": "tarball", "url": artifact, - "integrity": { "sha256": sha256_hex(&jar) }, + "integrity": { "sha256": sha256_hex(&jar), "sha512": sha512 }, }], "registryOverride": { "kind": "maven2", @@ -291,11 +330,37 @@ fn grant(standin: &StandIn, version: &str, tampered: Option<&[u8]>) -> (Granted, uuid: uuid.clone(), reference, }; + // The upstream jar of a run prints its release from the bump on. + let upstream = match version { + VERSION => format!("PRISTINE {run}\n"), + _ => format!("PRISTINE {version} {run}\n"), + }; + let patched = format!("PATCHED {uuid}\n"); + let record = json!({ + "uuid": uuid, + "purl": patch.purl, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { MARKER: { + "beforeHash": git_sha256(upstream.as_bytes()), + "afterHash": git_sha256(patched.as_bytes()), + "blobContent": b64(patched.as_bytes()), + "beforeBlobContent": b64(upstream.as_bytes()), + }}, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }); + let view = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); + standin.serve(1, &view, record.to_string().as_bytes()); let granted = Granted { version: version.to_string(), sha256: sha256_hex(&jar), url: format!("https://{registry}/{file}"), route, + archive, marker: format!("OUT: PATCHED {uuid}"), uuid, }; @@ -403,8 +468,8 @@ impl Pinned { &jar(&[]), Some((VICTIM, VERSION)), ); - let (patch, first) = grant(&standin, VERSION, None); - let (next, second) = grant(&standin, BUMPED, None); + let (patch, first) = grant(&standin, &run, VERSION, None); + let (next, second) = grant(&standin, &run, BUMPED, None); standin.api(&[first, second]); // The checkout: the hub's repository is the stand-in, the lock is @@ -505,6 +570,14 @@ impl Pinned { cell.socket_patch(&standin.origin(), args, &env) } + /// `socket-patch ` for a command of vendored mode, which downloads + /// the patched jar from the URL the grant has for it on the patch host: + /// that host is the stand-in here. + fn vendored(&self, args: &[&str]) -> Ran { + let origin = self.standin.origin(); + self.socket_patch(&[args, &["--patch-server-url", &origin]].concat()) + } + /// The command where it writes no entry for the hub, in a tree without /// `pom.xml`: it reports the patch skipped, gives one warning, `code` /// with the reason `why` and the words that the Bazel build keeps the @@ -619,7 +692,7 @@ impl Pinned { let mut twin = self.cell.twin(); let rogue = StandIn::start(); let tampered = victim("TAMPERED"); - let (other, served) = grant(&rogue, VERSION, Some(&tampered)); + let (other, served) = grant(&rogue, &self.run, VERSION, Some(&tampered)); rogue.api(&[served]); let host = format!("{PATCH_HOST}/"); twin.route_downloads(&[ @@ -918,6 +991,307 @@ fn a_version_bump_of_the_patched_artifact() { ); } +/// The command of vendored mode. +const VENDORED: [&str; 5] = ["get", PURL, "--mode", "vendored", "--yes"]; +/// The pair that keeps the directory of the committed jars out of the +/// packages of the workspace, as the `.bazelignore` the command creates. +const JARS_IGNORED: &str = + "# socket-patch: patched Maven jars for a Bazel hub, not Bazel packages \ + (to opt out, comment out the next line)\n.socket/vendor/maven\n"; + +/// The block of `MODULE.bazel` for `patch` in vendored mode, with its last +/// line break: the repository is the directory of the patch in the +/// checkout, and no host is named. +fn vendored_block(patch: &Granted) -> String { + let uuid = &patch.uuid; + format!( + r#"# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_local_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:local.bzl", "local_repository") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# {PURL}, Socket patch {uuid} +socket_patch_local_repository( + name = "socket_patch_{REPOSITORY}", + path = ".socket/vendor/maven/{uuid}", +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# {GROUP}:{VICTIM} at {VERSION}: run `socket-patch rollback {PURL}`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + {REPOSITORY} = "socket_patch_{REPOSITORY}", +) +# <<< socket-patch <<< +"# + ) +} + +impl Pinned { + /// The committed jar of the patch, from the checkout. + fn committed_jar(&self) -> String { + let uuid = &self.patch.uuid; + format!(".socket/vendor/maven/{uuid}/file/{VICTIM}-{VERSION}.jar") + } + + /// A finished command of vendored mode, `ran`, in a checkout whose + /// files were `before`: it vendored the one patch and warned of + /// nothing, and wrote the directory of the patch with the jar the + /// grant pins, the block after one blank line, the line of + /// `.bazelignore` and the ledger, and no other file. Gives the files of + /// the checkout. + fn vendored_by(&self, ran: &Ran, before: &Tree) -> Tree { + let (test, said) = (&self.cell.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "success", "{test}: {said}"); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{test}: {said}"); + assert_eq!(ran.envelope["warnings"], Value::Null, "{test}: {said}"); + let unit = format!(".socket/vendor/maven/{}", self.patch.uuid); + let written = [ + ".bazelignore".to_string(), + format!("{unit}/.gitignore"), + format!("{unit}/REPO.bazel"), + format!("{unit}/file/BUILD.bazel"), + self.committed_jar(), + ".socket/vendor/state.json".to_string(), + MODULE.to_string(), + ]; + let vendored = self.cell.tree(); + assert_eq!(changed(before, &vendored), written, "{test}: {said}"); + let text = + |tree: &Tree, file: &str| String::from_utf8(tree[file].clone()).expect("a text file"); + let with_block = format!("{}\n{}", text(before, MODULE), vendored_block(&self.patch)); + assert_eq!(text(&vendored, MODULE), with_block, "{test}: {said}"); + assert_eq!(text(&vendored, ".bazelignore"), JARS_IGNORED, "{test}"); + let build = format!( + "filegroup(\n name = \"file\",\n srcs = [\"{VICTIM}-{VERSION}.jar\"],\n \ + visibility = [\"//visibility:public\"],\n)\n" + ); + assert_eq!(text(&vendored, &written[3]), build, "{test}"); + let jar = sha256_hex(&vendored[&written[4]]); + assert_eq!(jar, self.patch.sha256, "{test}: not the jar the grant pins"); + vendored + } + + /// The build of a vendored checkout: it prints the marker of the + /// patched jar and changes no file of `vendored`, Bazel's lock + /// included; a `--lockfile_mode=error` build passes; and no jar was + /// asked of the patch host or of the hub's repository for it. + fn builds_the_committed_jar(&self, vendored: &Tree) { + let test = &self.cell.test; + let asked = |route: &String| self.standin.asked(route); + let before = [&self.patch.route, &self.upstream_route].map(asked); + self.cell.builds_patched(vendored, &self.patch.marker); + let after = [&self.patch.route, &self.upstream_route].map(asked); + assert_eq!(after, before, "{test}: the build fetched a jar"); + assert_eq!(after[0], 0, "{test}: the patch host was asked for the jar"); + } +} + +/// Vendored mode in a checkout that only Bazel builds: the command commits +/// the patched jar and the block that puts its directory in the place of +/// the hub's repository, the build is patched from the checkout alone, the +/// audit holds the committed jar to the patch, and the undo puts every +/// file back. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn a_vendored_patch_in_a_tree_only_bazel_builds() { + let test = "maven::a_vendored_patch_in_a_tree_only_bazel_builds"; + let Some(flow) = Pinned::open(test, false, &|_, _| {}) else { + return; + }; + let before = flow.builds_upstream(); + // As in hosted mode: nothing in the checkout of a Bazel before 7.5.0 + // says that it has `override_repo`, and the command then fails for + // the reason a hosted run warns of, before it downloads the patch + // (the failure is the first event of the purl), and writes nothing. + if flow.cell.numbers() < (7, 5, 0) { + let get = flow.vendored(&VENDORED); + let said = &get.dump; + assert_eq!(get.code, 1, "{test}: {said}"); + let failed = event_for(&get.envelope, PURL); + let why = format!("{NO_RELEASE}. {KEEPS}"); + assert_eq!( + (&failed["action"], &failed["errorCode"], &failed["error"]), + (&json!("failed"), &json!("maven_bazel_release"), &json!(why)), + "{test}: {said}" + ); + assert_eq!( + changed(&before, &flow.cell.tree()), + NOTHING, + "{test}: {said}" + ); + } + let before = flow.names_its_bazel(); + + let get = flow.vendored(&VENDORED); + let vendored = flow.vendored_by(&get, &before); + let downloads = flow.standin.asked(&flow.patch.archive); + assert_eq!( + downloads, 1, + "{test}: the jar comes from the patch service, once" + ); + flow.builds_the_committed_jar(&vendored); + + // The directory of the jar is no package of the workspace. + let query = flow.cell.bazel("query", &["//..."]); + let listed = query.stdout(); + assert!( + query.ok() && listed.lines().any(|line| line == CONSUMER), + "{test}: {}", + query.dump() + ); + let under_socket: Vec<&str> = listed.lines().filter(|l| l.contains(".socket")).collect(); + assert_eq!(under_socket, NOTHING, "{test}: {}", query.dump()); + + // `list` and `vex` see the patch, as they see a hosted one. + let run = |cell: &Cell, args: &[&str]| flow.socket_patch_in(cell, &flow.standin, args); + let list = flow.socket_patch(&["list"]); + let listed = event_for(&list.envelope, PURL); + assert_eq!( + (&listed["uuid"], &listed["details"]["mode"]), + (&json!(flow.patch.uuid), &json!("vendored")), + "{test}: {}", + list.dump + ); + let claim = Claim::new(PURL, &flow.patch.uuid, How::Vendored); + flow.cell.stands_alone(run, &claim, true); + + // The audit passes for the committed jar, and fails for another one, + // which Bazel builds all the same: no digest of a directory is + // checked at build time. + let audit = |passes: bool| { + let check = flow.socket_patch(&["vendor", "--check"]); + let said = &check.dump; + let event = event_for(&check.envelope, PURL); + let expected = match passes { + true => (0, "verified", "vendor_check_ok"), + false => (1, "failed", "vendor_check_failed"), + }; + let found = (check.code, &event["action"], &event["errorCode"]); + assert_eq!( + found, + (expected.0, &json!(expected.1), &json!(expected.2)), + "{test}: {said}" + ); + }; + audit(true); + let jar = flow.committed_jar(); + flow.cell + .write(&jar, victim(&format!("CHANGED {}", flow.run))); + audit(false); + flow.cell.builds(&format!("OUT: CHANGED {}", flow.run)); + flow.cell.write(&jar, &vendored[&jar]); + audit(true); + assert_eq!(changed(&vendored, &flow.cell.tree()), NOTHING, "{test}"); + + // A second machine with the checkout, and no host to ask: the + // stand-in is stopped, the output base is new, and the repository + // cache, which the machines share, holds the hub's own jars and no + // copy of the patched one. + let twin = flow.cell.twin(); + let Pinned { + cell, + standin, + patch, + upstream, + started, + .. + } = flow; + let origin = standin.stop(); + twin.builds(&patch.marker); + let lock = std::fs::read_to_string(twin.path("maven_install.json")).expect("the lock"); + let lock = Lock::parse(&lock).expect("the lock"); + let fetched = lock + .plain_jar(GROUP, VICTIM) + .and_then(|jar| jar.jar_sha256.clone()); + let fetched = fetched.expect("the sha256 of the upstream jar"); + assert_eq!( + (twin.cached(&fetched), twin.cached(&patch.sha256)), + (true, false), + "{test}: the repository cache holds the hub's jar, and not the patched one" + ); + drop(twin); + + // The undo: every file is the one of before, and so is the build. + let undo = cell.socket_patch(&origin, &["vendor", "--revert", "--yes"], &[]); + cell.undone(&undo, "removed", &before, &upstream); + println!( + "{test}: Bazel {} built {upstream:?}, then {:?} from the jar `get --mode vendored` \ + committed under .socket/vendor/maven, also on a second machine with no host to ask; \ + `bazel query //...` listed no package there, a `--lockfile_mode=error` build passed, \ + `vendor --check` failed for a changed jar, which Bazel built; `vendor --revert` \ + restored all {} files and the first build; {:?}", + cell.release(), + patch.marker, + before.len(), + started.elapsed() + ); +} + +/// From hosted mode to vendored mode and back: one entry for the jar at +/// every step, and the checkout of the hosted command again at the end of +/// the way back. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn a_hub_goes_from_hosted_to_vendored_and_back() { + let test = "maven::a_hub_goes_from_hosted_to_vendored_and_back"; + let Some(flow) = Pinned::open(test, false, &|_, _| {}) else { + return; + }; + flow.builds_upstream(); + let before = flow.names_its_bazel(); + let hosted = flow.pins(&before, &[MODULE]); + + // `vendor` takes the hosted patch over: its entry is the only one. + let eject = flow.vendored(&["vendor"]); + let vendored = flow.vendored_by(&eject, &before); + flow.builds_the_committed_jar(&vendored); + + // And back: the hosted command takes the vendored entry, its + // directory, its line and its ledger entry out, and says so. + let back = flow.socket_patch(&["get", PURL, "--mode", "hosted", "--yes"]); + let said = &back.dump; + assert_eq!(back.code, 0, "{test}: {said}"); + assert_eq!(back.envelope["summary"]["applied"], 1, "{test}: {said}"); + let warned: Vec<&str> = back.envelope["warnings"] + .as_array() + .into_iter() + .flatten() + .filter_map(|warning| warning["code"].as_str()) + .collect(); + assert_eq!( + warned, + ["redirect_takeover_reverted_vendored"], + "{test}: {said}" + ); + assert_eq!( + changed(&hosted, &flow.cell.tree()), + NOTHING, + "{test}: {said}" + ); + flow.builds_patched(&hosted); + + // Vendored again, by the command of the mode, and undone by `rollback`. + let again = flow.vendored(&VENDORED); + let same = flow.vendored_by(&again, &before); + assert_eq!(changed(&vendored, &same), NOTHING, "{test}"); + let undo = flow.socket_patch(&["rollback", "--yes"]); + flow.cell + .undone(&undo, "rolledBack", &before, &flow.upstream); + println!( + "{test}: Bazel {} built {:?}, then {:?} from the checkout after `vendor` took the \ + hosted entry over, and from the patch host after `get --mode hosted` took the \ + vendored one over; `rollback` restored all {} files and the first build; {:?}", + flow.cell.release(), + flow.upstream, + flow.patch.marker, + before.len(), + flow.started.elapsed() + ); +} + /// What the checkout builds in the artifact's place, and its package. const OWN_MARKER: &str = "OUT: OWN of the checkout"; const OWN_BUILD: &str = r#"load("@rules_java//java:defs.bzl", "java_library") diff --git a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs index 4bb23fb56..9d67f37b4 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -658,6 +658,66 @@ fn a_pinned_hub_gets_its_block_and_the_undo_takes_it_out() { assert!(!person.stderr.contains("Warning: pkg:maven"), "{person:?}"); } +/// Makes the checkout of [`pinned`] as a vendored run left it for the hub: +/// the block with the entry of vendored mode, the directory of the jar and +/// its line of `.bazelignore`; with `maven`, beside a `pom.xml`. +fn vendored(machine: &Machine, maven: bool) { + let unit = format!(".socket/vendor/maven/{UUID}"); + let hosted = "socket_patch_http_file(\n"; + let (head, entry) = BLOCK.split_once(hosted).expect("the entry"); + let (_, tail) = entry.split_once(")\n").expect("its end"); + let vendored = format!( + "{}socket_patch_local_repository(\n name = \ + \"socket_patch_dev_socket_fixture_victim_1_10_0\",\n path = \"{unit}\",\n)\n{tail}", + head.replace( + "socket_patch_http_file = use_repo_rule(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_file\")", + "socket_patch_local_repository = use_repo_rule(\"@bazel_tools//tools/build_defs/repo:local.bzl\", \"local_repository\")", + ) + ); + let ignore = "# socket-patch: patched Maven jars for a Bazel hub, not Bazel packages (to opt \ + out, comment out the next line)\n.socket/vendor/maven\n"; + machine.make(&pinned(), maven, false); + let proj = machine.root.join("proj"); + std::fs::create_dir_all(proj.join(&unit).join("file")).expect("the directory"); + for (path, text) in [ + ("MODULE.bazel".to_string(), format!("{HUB}\n{vendored}")), + (".bazelignore".to_string(), ignore.to_string()), + (format!("{unit}/REPO.bazel"), "# a repository\n".to_string()), + (format!("{unit}/file/BUILD.bazel"), String::new()), + (format!("{unit}/file/victim-1.10.0.jar"), "jar".to_string()), + ] { + std::fs::write(proj.join(path), text).expect("write it"); + } +} + +/// A hosted run puts its entry in the place of the vendored one that the +/// block holds for the jar, and removes what vendored mode kept for the +/// hub: the directory of the jar, which nothing names any more, and its +/// line of `.bazelignore`. Beside a Maven build no undo of a vendored +/// patch does that, since the ledger entry there is the Maven build's. +/// A hosted scan, which finds the jar in the hub's lock, does the same. +#[test] +fn a_hosted_run_removes_the_jar_vendored_mode_kept_for_the_hub() { + let machine = Machine::start(); + for command in [COMMANDS[0], &SCAN[..]] { + vendored(&machine, true); + let ran = machine.step(command); + assert_eq!(ran.code, Some(0), "{ran:?}"); + assert_eq!(ran.envelope()["warnings"], Value::Null, "{ran:?}"); + let with_block = format!("{HUB}\n{BLOCK}"); + assert_eq!( + String::from_utf8_lossy(&ran.wrote[MODULE]), + with_block, + "{ran:?}" + ); + let left = machine.files(); + let of_the_hub = + |path: &&String| path.contains(".socket/vendor") || path.ends_with("ignore"); + let kept: Vec<&String> = left.keys().filter(of_the_hub).collect(); + assert_eq!(kept, Vec::<&String>::new(), "{ran:?}"); + } +} + /// The Bazel files of a checkout, each with its text. type Files = Vec<(&'static str, String)>; @@ -1531,6 +1591,44 @@ fn a_hosted_scan_leaves_a_stale_entry_that_the_policy_filters() { } } +/// The hub's lock moves on after a vendored patch, and Bazel stops at the +/// entry as it does at a hosted one. A hosted scan leaves that entry: the +/// directory of its jar and its ledger entry are vendored mode's, whose +/// undo takes them out with it. The scan changes nothing of the hub and +/// warns of no restore that failed, alone and beside a Maven build, which +/// it pins as it does without the workspace. +#[test] +fn a_hosted_scan_leaves_a_stale_entry_of_vendored_mode() { + let machine = Machine::start(); + let moved = lock(&[("consumer", "2.0"), ("victim", "1.11.0")]); + let of_the_hub = |machine: &Machine| -> BTreeMap> { + let hub = |path: &str| { + path.contains(".socket/vendor") || path.ends_with("ignore") || path == MODULE + }; + let files = machine.files().into_iter(); + files.filter(|(path, _)| hub(path)).collect() + }; + for maven in [false, true] { + vendored(&machine, maven); + std::fs::write(machine.root.join("proj/maven_install.json"), &moved).expect("the lock"); + let held = of_the_hub(&machine); + assert_eq!(held.len(), 5, "{held:?}"); + for scan in [&[&SCAN[..], &["--dry-run"]].concat()[..], &SCAN] { + let scan = machine.step(scan); + let said = scan.envelope(); + let pins = match maven { + true => vec![PURL.to_string()], + false => vec![], + }; + let purls = event_triples(&said).into_iter().map(|(purl, ..)| purl); + assert_eq!(purls.collect::>(), pins, "{maven}: {scan:?}"); + let codes = warning_codes(&said); + assert_eq!((scan.code, codes), (Some(0), vec![]), "{maven}: {scan:?}"); + assert_eq!(of_the_hub(&machine), held, "{maven}: {scan:?}"); + } + } +} + /// A checkout that Gradle or Maven builds too. A hub's jar with a patch is /// a patch of the run like one it found installed, so the scan writes for /// it what `get ` writes there: the Gradle pin beside the block, or diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index 95ef1de0e..9bb41cd63 100644 --- a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs +++ b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs @@ -1695,8 +1695,11 @@ fn gradle_vendor_395_repair_refuses_a_linked_gradle_tree() { } /// A rules_jvm_external hub of a Bazel workspace builds the jar its own -/// lock pins, not the vendored one. `vendor` beside such a hub warns once -/// for each jar the hub builds, in the envelope or as a line a person +/// lock pins, not the one vendored for Maven. Here nothing in the checkout +/// says which Bazel builds it, so `vendor` writes no entry for the hub +/// ([`vendor_gives_a_pinned_bazel_hub_the_patched_jar`] is the checkout +/// where it does): beside such a hub it warns once for each jar the hub +/// builds, with the reason, in the envelope or as a line a person /// reads, and its events and every file it writes are those of the same /// run without the workspace. A hub that does not build a vendored jar /// adds nothing. @@ -1742,14 +1745,13 @@ fn a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else() { let (events, tree, warnings) = vendor(Some(lock("foo"))); assert_eq!((&events, &tree), (&without.0, &without.1)); let detail = format!( - "{0}: Bazel takes this artifact from maven_install.json (hub \"maven\", `maven.install` \ - at MODULE.bazel:3), which pins the upstream jar, and this command does not patch a \ - rules_jvm_external hub: the Bazel build stays unpatched whatever it did for another \ - build of the checkout. `socket-patch get {0} --mode hosted` at the Bazel root patches \ - a pinned hub", + "{0}: no file of the checkout says that Bazel 7.4.0 or later builds it, and an older \ + Bazel fails on the `override_repo` an entry needs: name the release in `.bazelversion`. \ + socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the \ + upstream jar", purl("foo") ); - let warning = serde_json::json!({ "code": "maven_bazel_hub_unpatched", "detail": detail }); + let warning = serde_json::json!({ "code": "maven_bazel_release", "detail": detail }); assert_eq!(warnings, [without.2, vec![warning]].concat()); // A person reads it once, on stderr, and not under `--silent`; a // program reads it in the envelope alone. @@ -1800,15 +1802,24 @@ fn a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else() { assert_eq!(others(Some(lock("foo"))), others(None)); } -/// Vendored mode patches no rules_jvm_external hub, and takes none over. -/// The entry that hosted mode keeps for a jar in the block of -/// `MODULE.bazel` is a hosted pin of that jar, and `vendor` and `vendor +/// Beside a Maven build, vendored mode ejects no hosted patch of a +/// rules_jvm_external hub. The entry that hosted mode keeps for a jar in +/// the block of `MODULE.bazel` is a hosted pin of that jar, and where +/// vendored mode writes no entry for the hub, `vendor` and `vendor /// --revert` leave it as it is: the Bazel build keeps the patched jar. /// Everything else is the run without the workspace, and nothing is said -/// of a hub that the block patches. That holds for an entry alone, and -/// for one whose patch a hosted run also pinned in the poms of the -/// reactor: `vendor` takes the poms' part of that pin over, as it does -/// without the workspace. +/// of a hub that the block patches. That holds for an entry alone, and for +/// one whose patch a hosted run also pinned in the poms of the reactor: +/// `vendor` takes the poms' part of that pin over, as it does without the +/// workspace. +/// +/// A hub that vendored mode can patch gets the vendored entry in the place +/// of the hosted one in the run that vendors the same patch for the Maven +/// build: one entry for the jar, which `vendor --revert` takes out. +/// +/// In a checkout that only Bazel builds, the hub is the build `vendor` +/// patches: its entry takes the place of the hosted one, and where it can +/// write none the hosted entry stays and nothing is written. #[test] fn vendor_leaves_the_hosted_entry_of_a_bazel_hub_in_place() { let module = format!( @@ -1942,4 +1953,675 @@ override_repo( assert_eq!(beside.3.as_deref(), Some(module.as_bytes()), "{in_poms}"); } } + + // A hub that vendored mode can patch, beside the Maven build that the + // run vendors the patch for (a patch of the manifest, and one that the + // poms pin too): the vendored entry is in the place of the hosted one, + // and the undo of the vendoring takes it out. + for in_poms in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + pinned_hub(root, "foo"); + write(root, "proj/MODULE.bazel", module.as_bytes()); + let records = match in_poms { + true => { + pin_poms(root); + serve_record(root) + } + false => nowhere.clone(), + }; + let held = || std::fs::read_to_string(root.join("proj/MODULE.bazel")).unwrap(); + ok(root, &["vendor", "--proxy-url", &records]); + assert_eq!(held(), format!("{HUB_MODULE}\n{FOO_BLOCK}"), "{in_poms}"); + assert!(hosted(root).is_empty(), "{in_poms}"); + ok(root, &["vendor", "--revert", "--proxy-url", &records]); + assert_eq!(held(), HUB_MODULE, "{in_poms}"); + } + + for declined in [true, false] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + only_bazel(root); + pinned_hub(root, "foo"); + write(root, "proj/MODULE.bazel", module.as_bytes()); + // Nothing says which Bazel builds the checkout. + for gone in ["proj/.bazelversion", "proj/MODULE.bazel.lock"] { + if declined { + std::fs::remove_file(root.join(gone)).unwrap(); + } + } + let (records, before) = (serve_record(root), snapshot(root)); + let (code, env) = socket(root, &["vendor", "--proxy-url", &records]); + let (failed, after) = (&env["events"][0], snapshot(root)); + let pins = usize::from(declined); + assert_eq!(code, Some(pins as i32), "{declined}: {env}"); + let entry = [serde_json::json!(["MODULE.bazel"])]; + assert_eq!(hosted(root), entry[..pins], "{declined}: {env}"); + if declined { + assert_eq!(failed["errorCode"], "maven_bazel_release", "{env}"); + let left = "socket-patch left the entry that MODULE.bazel holds for it as it is"; + let why = failed["error"].as_str().unwrap_or_default(); + assert!(why.ends_with(left), "{env}"); + assert_eq!(after, before, "{env}"); + } else { + let vendored = format!("{HUB_MODULE}\n{FOO_BLOCK}"); + let held = after["MODULE.bazel"].as_deref(); + assert_eq!(held, Some(vendored.as_bytes()), "{env}"); + } + } +} + +/// The module file of a checkout whose hub is pinned, and the files that +/// say which Bazel builds it and which release of the ruleset Bazel +/// selected: the checkout vendored mode writes its entry for. +const HUB_MODULE: &str = "bazel_dep(name = \"rules_jvm_external\", version = \"7.2\")\n\ + maven = use_extension(\"@rules_jvm_external//:extensions.bzl\", \"maven\")\n\ + maven.install(lock_file = \"//:maven_install.json\")\n"; + +fn pinned_hub(root: &Path, artifact: &str) { + let lock = format!( + "{{\"artifacts\": {{\"org.example:{artifact}\": {{\"shasums\": {{\"jar\": \"00\"}}, \ + \"version\": \"1.0\"}}}}, \"repositories\": {{\"https://repo.example/maven2/\": \ + [\"org.example:{artifact}\"]}}, \"version\": \"3\"}}\n" + ); + let bcr = "https://bcr.bazel.build/modules/rules_jvm_external"; + let module_lock = format!( + "{{\"lockFileVersion\": 13, \"registryFileHashes\": {{\"{bcr}/7.2/MODULE.bazel\": \"1\", \ + \"{bcr}/7.2/source.json\": \"2\"}}}}\n" + ); + write(root, "proj/MODULE.bazel", HUB_MODULE.as_bytes()); + write(root, "proj/maven_install.json", lock.as_bytes()); + write(root, "proj/.bazelversion", b"7.7.2\n"); + write(root, "proj/MODULE.bazel.lock", module_lock.as_bytes()); +} + +/// The fixture without its Maven build: a checkout that only Bazel builds. +fn only_bazel(root: &Path) { + for gone in ["proj/pom.xml", "proj/a/pom.xml"] { + std::fs::remove_file(root.join(gone)).unwrap(); + } + std::fs::remove_dir(root.join("proj/a")).unwrap(); + std::fs::remove_dir_all(root.join("proj/.mvn")).unwrap(); +} + +/// The directory vendored mode keeps for the hub's jar of `foo`, the +/// block that names it, with its last line break, and the pair of +/// `.bazelignore`. +const FOO_UNIT: &str = ".socket/vendor/maven/1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f"; +const FOO_BLOCK: &str = r#"# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_local_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:local.bzl", "local_repository") + +socket_patch_maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") + +# pkg:maven/org.example/foo@1.0, Socket patch 1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f +socket_patch_local_repository( + name = "socket_patch_org_example_foo_1_0", + path = ".socket/vendor/maven/1d3c1fd2-7b4e-4c1a-9f0e-2a3b4c5d6e7f", +) + +# If Bazel stops at the next line ("does not generate repository"), the hub's lock no longer pins +# org.example:foo at 1.0: run `socket-patch rollback pkg:maven/org.example/foo@1.0`. +# Do not change it to inject_repo(): the build would pass without the patch. +override_repo( + socket_patch_maven, + org_example_foo_1_0 = "socket_patch_org_example_foo_1_0", +) +# <<< socket-patch <<< +"#; +const JARS_IGNORED: &str = + "# socket-patch: patched Maven jars for a Bazel hub, not Bazel packages \ + (to opt out, comment out the next line)\n.socket/vendor/maven\n"; + +/// Vendored mode patches a pinned rules_jvm_external hub: `vendor` commits +/// the patched jar in a directory of its own, which the block at the end +/// of `MODULE.bazel` puts in the place of the hub's repository, and names +/// the directory in `.bazelignore`. That holds in a checkout only Bazel +/// builds, where the hub's jar is the vendored artifact, and beside a +/// Maven build, which is vendored exactly as without the workspace. +/// `vendor --check` fails for a committed jar that is not the patched one +/// and for a BUILD file that is not the one written; `list` and `vex` see +/// the patch; `vendor --revert` and `rollback` restore every byte. +#[test] +fn vendor_gives_a_pinned_bazel_hub_the_patched_jar() { + for alone in [true, false] { + // Without the workspace: what the Maven build alone gets. + let without = tempfile::tempdir().unwrap(); + fixture(without.path(), Shape::Reactor, &[("foo", FOO_UUID)]); + let maven_alone = (!alone).then(|| { + let env = ok(without.path(), &["vendor"]); + ( + events(&env), + env["warnings"].clone(), + snapshot(without.path()), + ) + }); + + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + if alone { + only_bazel(root); + } + pinned_hub(root, "foo"); + let pristine = snapshot(root); + let read = |rel: &str| std::fs::read(root.join("proj").join(rel)).ok(); + let text = |rel: &str| read(rel).map(|bytes| String::from_utf8(bytes).unwrap()); + + // A dry run says what would be vendored and writes nothing. + let env = ok(root, &["vendor", "--dry-run"]); + assert_eq!(env["warnings"], serde_json::Value::Null, "{alone}: {env}"); + assert_eq!(snapshot(root), pristine, "{alone}"); + + let env = ok(root, &["vendor"]); + assert_eq!(env["summary"]["applied"], 1, "{alone}: {env}"); + assert_eq!(env["warnings"], serde_json::Value::Null, "{alone}: {env}"); + let module = text("MODULE.bazel").unwrap(); + assert_eq!(module, format!("{HUB_MODULE}\n{FOO_BLOCK}"), "{alone}"); + assert_eq!( + text(".bazelignore").as_deref(), + Some(JARS_IGNORED), + "{alone}" + ); + let build = "filegroup(\n name = \"file\",\n srcs = [\"foo-1.0.jar\"],\n \ + visibility = [\"//visibility:public\"],\n)\n"; + let unit = |rel: &str| format!("{FOO_UNIT}/{rel}"); + assert_eq!(text(&unit("file/BUILD.bazel")).as_deref(), Some(build)); + assert_eq!(text(&unit(".gitignore")).as_deref(), Some("!*\n")); + let repo = text(&unit("REPO.bazel")).unwrap(); + assert!(repo.lines().all(|line| line.starts_with("# ")), "{repo}"); + let patched = jar(b"NOTICE foo\nPATCHED\n"); + let committed = read(&unit("file/foo-1.0.jar")).unwrap(); + let notice = |jar: &[u8]| { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(jar)).unwrap(); + let mut text = String::new(); + std::io::Read::read_to_string(&mut zip.by_name(MEMBER).unwrap(), &mut text).unwrap(); + text + }; + assert_eq!(notice(&committed), notice(&patched), "{alone}"); + // The ledger: the hub's jar as the artifact of a patch that only + // the hub takes, and the Maven tree's beside a Maven build. + let ledger: serde_json::Value = + serde_json::from_slice(&read(".socket/vendor/state.json").unwrap()).unwrap(); + let entry = &ledger["entries"][purl("foo")]; + let recorded = [ + &entry["ecosystem"], + &entry["flavor"], + &entry["artifact"]["path"], + ]; + let hub = [ + serde_json::json!("maven"), + serde_json::json!("bazel"), + serde_json::json!(unit("file/foo-1.0.jar")), + ]; + match alone { + true => assert_eq!(recorded, hub.each_ref(), "{ledger}"), + false => assert_eq!(entry["ecosystem"], "jvm", "{ledger}"), + } + // Beside the Maven build: its events, and every file but those of + // the hub, are the ones of the run without the workspace. + if let Some((events_alone, warnings, tree)) = &maven_alone { + assert_eq!((&events(&env), &env["warnings"]), (events_alone, warnings)); + let mut beside = snapshot(root); + let of_the_hub = |rel: &String| { + rel.starts_with(".socket/vendor/maven/") + || [ + "MODULE.bazel", + "MODULE.bazel.lock", + "maven_install.json", + ".bazelversion", + ".bazelignore", + ] + .contains(&rel.as_str()) + }; + beside.retain(|rel, _| !of_the_hub(rel)); + assert_eq!(&beside, tree); + } + let vendored = snapshot(root); + + // A second run changes nothing, and the audit passes. + let again = ok(root, &["vendor"]); + let in_sync = ( + purl("foo"), + "skipped".to_string(), + "already_vendored".to_string(), + ); + assert_eq!(events(&again), [in_sync], "{alone}: {again}"); + assert_eq!(snapshot(root), vendored, "{alone}"); + let (code, check) = socket(root, &["vendor", "--check"]); + assert_eq!(code, Some(0), "{alone}: {check}"); + // And `repair` finds nothing to do: the directory that `MODULE.bazel` + // names is the ledger entry's, also where that entry is the Maven + // build's. + let repaired = ok(root, &["repair"]); + assert_eq!(snapshot(root), vendored, "{alone}: {repaired}"); + // `list` and `vex` see the patch. + let (_, list) = socket(root, &["list"]); + assert_eq!(list["events"][0]["purl"], purl("foo"), "{alone}: {list}"); + let vex = root.join("vex.json"); + let document = [ + "vex", + "-O", + vex.to_str().unwrap(), + "--product", + "pkg:generic/x@1", + ]; + ok(root, &document); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&vex).unwrap()).unwrap(); + assert_eq!(doc["statements"][0]["status"], "not_affected", "{doc}"); + + // A committed jar that is not the patched one, one that carries + // the file of the patch beside a member the patched jar has not, + // and a BUILD file that names another jar: the audit fails for + // each, and names it. + let held = std::io::Cursor::new(committed.clone()); + let mut grown = zip::ZipWriter::new_append(held).unwrap(); + let plain = zip::write::SimpleFileOptions::default(); + grown.start_file("other/Other.class", plain).unwrap(); + let grown = grown.finish().unwrap().into_inner(); + assert_eq!(notice(&grown), notice(&patched)); + let planted = grown.clone(); + for (rel, other) in [ + ("file/foo-1.0.jar", jar(b"NOTICE foo\n")), + ("file/foo-1.0.jar", grown), + ( + "file/BUILD.bazel", + build.replace("foo-1.0", "other").into_bytes(), + ), + ] { + let held = read(&unit(rel)).unwrap(); + write(root, &format!("proj/{}", unit(rel)), &other); + let (code, check) = socket(root, &["vendor", "--check"]); + assert_eq!(code, Some(1), "{alone} {rel}: {check}"); + let failed = &check["events"][0]; + assert_eq!(failed["errorCode"], "vendor_check_failed", "{rel}: {check}"); + if !alone || rel.ends_with("BUILD.bazel") { + let why = failed["reason"].as_str().unwrap_or_default(); + assert!(why.contains(&unit(rel)), "{alone} {rel}: {check}"); + } + write(root, &format!("proj/{}", unit(rel)), &held); + } + // A `MODULE.bazel` without the entry, one whose block was changed + // by hand, and a lock that no longer pins the jar at the version of + // the patch: the Bazel build takes another jar or stops, and the + // audit says which, with a remedy that works. + let rollback = format!("run `socket-patch rollback {}`", purl("foo")); + let lock = text("maven_install.json").unwrap(); + let bumped = lock.replace("\"version\": \"1.0\"", "\"version\": \"1.1\""); + let edited = module.replace("# Do not change", "# Do change"); + for (file, held, other, why) in [ + ( + "MODULE.bazel", + &module, + HUB_MODULE, + "MODULE.bazel no longer names", + ), + ("MODULE.bazel", &module, &edited, "changed by hand"), + ("maven_install.json", &lock, &bumped, rollback.as_str()), + ] { + assert_ne!(held.as_str(), other, "{file}"); + write(root, &format!("proj/{file}"), other.as_bytes()); + let (code, check) = socket(root, &["vendor", "--check"]); + assert_eq!(code, Some(1), "{alone} {why}: {check}"); + let reason = check["events"][0]["reason"].as_str().unwrap_or_default(); + assert!(reason.contains(why), "{alone} {why}: {check}"); + // The hub was the only build of the patch: `vendor` has nothing + // to vendor it for, and names the same remedy. + if alone && file == "maven_install.json" { + let (code, env) = socket(root, &["vendor"]); + let failed = &env["events"][0]; + assert_eq!(code, Some(1), "{env}"); + assert_eq!(failed["errorCode"], "vendor_jvm_shape_unsupported", "{env}"); + let error = failed["error"].as_str().unwrap_or_default(); + assert!(error.ends_with(why), "{env}"); + } + write(root, &format!("proj/{file}"), held.as_bytes()); + } + assert_eq!(snapshot(root), vendored, "{alone}"); + + // Beside a Maven build `vex` hashes the jar of the Maven tree, as + // it does without the workspace: one that is not the patched jar + // is not attested, whatever the hub's copy holds. + if !alone { + let tree = format!("{FOO_MAVEN_TREE}/foo-1.0-socket.1d3c1fd2.jar"); + let held = std::fs::read(root.join(&tree)).unwrap(); + write(root, &tree, &jar(b"NOTICE foo\n")); + let (_, env) = socket(root, &document); + assert_eq!(env["summary"]["verified"], 0, "{env}"); + write(root, &tree, &held); + } + + // A directory that is lost whole comes back with every file: by + // `repair` where its jar is the vendored artifact, and by the next + // `vendor` beside a Maven build, which gives the hub the jar of the + // Maven tree again. That run also drops the directory an earlier + // patch of the jar left behind, which nothing names any more. + std::fs::remove_dir_all(root.join("proj").join(FOO_UNIT)).unwrap(); + let stale = ".socket/vendor/maven/0e77a000-0000-4000-8000-0000000000a1"; + if !alone { + write( + root, + &format!("proj/{stale}/REPO.bazel"), + b"# an earlier patch\n", + ); + write(root, &format!("proj/{stale}/file/foo-1.0.jar"), b"jar"); + } + let (code, check) = socket(root, &["vendor", "--check"]); + assert_eq!(code, Some(1), "{alone}: {check}"); + let back = ok(root, if alone { &["repair"] } else { &["vendor"] }); + assert!(!root.join("proj").join(stale).exists(), "{alone}: {back}"); + if !alone { + let rebuilt = ( + purl("foo"), + "skipped".to_string(), + "vendor_artifact_rebuilt".to_string(), + ); + assert!(events(&back).contains(&rebuilt), "{back}"); + } + let now = snapshot(root); + let differ: Vec<&String> = now + .keys() + .chain(vendored.keys()) + .filter(|rel| now.get(*rel) != vendored.get(*rel)) + .collect(); + assert_eq!(differ, Vec::<&String>::new(), "{alone}: {back}"); + + // The undo, by each command: every byte and directory of before. + // `rollback` and `remove` also drop the patch from the run's + // manifest, which is no file of the comparison and is put back. + // The same after the hub's lock moved on, where Bazel stops at the + // entry: the undo takes the stale entry out with its directory, + // which no scan does. + let manifest = root.join("proj/.socket/manifest.json"); + let patches = std::fs::read(&manifest).unwrap(); + let foo = purl("foo"); + let undos = [ + &["vendor", "--revert"][..], + &["rollback", &foo], + &["remove", &foo], + ]; + for (undo, stale) in undos + .iter() + .flat_map(|undo| [(*undo, false), (*undo, true)]) + { + std::fs::write(&manifest, &patches).unwrap(); + ok(root, &["vendor"]); + assert_eq!(snapshot(root), vendored, "{alone} {undo:?}"); + if stale { + write(root, "proj/maven_install.json", bumped.as_bytes()); + } + let undone = ok(root, undo); + write(root, "proj/maven_install.json", lock.as_bytes()); + assert_eq!(snapshot(root), pristine, "{alone} {undo:?} {stale}"); + // No installed tree holds the jar of a hub: nothing is said of + // a package-manager install for a patch that only the hub took. + let warned = undone["warnings"].as_array().cloned().unwrap_or_default(); + let reinstall = |warning: &serde_json::Value| warning["code"] == "reinstall_required"; + assert!( + !alone || !warned.iter().any(reinstall), + "{undo:?}: {undone}" + ); + } + + // A jar that waits at the hub's path with no ledger entry is not + // taken for the vendored one, although it carries the patch's + // file: the run fetches the patch's own jar over it. + if alone { + std::fs::write(&manifest, &patches).unwrap(); + write( + root, + &format!("proj/{}", unit("file/foo-1.0.jar")), + &planted, + ); + ok(root, &["vendor"]); + let taken = read(&unit("file/foo-1.0.jar")).unwrap(); + assert_eq!(taken, committed, "the planted jar was vendored"); + ok(root, &["vendor", "--revert"]); + assert_eq!(snapshot(root), pristine); + } + + // What a person reads: every file of the hub among those to commit, + // the step that takes the jar where the hub is the only build, and + // after the undo no step of a package manager. + std::fs::write(&manifest, &patches).unwrap(); + let said = |args: &[&str]| { + let out = spawn(root, args, false); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + assert!(out.status.success(), "{args:?}: {stdout}"); + stdout + }; + let (commit, step) = match alone { + true => ( + "Commit MODULE.bazel, .bazelignore and .socket/vendor/ to", + "Run `bazel build //...` so the build resolves the vendored artifacts \ + (MODULE.bazel names their directory)", + ), + false => ( + "Commit MODULE.bazel, .bazelignore, .socket/vendor/ and the updated lockfiles", + "Reinstall from the updated lockfile", + ), + }; + let vendoring = said(&["vendor"]); + assert!( + vendoring.contains(commit) && vendoring.contains(step), + "{alone}: {vendoring}" + ); + let reverting = said(&["vendor", "--revert"]); + assert!( + reverting.contains("Reverted 1 vendored package.") && !reverting.contains("resync"), + "{alone}: {reverting}" + ); + assert_eq!(snapshot(root), pristine, "{alone}"); + } +} + +/// Beside a Maven build the undo edits the files of two builds: the poms +/// and `.mvn/maven.config` of Maven, and `MODULE.bazel`. They are written +/// together. Where one of them cannot be replaced (its directory takes no +/// new file), the undo fails and every file, the vendored tree, the hub's +/// directory and the ledger are as they were, whichever build the file is +/// of: `MODULE.bazel` and the root pom in the project directory, or the +/// pom of the module in its own. Once every file can be written, the same +/// undo restores every byte. +#[cfg(unix)] +#[test] +fn an_undo_that_cannot_write_a_file_of_either_build_changes_nothing() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + pinned_hub(root, "foo"); + let pristine = snapshot(root); + ok(root, &["vendor"]); + let vendored = snapshot(root); + let manifest = root.join("proj/.socket/manifest.json"); + let patches = std::fs::read(&manifest).unwrap(); + let foo = purl("foo"); + let mode = |dir: &str, mode| { + std::fs::set_permissions(root.join(dir), std::fs::Permissions::from_mode(mode)).unwrap() + }; + let undos = [ + &["vendor", "--revert"][..], + &["rollback", &foo], + &["remove", &foo], + ]; + for dir in ["proj", "proj/a"] { + mode(dir, 0o555); + let probe = root.join(dir).join("probe"); + if std::fs::write(&probe, b"").is_ok() { + eprintln!("skipping: permission bits not enforced (running as root?)"); + std::fs::remove_file(probe).unwrap(); + return mode(dir, 0o755); + } + let ran = undos.map(|undo| { + let (code, env) = socket(root, undo); + let left = snapshot(root); + std::fs::write(&manifest, &patches).unwrap(); + (undo, code, env, left) + }); + mode(dir, 0o755); + for (undo, code, env, left) in ran { + assert_eq!(code, Some(1), "{dir} {undo:?}: {env}"); + let changed: std::collections::BTreeSet<&String> = (left.keys().chain(vendored.keys())) + .filter(|rel| left.get(*rel) != vendored.get(*rel)) + .collect(); + assert!( + changed.is_empty(), + "{dir} {undo:?} changed {changed:?}: {env}" + ); + let why = env.to_string(); + assert!( + why.contains("every file is as it was"), + "{dir} {undo:?}: {env}" + ); + } + } + ok(root, &["vendor", "--revert"]); + assert_eq!(snapshot(root), pristine); +} + +/// The files of that undo are replaced one after the other, under a +/// journal that names them all. A run that ends between two of them (here +/// it is killed there) has removed nothing, and leaves the journal: the +/// next command finishes the replacement before it does anything else, and +/// the undo run again removes the tree, the hub's directory, which no file +/// names any more, and the ledger entry. +#[test] +fn an_undo_killed_between_two_files_is_finished_by_the_next_run() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + pinned_hub(root, "foo"); + let pristine = snapshot(root); + let manifest = root.join("proj/.socket/manifest.json"); + let patches = std::fs::read(&manifest).unwrap(); + let foo = purl("foo"); + let tree = FOO_MAVEN_TREE.strip_prefix("proj/").unwrap(); + for point in [ + "group_commit_journal", + "group_commit_file@1", + "group_commit_file@3", + ] { + std::fs::write(&manifest, &patches).unwrap(); + ok(root, &["vendor"]); + let (mut cmd, _fixture) = command(root, &["rollback", &foo], true); + let killed = cmd.env("SOCKET_PATCH_FAILPOINT", point).output().unwrap(); + assert_eq!(killed.status.code(), Some(86), "{point}: {killed:?}"); + let left = snapshot(root); + for kept in [ + ".socket/vendor/.commit-journal.json".to_string(), + ".socket/vendor/state.json".to_string(), + format!("{FOO_UNIT}/file/foo-1.0.jar"), + format!("{tree}/foo-1.0-socket.1d3c1fd2.jar"), + ] { + assert!(left.contains_key(&kept), "{point}: {kept} is gone"); + } + let undone = ok(root, &["rollback", &foo]); + assert_eq!(snapshot(root), pristine, "{point}: {undone}"); + } +} + +/// Beside a Maven build the hub's directory must survive the commit, as +/// every vendored artifact must: where a rule of the checkout ignores it, +/// the run vendors for the Maven build, writes nothing for the hub and +/// says why. An entry that names a directory git leaves out would fail +/// the Bazel build of every other checkout. +#[test] +fn vendor_beside_a_maven_build_skips_a_hub_directory_that_git_ignores() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fixture(root, Shape::Reactor, &[("foo", FOO_UUID)]); + pinned_hub(root, "foo"); + let proj = root.join("proj"); + let init = std::process::Command::new("git") + .args(["init", "-q"]) + .current_dir(&proj) + .output(); + if !init.is_ok_and(|out| out.status.success()) { + return; + } + write(root, "proj/.gitignore", b".socket/vendor/maven/\n"); + let env = ok(root, &["vendor"]); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let said = ( + purl("foo"), + "skipped".to_string(), + "maven_bazel_hub_unpatched".to_string(), + ); + assert!(events(&env).contains(&said), "{env}"); + let module = std::fs::read_to_string(proj.join("MODULE.bazel")).unwrap(); + assert_eq!(module, HUB_MODULE, "{env}"); + assert!(!proj.join(".socket/vendor/maven").exists(), "{env}"); +} + +/// Where vendored mode cannot show that an entry would work, it writes +/// none, with the code a hosted run gives the same checkout. In a checkout +/// only Bazel builds that is the failure of the patch, and nothing is +/// written; beside a Maven build it is a warning +/// ([`a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else`]). +/// An option about downloads stands against a hosted entry and not against +/// a jar in the checkout. A jar no hub builds is refused as before. +#[test] +fn vendor_declines_for_a_hub_it_cannot_patch() { + let checkout = |artifact: &str| { + let tmp = tempfile::tempdir().unwrap(); + fixture(tmp.path(), Shape::Reactor, &[("foo", FOO_UUID)]); + only_bazel(tmp.path()); + pinned_hub(tmp.path(), artifact); + tmp + }; + let keeps = "socket-patch wrote nothing to MODULE.bazel for it, so the Bazel build keeps the \ + upstream jar"; + // Nothing says which Bazel builds the checkout. + let tmp = checkout("foo"); + let root = tmp.path(); + for gone in ["proj/.bazelversion", "proj/MODULE.bazel.lock"] { + std::fs::remove_file(root.join(gone)).unwrap(); + } + let before = snapshot(root); + let (code, env) = socket(root, &["vendor"]); + assert_eq!(code, Some(1), "{env}"); + let why = format!( + "no file of the checkout says that Bazel 7.4.0 or later builds it, and an older \ + Bazel fails on the `override_repo` an entry needs: name the release in `.bazelversion`. \ + {keeps}" + ); + let failed = ( + purl("foo"), + "failed".to_string(), + "maven_bazel_release".to_string(), + ); + assert_eq!(events(&env), [failed], "{env}"); + assert_eq!(env["events"][0]["error"], why, "{env}"); + assert_eq!(env["warnings"], serde_json::Value::Null, "{env}"); + // A person reads the purl once, before the reason. + let out = spawn(root, &["vendor"], false); + let line = format!("Error: Cannot vendor {}: {why}\n", purl("foo")); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(stderr.matches(&line).count(), 1, "{stderr}"); + assert_eq!(snapshot(root), before); + + // An option that leaves the entry without effect declines, and one + // about downloads does not. + let tmp = checkout("foo"); + let root = tmp.path(); + write(root, "proj/.bazelrc", b"common --ignore_dev_dependency\n"); + let (code, env) = socket(root, &["vendor"]); + assert_eq!(code, Some(1), "{env}"); + assert_eq!( + env["events"][0]["errorCode"], "maven_bazel_no_effect", + "{env}" + ); + write( + root, + "proj/.bazelrc", + b"common --repository_disable_download\n", + ); + let env = ok(root, &["vendor"]); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + + // No hub builds the jar: the refusal of a tree without a JVM build. + let tmp = checkout("other"); + assert_refused(tmp.path(), "no_build_file", "no pom.xml"); } diff --git a/crates/socket-patch-core/src/bazel/ignore.rs b/crates/socket-patch-core/src/bazel/ignore.rs index 5d8807133..785cf81b4 100644 --- a/crates/socket-patch-core/src/bazel/ignore.rs +++ b/crates/socket-patch-core/src/bazel/ignore.rs @@ -1,6 +1,6 @@ -//! The `.bazelignore` lines that keep patched Go module copies, and the -//! patched crates a crate hub builds, out of the packages of a Bazel -//! workspace. +//! The `.bazelignore` lines that keep patched Go module copies, the +//! patched crates a crate hub builds, and the patched Maven jars vendored +//! for a rules_jvm_external hub, out of the packages of a Bazel workspace. //! //! Vendored and agent mode patch a Go module by keeping a copy of it under //! the project's `.socket` directory, which a `go.mod` `replace` points @@ -21,6 +21,14 @@ //! package is none. Only where the module files make such a hub of the //! project's crates: other tools of the ruleset build a crate from that //! package. +//! +//! Vendored mode also keeps the patched jar of a Maven artifact that a +//! rules_jvm_external hub builds in a directory of its own under +//! `.socket/vendor/maven`, with the BUILD file that makes it the +//! repository Bazel links to ([`super::maven`]). Without a line Bazel +//! reads that file as a package of the workspace too: `bazel query +//! //...` lists it (Bazel 9.3.2, 8.8.2, 7.7.2 and 7.4.0), and the build is +//! the same with the line and without. use std::path::{Path, PathBuf}; @@ -32,21 +40,40 @@ use crate::vendor::go_mod_edit::{GO_PATCHES_DIR, GO_VENDOR_DIR}; /// The warning code of a `.bazelignore` that [`sync`] could not update. pub const NOT_UPDATED: &str = "bazelignore_not_updated"; +/// Whose copies a directory of [`COPIES`] holds: which of [`sync`]'s +/// flags lets a run add its pair. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Of { + Go, + /// The crates, whose pair is also added only under a hub that builds + /// them. + Crates, + Jars, +} + /// The directories [`sync`] keeps a line for, from the project, what the -/// copies in each are, and whether they are the crates, whose pair is -/// added only under a hub that builds them. -const COPIES: [(&str, &str, bool); 3] = [ - (GO_VENDOR_DIR, "Go module", false), - (GO_PATCHES_DIR, "Go module", false), - (CARGO_VENDOR_DIR, "crate", true), +/// copies in each are, and whose they are. +const COPIES: [(&str, &str, Of); 4] = [ + (GO_VENDOR_DIR, "Go module", Of::Go), + (GO_PATCHES_DIR, "Go module", Of::Go), + (CARGO_VENDOR_DIR, "crate", Of::Crates), + (super::maven::UNITS, "Maven jar", Of::Jars), ]; /// The line above the line [`sync`] writes for a directory of `what` -/// copies. +/// copies. The jars of a hub keep the wording their line was first +/// written with. fn comment(what: &str) -> String { - format!( - "{MARK} patched {what} copies, not Bazel packages (to opt out, comment out the next line)" - ) + match what { + "Maven jar" => format!( + "{MARK} patched Maven jars for a Bazel hub, not Bazel packages (to opt out, comment \ + out the next line)" + ), + _ => format!( + "{MARK} patched {what} copies, not Bazel packages (to opt out, comment out the next \ + line)" + ), + } } /// How [`comment`] starts, in this wording and in any other. A line is @@ -57,11 +84,12 @@ const MARK: &str = "# socket-patch:"; /// Make the `.bazelignore` at the Bazel root of `project` agree with the /// copies of the project: for each of `.socket/vendor/golang`, -/// `.socket/go-patches` and `.socket/vendor/cargo` ([`COPIES`]), one line +/// `.socket/go-patches`, `.socket/vendor/cargo` and `.socket/vendor/maven` +/// ([`COPIES`]), one line /// under its comment line while the directory exists and the file neither /// covers nor declines it ([`settled`]), and no such pair once it is gone. /// A pair is added only for an ecosystem the run has in scope (`go`, -/// `cargo`), and for the crates only where the workspace has a hub of the +/// `cargo`, `maven`), and for the crates only where the workspace has a hub of the /// project's crates ([`cargo_bazel::hub`], whose files are read when a /// pair for that directory is to be added and at no other time): elsewhere /// a directory that exists keeps what the file says of it, as does one @@ -77,14 +105,19 @@ const MARK: &str = "# socket-patch:"; /// lock of the root ([`lock`]). /// /// `Ok(Some)` is the file, when it was changed, and whose lines came or -/// went: `Go module`, `crate`, or both, in that order. `Err` is the detail +/// went: `Go module`, `crate`, `Maven jar`, or several, in that order. `Err` is the detail /// of a /// [`NOT_UPDATED`] warning: the file could not be read or written, or is a /// link, which socket-patch does not write through. The command that asked /// has done its work either way. -pub async fn sync(project: &Path, go: bool, cargo: bool) -> Result, String> { +pub async fn sync( + project: &Path, + go: bool, + cargo: bool, + maven: bool, +) -> Result, String> { let project = project.to_path_buf(); - run_blocking(move || sync_blocking(&project, go, cargo)).await + run_blocking(move || sync_blocking(&project, go, cargo, maven)).await } /// The file [`sync`] changed, and the copies its changed lines are about. @@ -108,7 +141,12 @@ pub(crate) fn ignores(root: &BazelRoot, dir: &Path) -> bool { file.is_ok_and(|file| covers(&file, dir.trim_end_matches('/'))) } -fn sync_blocking(project: &Path, go: bool, cargo: bool) -> Result, String> { +fn sync_blocking( + project: &Path, + go: bool, + cargo: bool, + maven: bool, +) -> Result, String> { let Some(root) = super::bazel_root(project) else { return Ok(None); }; @@ -120,19 +158,23 @@ fn sync_blocking(project: &Path, go: bool, cargo: bool) -> Result Some(meta.is_dir()), Err(e) => (e.kind() == std::io::ErrorKind::NotFound).then_some(false), }; - let mut wanted = COPIES.map(|(dir, what, crates)| { + let mut wanted = COPIES.map(|(dir, what, of)| { // A copy that is there gets a pair only from a run that has its // ecosystem in scope. - let adds = if crates { cargo } else { go }; + let adds = match of { + Of::Go => go, + Of::Crates => cargo, + Of::Jars => maven, + }; let state = exists(dir).filter(|there| adds || !there); (format!("{from_root}{dir}"), state, what) }); // And the crates only under a hub that builds them. Its files are read // once, and only when `text` would get a pair for the crates. let mut hub = None; - let mut under_a_hub = |wanted: &mut [(String, Option, &'static str); 3], text: &[u8]| { - for ((.., crates), (line, state, _)) in COPIES.iter().zip(wanted.iter_mut()) { - let adds = *crates && *state == Some(true) && !settled(text, line); + let mut under_a_hub = |wanted: &mut [(String, Option, &'static str); 4], text: &[u8]| { + for ((.., of), (line, state, _)) in COPIES.iter().zip(wanted.iter_mut()) { + let adds = *of == Of::Crates && *state == Some(true) && !settled(text, line); if adds && !*hub.get_or_insert_with(|| cargo_bazel::hub(&root)) { *state = None; } @@ -599,7 +641,7 @@ mod tests { /// [`super::sync`] for a run that has every ecosystem in scope. async fn sync(project: &Path) -> Result, String> { - super::sync(project, true, true).await + super::sync(project, true, true, true).await } /// The file [`sync`] says it changed, as the test spells it, for lines @@ -692,7 +734,7 @@ mod tests { async fn a_run_that_leaves_go_out_only_takes_pairs_away() { let (_tmp, root, project) = project("", VENDOR); let file = root.join(".bazelignore"); - let sync = |project: PathBuf| async move { super::sync(&project, false, true).await }; + let sync = |project: PathBuf| async move { super::sync(&project, false, true, true).await }; assert_eq!(sync(project.clone()).await, Ok(None)); assert!(!file.exists()); fs::create_dir(&file).unwrap(); @@ -751,6 +793,55 @@ mod tests { } } + /// The directory of the jars that vendored mode keeps for a hub has a + /// pair of its own, under a comment of its own. It comes and goes with + /// that directory by the rules of the Go pairs, a run that leaves Maven + /// out adds none, and no hub has to be found for it. + #[tokio::test] + async fn the_jars_of_a_hub_have_a_pair_of_their_own() { + let jars = crate::bazel::maven::UNITS; + assert_eq!(jars, ".socket/vendor/maven"); + let of_jars = format!("{}\n{jars}\n", comment("Maven jar")); + assert!(of_jars.starts_with(MARK) && !of_jars.starts_with(COMMENT)); + let (_tmp, root, project) = project("", jars); + let file = root.join(".bazelignore"); + let left = || fs::read_to_string(&file).ok(); + let without_maven = super::sync(&project, true, true, false).await; + assert_eq!(without_maven, Ok(None), "Maven left out"); + assert_eq!(left(), None); + assert_eq!(sync(&project).await, changed_for(&root, "Maven jar")); + assert_eq!(sync(&project).await, Ok(None), "a second run"); + assert_eq!(left(), Some(of_jars.clone())); + fs::create_dir_all(project.join(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert_eq!(left(), Some(of_jars.clone() + &pair(VENDOR))); + // Each goes with its own directory, and the file with the last. + fs::remove_dir_all(project.join(jars)).unwrap(); + let gone = super::sync(&project, false, false, false).await; + assert_eq!(gone, changed_for(&root, "Maven jar")); + assert_eq!(left(), Some(pair(VENDOR))); + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert_eq!(left(), None); + // A line of the user's that covers the directory, and the pair + // with its path line commented out, are left as they are. + fs::create_dir_all(project.join(jars)).unwrap(); + let declined = format!("{}\n# {jars}\n", comment("Maven jar")); + for settled in [".socket\n", ".socket/vendor\n", declined.as_str()] { + fs::write(&file, settled).unwrap(); + assert_eq!(sync(&project).await, Ok(None), "{settled:?}"); + assert_eq!(left().as_deref(), Some(settled)); + } + // What cannot be written is said with the line to add. + fs::remove_file(&file).unwrap(); + fs::create_dir(&file).unwrap(); + let detail = sync(&project).await.expect_err("a directory"); + assert!( + detail.contains("add `.socket/vendor/maven` to it"), + "{detail}" + ); + } + /// The vendored crates get their pair, under a comment line of their /// own, where the module files of the workspace make a crate hub and /// the run has Cargo in scope. Elsewhere a directory that is there @@ -782,7 +873,7 @@ mod tests { let hub = HUB.replace("\"//:", "\"//svc:"); fs::write(&module, &hub).unwrap(); // A run that leaves Cargo out adds none either. - assert_eq!(super::sync(&project, true, false).await, Ok(None)); + assert_eq!(super::sync(&project, true, false, true).await, Ok(None)); assert!(!file.exists()); assert_eq!(sync(&project).await, changed_for(&root, "crate")); assert_eq!(fs::read_to_string(&file).unwrap(), crates); @@ -795,7 +886,7 @@ mod tests { fs::remove_dir_all(project.join(CRATES)).unwrap(); fs::remove_dir_all(project.join(VENDOR)).unwrap(); fs::write(&module, "").unwrap(); - let gone = super::sync(&project, false, false).await; + let gone = super::sync(&project, false, false, false).await; assert_eq!(gone, changed_for(&root, "Go module and crate")); assert!(!file.exists()); // A user's "no" holds for the crates as for any other directory. diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index c8b52bd51..73eb1d69d 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -23,6 +23,16 @@ //! writes it, [`pins`] reads the block for `list`, `rollback`, `remove` //! and `vex`, and [`without`] takes an entry out. [`hub_jars`] are the //! jars a hosted scan looks for patches of: those the pinned hubs fetch. +//! +//! Vendored mode patches a pinned hub through the same block. Its entry +//! names no host: the repository is a directory of the checkout, +//! `.socket/vendor/maven/` ([`Patch::unit`]), which holds the +//! patched jar and the two files that make the directory a repository +//! with the one target the hub takes a jar by ([`unit_files`]), and which +//! Bazel's `local_repository` links to, where it is. Bazel checks no digest +//! of such a directory: `socket-patch vendor --check` holds the committed +//! jar to the patch. +//! //! The block is recognised by its text alone: one that is not, byte for //! byte, what socket-patch writes for its entries was changed by hand, and //! is neither written to nor trusted. @@ -674,17 +684,41 @@ pub struct Patch { pub artifact: String, pub version: String, pub uuid: String, - /// The sha256 of the patched jar, which Bazel checks its download by. + /// The sha256 of the patched jar, which Bazel checks its download by, + /// and the URL of that jar on the patch host. Both are empty in the + /// entry of vendored mode, whose jar is in the checkout + /// ([`Patch::unit`]). pub sha256: String, pub url: String, } +/// The directory of the checkout that holds the directory of each patch +/// that vendored mode keeps for a hub, and the file that makes such a +/// directory a repository. +pub const UNITS: &str = ".socket/vendor/maven"; +pub const REPO: &str = "REPO.bazel"; + impl Patch { pub fn purl(&self) -> String { let (group, artifact) = (&self.group, &self.artifact); format!("pkg:maven/{group}/{artifact}@{}", self.version) } + /// The directory of a vendored entry, from the Bazel root, which is + /// the repository of its jar. `None` for the entry of hosted mode. + pub fn unit(&self) -> Option { + self.url + .is_empty() + .then(|| format!("{UNITS}/{}", self.uuid)) + } + + /// The patched jar in [`Patch::unit`], under the name of the upstream + /// jar. + pub fn jar(&self) -> Option { + let (unit, artifact, version) = (self.unit()?, &self.artifact, &self.version); + Some(format!("{unit}/file/{artifact}-{version}.jar")) + } + fn repository(&self) -> String { repository_name(&self.group, &self.artifact, &self.version).unwrap_or_default() } @@ -714,13 +748,23 @@ fn render(label: &str, patches: &[Patch]) -> String { let (name, purl, uuid) = (patch.repository(), patch.purl(), &patch.uuid); let (sha256, url) = (&patch.sha256, &patch.url); let file = artifact_path(group, artifact, version, None, "jar"); + let repository = match patch.unit() { + Some(unit) => format!( + "socket_patch_local_repository(\n \ + name = \"socket_patch_{name}\",\n \ + path = \"{unit}\",\n)" + ), + None => format!( + "socket_patch_http_file(\n \ + name = \"socket_patch_{name}\",\n \ + downloaded_file_path = \"v1/{file}\",\n \ + sha256 = \"{sha256}\",\n \ + urls = [\"{url}\"],\n)" + ), + }; format!( "# {purl}, Socket patch {uuid}\n\ - socket_patch_http_file(\n \ - name = \"socket_patch_{name}\",\n \ - downloaded_file_path = \"v1/{file}\",\n \ - sha256 = \"{sha256}\",\n \ - urls = [\"{url}\"],\n)\n\n\ + {repository}\n\n\ # If Bazel stops at the next line (\"does not generate repository\"), the hub's \ lock no longer pins\n\ # {group}:{artifact} at {version}: run `socket-patch rollback {purl}`.\n\ @@ -731,10 +775,26 @@ fn render(label: &str, patches: &[Patch]) -> String { }; let mut patches: Vec<&Patch> = patches.iter().collect(); patches.sort_by_key(|patch| patch.repository()); + // The rule of each kind of entry there is, hosted first. + let rules = [ + ("http", "http_file", false), + ("local", "local_repository", true), + ]; + let used = |(_, _, vendored): &&(&str, &str, bool)| { + patches + .iter() + .any(|patch| patch.url.is_empty() == *vendored) + }; + let rule = |(file, rule, _): &(&str, &str, bool)| { + format!( + "socket_patch_{rule} = use_repo_rule(\ + \"@bazel_tools//tools/build_defs/repo:{file}.bzl\", \"{rule}\")\n" + ) + }; + let rules: String = rules.iter().filter(used).map(rule).collect(); let entries: Vec = patches.into_iter().map(entry).collect(); format!( - "{BEGIN}\nsocket_patch_http_file = use_repo_rule(\ - \"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_file\")\n\n\ + "{BEGIN}\n{rules}\n\ socket_patch_maven = use_extension(\"{label}\", \"maven\")\n\n{}{END}", entries.join("\n") ) @@ -763,13 +823,20 @@ fn parse(body: &str) -> Option<(String, Vec)> { let below = lines.get(at + 1..)?.iter().take(6); below.copied().find_map(|line| between(line, open, close)) }; + // The entry of vendored mode names a directory, and nothing of + // a host: which directory, [`find`] holds it to. + let hosted = field(" path = \"", "\",").is_none(); + let of_host = |open: &str, close: &str| match hosted { + true => field(open, close), + false => Some(String::new()), + }; patches.push(Patch { group: group.to_string(), artifact: artifact.to_string(), version: version.to_string(), uuid: uuid.to_string(), - sha256: field(" sha256 = \"", "\",")?, - url: field(" urls = [\"", "\"],")?, + sha256: of_host(" sha256 = \"", "\",")?, + url: of_host(" urls = [\"", "\"],")?, }); } Some((label, patches)) @@ -833,7 +900,7 @@ fn find(text: &str) -> Block { /// of a file with both). A file whose last line has no line break gets a /// block without one, so that [`without`] can tell. `None` when the block /// that is there was changed by hand. -fn with_patch(module: &str, label: &str, patch: Patch) -> Option { +pub fn with_patch(module: &str, label: &str, patch: Patch) -> Option { let (at, mut patches) = match find(module) { Block::Edited(_) => return None, Block::None => (None, Vec::new()), @@ -851,6 +918,97 @@ fn with_patch(module: &str, label: &str, patch: Patch) -> Option { }) } +/// The patches of the block of `module`: none when it has no block, or one +/// that was changed by hand. +pub fn entries(module: &str) -> Vec { + match find(module) { + Block::Ours(_, _, patches) => patches, + _ => Vec::new(), + } +} + +/// The files of a vendored entry's directory ([`Patch::unit`]), each by +/// its path from the Bazel root: the file that makes the directory a +/// repository, the package `file` with the one target `file`, by which a +/// hub takes the jar of the repository it fetches (`@//file` +/// in the ruleset's `private/dependency_tree_parser.bzl` at 6.5, 6.9 and +/// 7.2), the jar, and a `.gitignore` that takes back a rule of the +/// checkout that ignores jars, so that git commits this one. `None` for +/// the entry of hosted mode. +pub fn unit_files(patch: &Patch, jar: Vec) -> Option<[(String, Vec); 4]> { + let (unit, path) = (patch.unit()?, patch.jar()?); + let name = path.rsplit('/').next().unwrap_or_default(); + let (purl, uuid) = (patch.purl(), &patch.uuid); + let repo = format!( + "# The jar of {purl} with Socket patch {uuid}, which the block of\n\ + # socket-patch in MODULE.bazel puts in the place of the one a hub fetches.\n\ + # `socket-patch vendor --check` holds the jar to the patch.\n" + ); + let build = format!( + "filegroup(\n name = \"file\",\n srcs = [\"{name}\"],\n \ + visibility = [\"//visibility:public\"],\n)\n" + ); + Some([ + (format!("{unit}/{REPO}"), repo.into_bytes()), + (format!("{unit}/file/BUILD.bazel"), build.into_bytes()), + (path, jar), + (format!("{unit}/.gitignore"), b"!*\n".to_vec()), + ]) +} + +/// What a decline says after its reason: what the block of `file` holds +/// for the jar, when `held` is the id of the patch of its entry there, +/// after a run for the patch `uuid` wrote nothing for the reason `code`. +fn left(held: Option<&str>, uuid: &str, code: &str, file: &str) -> String { + match held { + None => KEEPS.to_string(), + Some(held) if held == uuid && code == NO_EFFECT => format!( + "socket-patch left the entry that {file} holds for it as it is, and while that \ + stands the entry has no effect: the Bazel build keeps the upstream jar" + ), + Some(held) if held == uuid => { + format!("socket-patch left the entry that {file} holds for it as it is") + } + Some(held) => format!( + "socket-patch wrote nothing to {file} for it: the entry of patch {held} remains \ + there, and where the block is in effect the Bazel build takes that patch's jar" + ), + } +} + +/// What a vendored run in `project` writes to the block for the patch +/// `uuid` of `purl`: the label and the entry, or the code of a decline and +/// what the run says of it (the detail of the patch's refusal, which names +/// the purl itself). `None` for a patch whose jar no hub builds or may +/// build, in no Bazel workspace, and for a jar with a classifier or of +/// another packaging: such a run is the one it was. +pub fn vendored( + project: &Path, + purl: &str, + uuid: &str, +) -> Option> { + let (group, artifact, version) = parse_maven_purl(purl).filter(|_| plain(purl))?; + let [group, artifact, version] = [group, artifact, version].map(|part| part.to_string()); + let jar: Jar = (uuid.to_string(), group, artifact, version); + let (_, entry, held) = verdicts(project, None, std::slice::from_ref(&jar), true).pop()?; + let (uuid, group, artifact, version) = jar; + let patch = Patch { + group, + artifact, + version, + uuid, + sha256: String::new(), + url: String::new(), + }; + Some(match entry { + Ok(label) => Ok((label, patch)), + Err((code, why)) => { + let ends = left(held.as_deref(), &patch.uuid, code, FILE); + Err((code, format!("{why}. {ends}"))) + } + }) +} + /// `module` without the patches of its block that `gone` names. With the /// last one the block goes, and what [`with_patch`] put before it: the /// file is then byte for byte what it was before its first patch. `None` @@ -904,7 +1062,7 @@ pub type Site = BTreeMap; pub type Jar = (String, String, String, String); /// A code of this module, and why. -type Declined = (&'static str, String); +pub type Declined = (&'static str, String); /// What a warning says after the reason, when the block holds no entry /// for the jar. @@ -1008,6 +1166,7 @@ fn settings( view: &dyn Fn(&str) -> Entry, locks: &dyn Fn(&str) -> Entry, asked: &Asked, + vendored: bool, ) -> Result<(), Declined> { let link = std::fs::symlink_metadata(root.join(FILE)).is_ok_and(|meta| meta.is_symlink()); if link { @@ -1061,7 +1220,15 @@ fn settings( "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ so that Bazel updates its lock" ), - (_, [_]) => return rc(view, release).into_iter().next().map_or(Ok(()), Err), + // The jar of a vendored entry is in the checkout: no option about + // downloads stands against it. + (_, [_]) => { + let against = |(code, _): &Declined| !vendored || *code != DOWNLOAD; + return rc(view, release) + .into_iter() + .find(against) + .map_or(Ok(()), Err); + } _ => format!( "MODULE.bazel.lock does not say which release of {module} Bazel selected, and the \ name of a jar's repository depends on it: build once so that Bazel writes its lock" @@ -1135,8 +1302,9 @@ pub fn jars<'a>(patches: impl Iterator) -> Ve patches.filter_map(jar).collect() } -/// What a hosted run in `project` may write for each of `jars`: read once -/// per run from the checkout. `module` is the text of the project's own +/// What a hosted run in `project` may write for each of `jars`, or with +/// `vendored` a vendored one: read once per run from the checkout. +/// `module` is the text of the project's own /// `MODULE.bazel` as the run has it, when it has read it. Empty for a /// project in no Bazel workspace and when no hub builds, or may build, /// any of the jars: nothing changes for such a run. An entry is written @@ -1144,8 +1312,26 @@ pub fn jars<'a>(patches: impl Iterator) -> Ve /// lock, or one that could not be read, may build the upstream jar beside /// the hub that would get the patched one. A project below the root gets /// no entry: the root is read all the same, for what its block holds. -pub fn site(project: &Path, module: Option<&str>, jars: &[Jar]) -> Site { - let mut site = Site::new(); +pub fn site(project: &Path, module: Option<&str>, jars: &[Jar], vendored: bool) -> Site { + let verdict = |(uuid, entry, held): (String, Result, _)| { + let entry = entry.map_err(|(code, why)| (code.to_string(), why)); + (uuid, Verdict { entry, held }) + }; + let read = verdicts(project, module, jars, vendored).into_iter(); + read.map(verdict).collect() +} + +/// [`site`], with the code of a decline as this module has it: for each +/// jar that a hub builds or may build, the id of its patch, the label to +/// write its entry under or why none is written, and the id of the patch +/// whose entry the block holds for the jar. +fn verdicts( + project: &Path, + module: Option<&str>, + jars: &[Jar], + vendored: bool, +) -> Vec<(String, Result, Option)> { + let mut site = Vec::new(); let Some(root) = super::bazel_root(project) else { return site; }; @@ -1172,19 +1358,17 @@ pub fn site(project: &Path, module: Option<&str>, jars: &[Jar]) -> Site { Err((NOT_AT_ROOT, why)) } Built::Yes(_) => hubs.label(group, artifact, version).and_then(|label| { - let all = workspace - .get_or_insert_with(|| settings(&root.dir, &view, &locks, &hubs.asked)); + let all = workspace.get_or_insert_with(|| { + settings(&root.dir, &view, &locks, &hubs.asked, vendored) + }); all.clone().map(|()| label) }), }; let jar = |patch: &&Patch| { (&patch.group, &patch.artifact, &patch.version) == (group, artifact, version) }; - let verdict = Verdict { - entry: entry.map_err(|(code, why)| (code.to_string(), why)), - held: hubs.block.iter().find(jar).map(|patch| patch.uuid.clone()), - }; - site.insert(uuid.clone(), verdict); + let held = hubs.block.iter().find(jar).map(|patch| patch.uuid.clone()); + site.push((uuid.clone(), entry, held)); } site } @@ -1267,22 +1451,18 @@ pub fn rewrite( // pin, or the entry of another patch, which is not this run's to // take out. An entry that the reason of the decline leaves without // effect is no pin: the patch is not reported as applied for it. - let ends = match verdict.held.as_deref() { - None => KEEPS.to_string(), - Some(held) if held == dep.patch_uuid && code == NO_EFFECT => format!( - "socket-patch left the entry that {file} holds for it as it is, and while that \ - stands the entry has no effect: the Bazel build keeps the upstream jar" - ), - Some(held) if held == dep.patch_uuid => { - let uuid = dep.patch_uuid.clone(); - result.confirmed_bazel_maven_uuids.insert(uuid); - format!("socket-patch left the entry that {file} holds for it as it is") - } - Some(held) => format!( - "socket-patch wrote nothing to {file} for it: the entry of patch {held} remains \ - there, and where the block is in effect the Bazel build takes that patch's jar" - ), - }; + let held = verdict.held.as_deref(); + // A vendored entry of the same patch is not this run's pin: the + // run wrote nothing, and the checkout stays a vendored one. + let vendored = |patch: &Patch| patch.uuid == dep.patch_uuid && patch.unit().is_some(); + let vendored = files + .get(FILE) + .is_some_and(|text| entries(text).iter().any(vendored)); + if held == Some(&dep.patch_uuid) && code != NO_EFFECT && !vendored { + let uuid = dep.patch_uuid.clone(); + result.confirmed_bazel_maven_uuids.insert(uuid); + } + let ends = left(held, &dep.patch_uuid, &code, &file); let detail = format!("{purl}: {why}. {ends}"); result.warnings.push(RewriteWarning { code, detail }); } @@ -1303,6 +1483,9 @@ pub struct Pin { pub unbuilt: Option, } +/// How [`Pin::unbuilt`] ends for an entry that only the undo takes out. +pub const STOPS: &str = "so Bazel stops at its entry"; + /// The patches in the block of `module`, the text of the `MODULE.bazel` /// at the Bazel root `root`, or why the block is no record of any: it was /// changed by hand. @@ -1334,8 +1517,7 @@ pub fn pins(root: &Path, module: &str) -> Result, String> { Built::Yes(_) => off.clone(), Built::Unknown(doubt, kind) => Some(unknown(doubt, kind).1), Built::No => Some(format!( - "no pinned hub takes {group}:{artifact} at {version} any more, so Bazel stops \ - at its entry" + "no pinned hub takes {group}:{artifact} at {version} any more, {STOPS}" )), }; let patch = patch.clone(); @@ -1354,9 +1536,12 @@ pub struct HubJars { /// The warning ([`HUB_NOT_READ`]) for the first thing that was not /// read. pub unread: Option<(&'static str, String)>, - /// The entries of the block whose jar no pinned hub fetches any more, - /// when every hub was read: the purl and the id of the patch of each. - /// Bazel stops at such an entry. + /// The entries of hosted mode in the block whose jar no pinned hub + /// fetches any more, when every hub was read: the purl and the id of + /// the patch of each. Bazel stops at such an entry. An entry of + /// vendored mode in that state is not among them: its directory and + /// its ledger entry are vendored mode's to take out, which `rollback`, + /// `remove` and `vendor --revert` do, and `vendor --check` names it. pub stale: Vec<(String, String)>, } @@ -1368,9 +1553,9 @@ pub struct HubJars { /// the first thing that was not read: no jar is guessed for a hub without /// a lock, or for one whose tags or lock cannot be read. In a workspace /// that has nothing to do with the ruleset there is no hub to read, and -/// no warning. And the entries of the block that are stale, for the run -/// to take out. Nothing for a project below the root, where no entry is -/// written either, and for one in no Bazel workspace. +/// no warning. And the entries of hosted mode in the block that are +/// stale, for the run to take out. Nothing for a project below the root, +/// where no entry is written either, and for one in no Bazel workspace. pub async fn hub_jars(project: &Path) -> HubJars { let project = project.to_path_buf(); run_blocking(move || hub_jars_blocking(&project)).await @@ -1409,8 +1594,10 @@ fn hub_jars_blocking(project: &Path) -> HubJars { ); (HUB_NOT_READ, detail) }); - let stale = - |patch: &&Patch| hubs.built(&patch.group, &patch.artifact, &patch.version) == Built::No; + let stale = |patch: &&Patch| { + patch.unit().is_none() + && hubs.built(&patch.group, &patch.artifact, &patch.version) == Built::No + }; let stale = hubs.block.iter().filter(stale); HubJars { jars: purls.into_iter().collect(), @@ -1426,16 +1613,59 @@ fn hub_jars_blocking(project: &Path) -> HubJars { /// project's Bazel workspace builds ([`HUB_UNPATCHED`]) or may build /// ([`UNREADABLE`]). Nothing for a project in no Bazel workspace, and /// nothing is looked for without a Maven purl among them. -pub async fn notices(project: &Path, purls: Vec) -> Vec<(&'static str, String)> { +/// +/// A `vendored` run patches a hub: its warnings are for the jars whose +/// entry the block does not hold after it, each with the reason vendored +/// mode writes none ([`site`]), under the code a hosted run gives it. +pub async fn notices( + project: &Path, + purls: Vec, + vendored: bool, +) -> Vec<(&'static str, String)> { let project = project.to_path_buf(); - run_blocking(move || notices_blocking(&project, purls)).await + run_blocking(move || notices_blocking(&project, purls, vendored)).await } -fn notices_blocking(project: &Path, mut purls: Vec) -> Vec<(&'static str, String)> { +fn notices_blocking( + project: &Path, + mut purls: Vec, + vendored: bool, +) -> Vec<(&'static str, String)> { purls.sort(); purls.dedup(); let jar = |purl| Some((purl, parse_maven_purl(purl).filter(|_| plain(purl))?)); let jars: Vec<_> = purls.iter().map(String::as_str).filter_map(jar).collect(); + if vendored { + // A warning names the purl: it stands where a run has the patch's id. + let by_purl = |(purl, (group, artifact, version)): &(&str, _)| -> Jar { + let [group, artifact, version] = [group, artifact, version].map(ToString::to_string); + (purl.to_string(), group, artifact, version) + }; + let jars: Vec = jars.iter().map(by_purl).collect(); + let said = |(purl, entry, held): (String, Result, Option)| { + let (code, why) = match (held, entry) { + // The entry is there and the checkout leaves it without + // effect (an rc file that switches the block off, an + // override of the jar): the build takes the upstream jar + // past it, which is said as a hosted run says it. + (Some(held), Err((code, why))) if code == NO_EFFECT => { + let ends = left(Some(&held), &held, code, FILE); + return Some((code, format!("{purl}: {why}. {ends}"))); + } + // Any other entry stands: the hub takes its jar. + (Some(_), _) => return None, + (None, Err(declined)) => declined, + (None, Ok(_)) => { + let why = "a rules_jvm_external hub of the Bazel workspace builds this \ + artifact from its lock, and this run vendored nothing for it"; + (HUB_UNPATCHED, why.to_string()) + } + }; + Some((code, format!("{purl}: {why}. {KEEPS}"))) + }; + let read = verdicts(project, None, &jars, true).into_iter(); + return read.filter_map(said).collect(); + } let root = (!jars.is_empty()).then(|| super::bazel_root(project)); let Some(root) = root.flatten() else { return Vec::new(); @@ -1585,6 +1815,11 @@ use_repo(maven, "maven") } "#; + /// [`super::notices_blocking`] for a run that patches no hub. + fn notices_blocking(project: &Path, purls: Vec) -> Vec<(&'static str, String)> { + super::notices_blocking(project, purls, false) + } + /// The view of the files `files`, held in memory. fn view<'a>(files: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Entry + 'a { move |path| match files.iter().find(|(name, _)| *name == path) { @@ -2475,6 +2710,13 @@ jvm.artifact(group = "com.example", artifact = "a", version = "1") }; assert_eq!(hub_jars_blocking(dir.path()), expected, "{module}"); } + // A stale entry of vendored mode is not on the list: a hosted run + // has no way to take its directory and its ledger entry with it. + let mut vendored = patch("netty-tcnative-classes", NETTY_UUID); + (vendored.sha256, vendored.url) = (String::new(), String::new()); + let module = with_patch(PINNED, LABEL, vendored).expect("a block"); + let dir = project(&[("MODULE.bazel", &module), (main, LOCK_SKIPS)]); + assert!(hub_jars_blocking(dir.path()).stale.is_empty()); // Only for the root of a workspace, where an entry is written: // not below it, whatever its hubs are, and not without one. for module in [PINNED, &lockless] { @@ -2867,7 +3109,7 @@ override_repo( /// What [`site`] says of netty's jar in the checkout: `write