From 9501922ab3e61a80da38ddef1efab2289b84b3db Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 11:01:35 -0500 Subject: [PATCH 1/5] Test vendored mode for a Maven artifact that only a Bazel hub builds Hosted mode patches a pinned rules_jvm_external hub: one block in the root MODULE.bazel puts a repository with the patched jar in the place of the hub's own. Vendored mode has no test on a real Bazel for such a hub. This adds one, in the checkout whose only build is Bazel's, and records what the code does there today. `socket-patch get --mode vendored --yes` exits 1. Its event is `failed` / `vendor_jvm_shape_unsupported` ("no_build_file: no pom.xml, Gradle, sbt or scala-cli build at the project root"): vendored mode knows a Maven artifact only as the dependency of one of those builds. Its one warning is `maven_bazel_hub_unpatched`, which names the hub's lock and says that the Bazel build stays unpatched. It writes no file and downloads no jar, the build prints the upstream marker before and after, and `vendor --revert` has nothing to take out. The flow asserts that refusal by its code and text, so that a commit which makes vendored mode patch the hub has to change the expectation. For a vendored run the test's stand-in now serves what such a run asks the patch service for: the patched jar at the path of the grant's own URL for it, with its sha512, and the record of the patch, whose one file is the one that differs from the upstream jar of the run. A vendored command is given `--patch-server-url`, so that the URL's host is the stand-in. The hosted flows read neither. Run on macOS arm64 with Bazel 9.3.2 (rules_jvm_external 7.2), every child behind a logging proxy that refuses public Maven hosts: the five Maven flows pass in 74 s, with no request to such a host. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_bazel_build/maven.rs | 142 ++++++++++++++++-- 1 file changed, 133 insertions(+), 9 deletions(-) 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 c2d13aa7c..851cf0731 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -40,6 +40,13 @@ //! (`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` fails (exit 1, `vendor_jvm_shape_unsupported`: no Maven, Gradle, +//! sbt or scala-cli build is there to pin), says that the hub builds the +//! upstream jar (`maven_bazel_hub_unpatched`) and writes no file: the +//! build prints the upstream marker before and after. +//! //! 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 @@ -87,14 +94,17 @@ 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; use crate::harness::{changed, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING}; -use crate::hosted_memory_common::Patch; +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 @@ -228,6 +238,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, } @@ -237,7 +250,11 @@ struct Granted { /// registry, the version with the suffix only that registry serves. The /// route of the jar answers with `tampered`, or with the jar the grant /// pins. -fn grant(standin: &StandIn, tampered: Option<&[u8]>) -> Granted { +/// +/// 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: the one file that differs from the jar of the run `run`. +fn grant(standin: &StandIn, run: &str, tampered: Option<&[u8]>) -> Granted { let uuid = uuid::Uuid::new_v4().to_string(); let token = uuid::Uuid::new_v4().to_string(); let suffixed = format!("{VERSION}-socket.{}", &uuid[..8]); @@ -246,9 +263,12 @@ fn grant(standin: &StandIn, 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, @@ -256,7 +276,7 @@ fn grant(standin: &StandIn, tampered: Option<&[u8]>) -> Granted { "artifacts": [{ "kind": "tarball", "url": artifact, - "integrity": { "sha256": sha256_hex(&jar) }, + "integrity": { "sha256": sha256_hex(&jar), "sha512": sha512 }, }], "registryOverride": { "kind": "maven2", @@ -276,10 +296,31 @@ fn grant(standin: &StandIn, tampered: Option<&[u8]>) -> Granted { uuid: uuid.clone(), reference, }]); + let (upstream, patched) = (format!("PRISTINE {run}\n"), format!("PATCHED {uuid}\n")); + let record = json!({ + "uuid": uuid, + "purl": 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()); Granted { sha256: sha256_hex(&jar), url: format!("https://{registry}/{file}"), route, + archive, marker: format!("OUT: PATCHED {uuid}"), uuid, } @@ -378,7 +419,7 @@ impl Pinned { &jar(&[]), Some((VICTIM, VERSION)), ); - let patch = grant(&standin, None); + let patch = grant(&standin, &run, None); // The checkout: the hub's repository is the stand-in, the lock is // the empty file the ruleset's documentation starts from. @@ -477,6 +518,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 @@ -563,7 +612,7 @@ impl Pinned { let mut twin = self.cell.twin(); let rogue = StandIn::start(); let tampered = victim("TAMPERED"); - let other = grant(&rogue, Some(&tampered)); + let other = grant(&rogue, &self.run, Some(&tampered)); let host = format!("{PATCH_HOST}/"); twin.route_downloads(&[ rewrite(&host, &rogue.origin()), @@ -799,6 +848,81 @@ fn a_version_bump_of_the_patched_artifact() { ); } +/// The command of vendored mode, and what it says today of a patch whose +/// jar only a hub builds. +const VENDORED: [&str; 5] = ["get", PURL, "--mode", "vendored", "--yes"]; +const NO_BUILD: &str = "reason: no_build_file: no pom.xml, Gradle, sbt or scala-cli build at the \ + project root"; + +/// Vendored mode in a checkout that only Bazel builds: the command fails +/// for want of a Maven or Gradle build to pin, says that the hub builds +/// the upstream jar, and leaves every file and the build as they were. +#[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; + }; + flow.builds_upstream(); + let before = flow.names_its_bazel(); + + let get = flow.vendored(&VENDORED); + let said = &get.dump; + assert_eq!(get.code, 1, "{test}: {said}"); + let events = get.envelope["events"].as_array().expect("events"); + let failed = events.iter().find(|event| event["action"] == "failed"); + let failed = failed.unwrap_or_else(|| panic!("{test}: nothing failed: {said}")); + assert_eq!( + (&failed["purl"], &failed["errorCode"], &failed["error"]), + ( + &json!(PURL), + &json!("vendor_jvm_shape_unsupported"), + &json!(NO_BUILD) + ), + "{test}: {said}" + ); + assert_eq!(get.envelope["summary"]["applied"], 0, "{test}: {said}"); + let warnings = get.envelope["warnings"].as_array().expect("warnings"); + let [warning] = &warnings[..] else { + panic!("{test}: not one warning: {said}"); + }; + let detail = warning["detail"].as_str().unwrap_or_default(); + let unpatched = + format!("{PURL}: Bazel takes this artifact from maven_install.json (hub \"{HUB}\", "); + assert_eq!( + warning["code"], "maven_bazel_hub_unpatched", + "{test}: {said}" + ); + assert!( + detail.starts_with(&unpatched) && detail.contains("the Bazel build stays unpatched"), + "{test}: {said}" + ); + assert_eq!( + changed(&before, &flow.cell.tree()), + NOTHING, + "{test}: {said}" + ); + for route in [&flow.patch.route, &flow.patch.archive] { + let asked = flow.standin.asked(route); + assert_eq!(asked, 0, "{test}: the command fetched {route}"); + } + + // The build is the one of before, and the undo of vendored mode has + // nothing to take out. + flow.cell.builds(&flow.upstream); + let undo = flow.vendored(&["vendor", "--revert", "--yes"]); + assert_eq!(undo.code, 0, "{test}: {}", undo.dump); + assert_eq!(changed(&before, &flow.cell.tree()), NOTHING, "{test}"); + println!( + "{test}: Bazel {} built {:?} before and after `get --mode vendored` failed for {PURL} \ + (vendor_jvm_shape_unsupported) and wrote nothing; {:?}", + flow.cell.release(), + flow.upstream, + 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") From 7da169004ec24f0e581b56e5af26146ff39dcc2e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Mon, 23 Nov 2026 14:00:50 -0500 Subject: [PATCH 2/5] Vendor a Maven patch for a pinned rules_jvm_external hub of Bazel Hosted mode patches a pinned rules_jvm_external hub of a Bazel workspace with one block at the end of the root MODULE.bazel: per patch an `http_file` of the patched jar on the Socket patch host, and Bazel's `override_repo` of the repository through which the hub fetches that jar. Vendored mode patched no hub. In a checkout only Bazel builds, `get --mode vendored` failed with `vendor_jvm_shape_unsupported` ("no pom.xml, Gradle, sbt or scala-cli build"), and beside a Maven or Gradle build it vendored for that build and said that the Bazel build stays unpatched. With this commit `socket-patch vendor`, `scan --mode vendored` and `get --mode vendored`, run at the Bazel root, commit the patched jar for the hub: the jar is downloaded once, from Socket's patch service, and the build then needs no host. No upstream registry is asked. What is written .socket/vendor/maven//REPO.bazel .socket/vendor/maven//file/BUILD.bazel .socket/vendor/maven//file/-.jar .socket/vendor/maven//.gitignore and, in the same block of MODULE.bazel, an entry whose repository is that directory: socket_patch_local_repository = use_repo_rule("@bazel_tools//tools/build_defs/repo:local.bzl", "local_repository") # pkg:maven//@, Socket patch socket_patch_local_repository( name = "socket_patch_", path = ".socket/vendor/maven/", ) followed by the comment and the `override_repo` of a hosted entry. A block binds the rule of each kind of entry it holds, `http_file` first, so a block of hosted entries is byte for byte what it was. - The hub takes the jar of a repository by its target `//file` (`@//file` in the ruleset's dependency_tree_parser.bzl at 6.5, 6.9 and 7.2, copied to the hub's own path), so the BUILD file is one public filegroup `file` over the jar, whose name does not matter: it is the upstream jar's. - `local_repository` and `new_local_repository` are in `@bazel_tools//tools/build_defs/repo:local.bzl` at Bazel 7.4.0, 7.7.2, 8.8.2 and 9.3.2, and take a `path` from the workspace root (`rctx.workspace_root.get_child`), not from the file that names it. `local_repository` links the repository to the directory: nothing is copied or downloaded, and the repository cache holds no copy of the jar. Bazel refuses a linked repository without a boundary file ("No MODULE.bazel, REPO.bazel, or WORKSPACE file found", in StarlarkRepositoryFunction.java at 7.4.0, 7.7.2 and 8.8.2 and RepositoryFetchFunction.java at 9.3.2), hence REPO.bazel, which holds three comment lines. `new_local_repository` with an empty `build_file_content` also built patched on 9.3.2 without REPO.bazel (two files instead of three); `local_repository` is the rule Bazel documents for a directory that has a BUILD file, and it generates nothing. - The `.gitignore` is `!*`: a `*.jar` rule of the checkout (the stock Java one) would drop the jar from the commit. A rule that ignores the directory itself is refused (`vendor_artifact_gitignored`), as for every vendored artifact. - The directory is the unit `.socket/vendor//` that every vendored artifact has, not a directory by the repository's name: the ledger, `vendor --check`, `vex`, `repair`, the orphan sweep and the guard against a linked vendor directory then hold for it as they are. - `.bazelignore` gets `.socket/vendor/maven` under a comment line of its own, by the rules of the Go lines (added while the directory exists, removed with it, the user's own line or commented-out line respected, `bazelignore_not_updated` when it cannot be written). Without it `bazel query //...` lists `//.socket/vendor/maven//file:file`; the build is the same with and without the line. - The patch is recorded in the vendor ledger. For a patch that only the hub takes: ecosystem `maven`, flavor `bazel`, the committed jar as the artifact, and no wiring records, because the block is read from MODULE.bazel and from nowhere else. Integrity Bazel checks the sha256 of an `http_file` and nothing of a directory: a changed committed jar is built (measured, and asserted in the flow). No rule of Bazel's own checks a digest of a file of the main repository, and a Starlark rule committed into the user's tree is not written. The check is `vendor --check`, in a checkout only Bazel builds and beside a Maven or Gradle build alike. It fails when the jar that Bazel builds is not, byte for byte, the vendored jar whose sha256 the ledger records (beside a build the hub's jar is a copy of that build's, with the same sha256: a jar that keeps the patch's files and differs elsewhere fails too); when REPO.bazel or file/BUILD.bazel is not the file that was written (a BUILD file that names another jar); when the block no longer names the directory or was changed by hand; and when the entry is one a build stops at or may pass without: no pinned hub takes the jar at that version any more, for which the reason ends with `socket-patch rollback ` (the undo is what takes such an entry out, and a vendored `get` of that purl now ends with the same words), or an rc file switches the entry off. `vex` hashes the same jar before it attests. When no entry is written The decision is the hosted lane's (`bazel::maven::site`, now with a `vendored` flag), with the same codes and texts: `maven_bazel_not_at_root`, `_not_pinned`, `_unreadable`, `_release`, `_artifact`, `_no_effect`. Not `maven_bazel_download`: an option about downloads (a downloader config, `--repository_disable_download`, `--vendor_dir`) does not stand against a jar in the checkout. A build with `--repository_disable_download` was run on 9.3.2 and is patched; that Bazel's vendor mode leaves a local repository alone is read (RepositoryDelegatorFunction.java at 7.4.0, RepositoryFetchFunction.java at 9.3.2), not run. - In a checkout with no Maven, Gradle, sbt or scala-cli build the hub is the patch's only target: the patch fails with that code (exit 1, as a vendored refusal does) and nothing is written. The decline comes from `vendor::refusals::bazel_workspace_refusals`, the one dispatch of the vendored refusals that rest on a Bazel workspace, so a scan, a `get`, a `vendor` and the eject of hosted pins all take it before anything is downloaded. `--allow-vendored-in-bazel` does not lift it: the switch is for a build that may not find a vendored copy, and here no entry could be shown to work and there is nothing else to write. A jar that no hub builds still fails with `vendor_jvm_shape_unsupported`. - Beside such a build, that build is vendored exactly as without the workspace, the hub gets a copy of the same jar when the build took the patch, and a hub that cannot be given one is a warning with the code and the reason, in the place of `maven_bazel_hub_unpatched`. Switching modes, and the undo - One entry per jar. A vendored run puts its entry in the place of a hosted one. `vendor` ejects a hosted patch that only the block wires where the hub is the project's one build. Beside a Maven or Gradle build it ejects no such patch, and the entry stays hosted, unless the same run vendors that patch for the build (a patch of the manifest, or a pin that the build's own files hold too): the hub's entry is then the vendored one, and `vendor --revert` takes it out. - Before `vendor` takes a hosted entry out, the hub is asked about the checkout as it is, in the eject's preflight (the same dispatch, before any record is fetched). Where no vendored entry would be written, the eject is refused whole (`eject_refused`, nothing changed), and the reason starts with "kept hosted: " and ends with "socket-patch left the entry that MODULE.bazel holds for it as it is": the Bazel build keeps the hosted jar. - A hosted run over a patch that only the hub takes reverts the vendored entry, its directory, its `.bazelignore` line and its ledger entry first (the existing vendored-to-hosted takeover), and the checkout is then the one a hosted run alone leaves. Beside a Maven build the ledger entry is that build's and no takeover reverts it, so the hosted run itself removes the hub's directory once its entry is in the place of the vendored one and nothing names the directory, and the `.bazelignore` line goes with it. The vendored tree of the Maven build stays, as it does without the workspace. - `vendor --revert`, `rollback` and `remove` take the entry out, then the directory: every file is byte for byte what it was, but for a `.bazelignore` that was an empty file of the user's, which is deleted with the last line, as for the Go lines. A MODULE.bazel that names the directory outside an entry of the block (a block changed by hand) fails the undo before anything is removed: Bazel stops at a `local_repository` whose directory is gone. - `repair` puts a lost or changed jar back; for this artifact it writes the jar alone, not a pom beside it. Also - `list` shows the patch as vendored; discovery reads the vendored entry as vendored wiring of the committed jar, withheld like a hosted entry when the hub no longer fetches that version or an rc file switches the block off. - The jar's directory beside a Maven or Gradle build belongs to that build's ledger entry: the orphan sweep and both checks of `repair` and `vendor --check` for wiring without a ledger entry take a JVM entry for the owner of `maven/`, and read MODULE.bazel for a directory it still names. `repair` on such a checkout finds nothing to do. - Beside a Maven or Gradle build, a `vendor` that finds that build in sync and the hub's copy missing or changed, or its entry gone, writes them again and reports `vendor_artifact_rebuilt`. - Beside a Maven or Gradle build `vex` hashes the jar of that build's tree, as before, not the hub's copy. - What a person reads. After a run that wrote for a hub, alone or beside another build, the files to commit name MODULE.bazel and .bazelignore with .socket/vendor/. For a hub alone the next step is `bazel build //...` ("MODULE.bazel names their directory"), the undo names no install to resync and gives no `reinstall_required`: no installed tree holds the jar. A decline names the purl once. Tests Unit, socket-patch-core: the entry and its four files, the declines, and the warnings of a vendored run (bazel::maven: `a_vendored_entry_names_the_directory_of_its_patch`, `a_vendored_entry_is_declined_as_a_hosted_one_but_for_downloads`, `a_vendored_run_is_warned_of_the_jars_it_wrote_no_entry_for`); the pair of .bazelignore (`the_jars_of_a_hub_have_a_pair_of_their_own`); the undo and the ignored directory (vendor::maven_repo: `the_revert_takes_the_hub_entry_out_before_its_directory`, `a_hub_directory_that_git_ignores_is_refused`); the way back to hosted (`a_maven_patch_of_a_bazel_hub_alone_is_in_reach`, `a_hosted_run_drops_the_hub_directory_that_nothing_names`); discovery (`an_entry_that_names_a_directory_is_vendored_wiring`) and a row of `what_is_not_an_entry_of_the_pin`. Unit, socket-patch-cli: `orphan_sweep_keeps_the_jar_of_a_bazel_hub`, and the commit hint and the install command of the `bazel` flavor. Without Bazel (tests/vendor_jvm_cli.rs): - `vendor_gives_a_pinned_bazel_hub_the_patched_jar`, alone and beside a Maven reactor: the four files, the block, the ledger entry, a rerun that changes nothing and downloads nothing, `vendor --check`, `list`, `repair`, `vex`, a changed jar, a jar that keeps the patch's file beside a member of its own, a changed BUILD file, a MODULE.bazel without the entry, a block changed by hand, a lock that no longer pins the jar, a lost jar put back by `repair` and by `vendor`, `vendor --revert`, `rollback` and `remove`, each back to the bytes of before, and the lines a person reads. - `vendor_declines_for_a_hub_it_cannot_patch`: the code, the exit, nothing written, and no warning that repeats the failure. - `vendor_leaves_the_hosted_entry_of_a_bazel_hub_in_place` also holds `vendor` over a hosted entry beside a Maven build whose hub it can patch (the vendored entry in its place, taken out by `vendor --revert`), and in a checkout only Bazel builds: the vendored entry in its place, or, for a hub it declines, the checkout unchanged and a reason that says the hosted entry stays. - tests/e2e_bazel_maven_beside.rs, `a_hosted_run_removes_the_jar_vendored_mode_kept_for_the_hub`: a hosted `get` beside a pom, over a vendored entry, leaves the hosted block and neither the directory nor the `.bazelignore` line. With a real Bazel (tests/e2e_bazel_build/maven.rs, the patch host played by a local server): - `a_vendored_patch_in_a_tree_only_bazel_builds` takes the place of the flow of the previous commit: the build prints the marker of the patched jar and changes no file, a `--lockfile_mode=error` build passes, `bazel query //...` lists no package under .socket, `list` and `vex` see a vendored patch, `vendor --check` fails for a changed jar that Bazel builds all the same, a second output base builds patched with the local server stopped while the repository cache holds the hub's jar and not the patched one, and `vendor --revert` restores every file and the first build. On a Bazel before 7.5.0 it first holds the decline of a checkout that names no release: the failure is the first event, before a download. - `a_hub_goes_from_hosted_to_vendored_and_back`: `vendor` over a hosted entry, `get --mode hosted` over the vendored one, the vendored command again, and `rollback`; one entry for the jar at every step. - The harness's local server is no longer taken from wiremock's pool, so that stopping it closes its port. Every flow of the target starts its server this way now. Existing expectations that change: - `a_bazel_hub_that_builds_a_vendored_jar_adds_one_warning_and_nothing_else`: its checkout names no Bazel release, so the warning is now `maven_bazel_release` with that reason, where it was `maven_bazel_hub_unpatched`. - `a_takeover_leaves_the_entry_of_a_bazel_hub` (unit): a pin that only the block wires is among the pins of an eject where the hub is the only build, and still not beside a pom. - The flow of the previous commit, which recorded the failure. Docs: "Bazel workspaces: Maven" in docs/ecosystems.md, and in "Bazel workspaces: what is supported" the Maven row (vendored: "Supported with Bazel 7.4.0 or later"; VEX: "Supported with a hosted or vendored patch") with its entries. No entry is added to the known problems: no state was found in which a vendored command exits 0 and the next Bazel build fails. The rows of the codes in CLI_CONTRACT.md. bazel-maven.yml starts its legs for a change to vendor/maven_repo.rs and vendor/refusals.rs too. Run on macOS arm64, every child behind a logging proxy that refuses public Maven hosts: the six Maven flows pass on Bazel 9.3.2 (118 s), 8.8.2 (124 s), 7.7.2 (78 s) and 7.4.0 (72 s), with no request to such a host. With a binary built from the previous commit the two new flows fail on 9.3.2. Outside a Bazel workspace this binary and that one print the same bytes and leave the same files for twelve commands on a Maven reactor and on a Gradle build. Not here: `scan` does not find the artifacts of a hub (it vendors a hub's jar for a package it found elsewhere); an artifact that a Maven build beside the hub does not use at the patch's version is skipped as before, where hosted mode patches the hub; agent mode is not supported for a Bazel build and patches no hub; a hub without a lock and a `maven_install` of a WORKSPACE file are declined. scripts/loc-budget.json: bazel 2486 -> 2656. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-maven.yml | 28 +- crates/socket-patch-cli/CLI_CONTRACT.md | 12 +- crates/socket-patch-cli/src/commands/apply.rs | 3 +- crates/socket-patch-cli/src/commands/mod.rs | 79 ++- .../socket-patch-cli/src/commands/rollback.rs | 11 +- .../src/commands/scan/hosted.rs | 19 + .../socket-patch-cli/src/commands/vendor.rs | 178 +++++- .../src/commands/vendor_orphans.rs | 7 +- .../src/commands/vendored_backend/repair.rs | 21 +- .../src/commands/vex_sources.rs | 8 +- .../tests/e2e_bazel_build/harness.rs | 28 +- .../tests/e2e_bazel_build/maven.rs | 342 +++++++++-- .../tests/e2e_bazel_maven_beside.rs | 49 ++ .../socket-patch-cli/tests/vendor_jvm_cli.rs | 532 +++++++++++++++- crates/socket-patch-core/src/bazel/ignore.rs | 119 +++- crates/socket-patch-core/src/bazel/maven.rs | 534 ++++++++++++++-- crates/socket-patch-core/src/hosted/engine.rs | 7 +- .../socket-patch-core/src/hosted/takeover.rs | 23 +- .../patch/redirect/upstream/bazel_maven.rs | 23 +- .../src/vendor/maven_repo.rs | 568 +++++++++++++++++- .../src/vendor/redownload.rs | 9 +- .../socket-patch-core/src/vendor/refusals.rs | 29 +- .../src/vex/discover/bazel_maven.rs | 70 ++- docs/ecosystems.md | 154 ++++- scripts/loc-budget.json | 2 +- 25 files changed, 2589 insertions(+), 266 deletions(-) diff --git a/.github/workflows/bazel-maven.yml b/.github/workflows/bazel-maven.yml index c4a320fac..e509c445c 100644 --- a/.github/workflows/bazel-maven.yml +++ b/.github/workflows/bazel-maven.yml @@ -1,13 +1,18 @@ 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 version bump of the patched artifact, and a hub the block cannot -# patch. bazel-compatibility.yml holds the legs and what every ecosystem +# 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 @@ -57,11 +62,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/, @@ -87,6 +95,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] @@ -113,6 +123,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 a1d543d5e..c24d9e7ea 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2412,7 +2412,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). | @@ -2660,15 +2660,15 @@ command's integration tests check its output. | `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`. | | `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". | | `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 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`, 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`". | -| `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 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_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". | +| `bazelignore_not_updated` | run-level `warnings[]` | Go vendored and agent mode, 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` 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`". | +| `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 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_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 28177a3eb..6727529a6 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -56,12 +56,15 @@ 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, so that Bazel and gazelle read -/// no package there (`socket_patch_core::bazel::ignore`). A command that can +/// no package there (`socket_patch_core::bazel::ignore`), and the directory +/// of the patched Maven jars that vendored mode keeps for a hub. 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` out only takes away the pair of a copy -/// that is gone. So does the prune pass of a scan, which comes here after +/// that is gone, as one that leaves `maven` out does for the jars. 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. /// @@ -71,7 +74,8 @@ pub(crate) async fn sync_bazelignore( common: &crate::args::GlobalArgs, adds: bool, ) -> Vec { - use socket_patch_core::{bazel::ignore, crawlers::Ecosystem::Golang}; + use socket_patch_core::bazel::ignore; + use socket_patch_core::crawlers::Ecosystem::{Golang, Maven}; let mut warnings = Vec::new(); if common.dry_run || common.is_global() { return warnings; @@ -83,30 +87,44 @@ pub(crate) async fn sync_bazelignore( projects.push(common.project_root()); } let (loud, mut told) = (!common.json && !common.silent, Vec::new()); + // What a person is told of the file, when it stays and when it goes: + // of the Go copies, then of the jars. + let said = [ + ( + "the lines that keep patched Go module copies under .socket out of Bazel's packages", + "no patched Go module copy is left under .socket", + ), + ( + "the line that keeps the patched Maven jars under .socket out of Bazel's packages", + "no patched Maven jar is left under .socket", + ), + ]; for project in projects { - match ignore::sync(&project, adds && common.ecosystem_selected(Golang)).await { - Ok(Some(file)) if loud && !told.contains(&file) => { - let (verb, what) = match file.exists() { - true => ( - "Updated", - "the lines that keep patched Go module copies under .socket out of \ - Bazel's packages", - ), - false => ("Removed", "no patched Go module copy is left under .socket"), - }; - println!("{verb} {}: {what}", file.display()); - told.push(file); - } - Err(detail) if adds => { - if loud { - eprintln!("Warning: {detail}"); + let synced = [ + ignore::sync(&project, adds && common.ecosystem_selected(Golang)).await, + ignore::sync_jars(&project, adds && common.ecosystem_selected(Maven)).await, + ]; + for (synced, (stays, gone)) in synced.into_iter().zip(said) { + match synced { + Ok(Some(file)) if loud && !told.contains(&(file.clone(), stays)) => { + let (verb, what) = match file.exists() { + true => ("Updated", stays), + false => ("Removed", gone), + }; + println!("{verb} {}: {what}", file.display()); + told.push((file, stays)); + } + Err(detail) if adds => { + if loud { + eprintln!("Warning: {detail}"); + } + warnings.push(crate::json_envelope::RunWarning::new( + ignore::NOT_UPDATED, + detail, + )); } - warnings.push(crate::json_envelope::RunWarning::new( - ignore::NOT_UPDATED, - detail, - )); + _ => {} } - _ => {} } } warnings @@ -125,24 +143,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 2cefed2cc..30fd224cd 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2745,7 +2745,16 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let gc_bytes_freed = gc.map_or(0, |gc| gc.bytes_freed); // ── run-level warnings ─────────────────────────────────────── - let unwired_any = !vendored_leg.reverted.is_empty() + // 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 unwired_any = vendored_leg.reverted.iter().any(|key| !of_hub(key)) || !vendored_leg.preserved.is_empty() || !hosted_leg.reverted.is_empty(); let advised = ReinstallAdvised::of( diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index dbdbdfe91..84bb90012 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2235,6 +2235,24 @@ 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 uuids = rewrite.confirmed_bazel_maven_uuids.iter(); + let left = socket_patch_core::vendor::maven_repo::drop_unnamed_units( + &common.cwd, + module, + uuids, + state, + ); + let warning = |detail| RunWarning::new("cleanup_failed", detail); + unit_warnings.extend(left.await.into_iter().map(warning)); + } // The agent-mode manifest's records: local proof that an installed copy // was patched in place, for the stale-install probes below. @@ -2570,6 +2588,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()); // Granted, but nothing in the project pins it (no lock entry, 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 9ea104bcf..da9c39028 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 851cf0731..26fb3a0c3 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/maven.rs @@ -42,10 +42,26 @@ //! //! - [`a_vendored_patch_in_a_tree_only_bazel_builds`]: vendored mode in the //! checkout without a `pom.xml`. `socket-patch get --mode vendored -//! --yes` fails (exit 1, `vendor_jvm_shape_unsupported`: no Maven, Gradle, -//! sbt or scala-cli build is there to pin), says that the hub builds the -//! upstream jar (`maven_bazel_hub_unpatched`) and writes no file: the -//! build prints the upstream marker before and after. +//! --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 @@ -103,7 +119,9 @@ 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; -use crate::harness::{changed, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING}; +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 @@ -848,15 +866,109 @@ fn a_version_bump_of_the_patched_artifact() { ); } -/// The command of vendored mode, and what it says today of a patch whose -/// jar only a hub builds. +/// The command of vendored mode. const VENDORED: [&str; 5] = ["get", PURL, "--mode", "vendored", "--yes"]; -const NO_BUILD: &str = "reason: no_build_file: no pom.xml, Gradle, sbt or scala-cli build at the \ - project root"; +/// 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") + } -/// Vendored mode in a checkout that only Bazel builds: the command fails -/// for want of a Maven or Gradle build to pin, says that the hub builds -/// the upstream jar, and leaves every file and the build as they were. + /// 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() { @@ -864,61 +976,193 @@ fn a_vendored_patch_in_a_tree_only_bazel_builds() { let Some(flow) = Pinned::open(test, false, &|_, _| {}) else { return; }; - flow.builds_upstream(); + 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 said = &get.dump; - assert_eq!(get.code, 1, "{test}: {said}"); - let events = get.envelope["events"].as_array().expect("events"); - let failed = events.iter().find(|event| event["action"] == "failed"); - let failed = failed.unwrap_or_else(|| panic!("{test}: nothing failed: {said}")); + let vendored = flow.vendored_by(&get, &before); + let downloads = flow.standin.asked(&flow.patch.archive); assert_eq!( - (&failed["purl"], &failed["errorCode"], &failed["error"]), - ( - &json!(PURL), - &json!("vendor_jvm_shape_unsupported"), - &json!(NO_BUILD) - ), - "{test}: {said}" + 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() ); - assert_eq!(get.envelope["summary"]["applied"], 0, "{test}: {said}"); - let warnings = get.envelope["warnings"].as_array().expect("warnings"); - let [warning] = &warnings[..] else { - panic!("{test}: not one warning: {said}"); + 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}" + ); }; - let detail = warning["detail"].as_str().unwrap_or_default(); - let unpatched = - format!("{PURL}: Bazel takes this artifact from maven_install.json (hub \"{HUB}\", "); + 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!( - warning["code"], "maven_bazel_hub_unpatched", - "{test}: {said}" + (twin.cached(&fetched), twin.cached(&patch.sha256)), + (true, false), + "{test}: the repository cache holds the hub's jar, and not the patched one" ); - assert!( - detail.starts_with(&unpatched) && detail.contains("the Bazel build stays unpatched"), + 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(&before, &flow.cell.tree()), + changed(&hosted, &flow.cell.tree()), NOTHING, "{test}: {said}" ); - for route in [&flow.patch.route, &flow.patch.archive] { - let asked = flow.standin.asked(route); - assert_eq!(asked, 0, "{test}: the command fetched {route}"); - } + flow.builds_patched(&hosted); - // The build is the one of before, and the undo of vendored mode has - // nothing to take out. - flow.cell.builds(&flow.upstream); - let undo = flow.vendored(&["vendor", "--revert", "--yes"]); - assert_eq!(undo.code, 0, "{test}: {}", undo.dump); - assert_eq!(changed(&before, &flow.cell.tree()), NOTHING, "{test}"); + // 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 {:?} before and after `get --mode vendored` failed for {PURL} \ - (vendor_jvm_shape_unsupported) and wrote nothing; {:?}", + "{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() ); } 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 c494e7a0a..db52541da 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_maven_beside.rs @@ -644,6 +644,55 @@ fn a_pinned_hub_gets_its_block_and_the_undo_takes_it_out() { assert!(!person.stderr.contains("Warning: pkg:maven"), "{person:?}"); } +/// 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. +#[test] +fn a_hosted_run_removes_the_jar_vendored_mode_kept_for_the_hub() { + let machine = Machine::start(); + 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(), true, 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"); + } + let get = machine.step(COMMANDS[0]); + assert_eq!(get.code, Some(0), "{get:?}"); + assert_eq!(get.envelope()["warnings"], Value::Null, "{get:?}"); + let with_block = format!("{HUB}\n{BLOCK}"); + assert_eq!( + String::from_utf8_lossy(&get.wrote[MODULE]), + with_block, + "{get:?}" + ); + 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(), "{get:?}"); +} + /// The Bazel files of a checkout, each with its text. type Files = Vec<(&'static str, String)>; diff --git a/crates/socket-patch-cli/tests/vendor_jvm_cli.rs b/crates/socket-patch-cli/tests/vendor_jvm_cli.rs index 95ef1de0e..be716d381 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,495 @@ 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)); + 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 jar that is lost comes back: by `repair` where it is the + // vendored artifact, and by the next `vendor` beside a Maven build, + // which gives the hub the jar of the Maven tree again. + std::fs::remove_file(root.join("proj").join(unit("file/foo-1.0.jar"))).unwrap(); + let (code, check) = socket(root, &["vendor", "--check"]); + assert_eq!(code, Some(1), "{alone}: {check}"); + let back = ok(root, if alone { &["repair"] } else { &["vendor"] }); + 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. + let manifest = root.join("proj/.socket/manifest.json"); + let patches = std::fs::read(&manifest).unwrap(); + let foo = purl("foo"); + for undo in [ + &["vendor", "--revert"][..], + &["rollback", &foo], + &["remove", &foo], + ] { + std::fs::write(&manifest, &patches).unwrap(); + ok(root, &["vendor"]); + assert_eq!(snapshot(root), vendored, "{alone} {undo:?}"); + let undone = ok(root, undo); + assert_eq!(snapshot(root), pristine, "{alone} {undo:?}"); + // 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}" + ); + } + + // 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}"); + } +} + +/// 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 aad0e4476..de9b0cef4 100644 --- a/crates/socket-patch-core/src/bazel/ignore.rs +++ b/crates/socket-patch-core/src/bazel/ignore.rs @@ -10,6 +10,15 @@ //! fails to load rules_go from it. A `.bazelignore` line keeps both out. //! Bazel reads the file at the root of the workspace only and takes each //! line as a literal directory path from that root. +//! +//! 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. [`sync_jars`] keeps the line for +//! that directory, as [`sync`] does for the Go copies. use std::path::{Path, PathBuf}; @@ -23,6 +32,29 @@ pub const NOT_UPDATED: &str = "bazelignore_not_updated"; const COMMENT: &str = "# socket-patch: patched Go module copies, not Bazel packages (to opt out, comment out the next line)"; +/// The directories a call keeps lines for, the line above each line it +/// writes, and why a user has to add a line that could not be written. +struct Kept { + dirs: &'static [&'static str], + comment: &'static str, + why: &'static str, +} + +const GO: Kept = Kept { + dirs: &[GO_VENDOR_DIR, GO_PATCHES_DIR], + comment: COMMENT, + why: "so that Bazel and gazelle do not read the patched Go module copies there as packages \ + (`bazel run //:gazelle` or `bazel build //...` can otherwise break the build)", +}; + +const JARS: Kept = Kept { + dirs: &[super::maven::UNITS], + comment: "# socket-patch: patched Maven jars for a Bazel hub, not Bazel packages (to opt out, \ + comment out the next line)", + why: "so that Bazel reads no package of the workspace in the directory of the patched Maven \ + jars", +}; + /// How [`COMMENT`] starts, in this wording and in any other. A line is /// [`sync`]'s to remove only when it stands under a line that starts so, /// and a user who puts a `#` before that line has declined it: [`sync`] @@ -51,10 +83,18 @@ const MARK: &str = "# socket-patch:"; /// has done its work either way. pub async fn sync(project: &Path, add: bool) -> Result, String> { let project = project.to_path_buf(); - run_blocking(move || sync_blocking(&project, add)).await + run_blocking(move || sync_blocking(&project, &GO, add)).await } -fn sync_blocking(project: &Path, add: bool) -> Result, String> { +/// [`sync`] for the directory of the jars that vendored mode keeps for a +/// rules_jvm_external hub, `.socket/vendor/maven`: one line under a comment +/// line of its own while the directory exists, with the same rules. +pub async fn sync_jars(project: &Path, add: bool) -> Result, String> { + let project = project.to_path_buf(); + run_blocking(move || sync_blocking(&project, &JARS, add)).await +} + +fn sync_blocking(project: &Path, kept: &Kept, add: bool) -> Result, String> { let Some(root) = super::bazel_root(project) else { return Ok(None); }; @@ -69,8 +109,11 @@ fn sync_blocking(project: &Path, add: bool) -> Result, String> { Ok(meta) => Some(meta.is_dir()), Err(e) => (e.kind() == std::io::ErrorKind::NotFound).then_some(false), }; - let wanted = - [GO_VENDOR_DIR, GO_PATCHES_DIR].map(|dir| (format!("{from_root}{dir}"), exists(dir))); + let wanted = kept.dirs.iter(); + let wanted: Vec<_> = wanted + .map(|dir| (format!("{from_root}{dir}"), exists(dir))) + .collect(); + let edited = |old: &[u8]| edited(old, &wanted, add, kept.comment); let file = root.dir.join(".bazelignore"); let read = || match read_regular_to_bytes_sync(&file) { @@ -80,7 +123,7 @@ fn sync_blocking(project: &Path, add: bool) -> Result, String> { // Most runs find nothing to change, and take no lock to find that. A // file that cannot be read is an edit only with a copy to name in it. let unlocked = read().unwrap_or_default(); - if edited(&unlocked, &wanted, add) == unlocked { + if edited(&unlocked) == unlocked { return Ok(None); } let _lock = lock(&root.dir); @@ -88,7 +131,7 @@ fn sync_blocking(project: &Path, add: bool) -> Result, String> { Ok(old) => (old, None), Err(e) => (Vec::new(), Some(e)), }; - let new = edited(&old, &wanted, add); + let new = edited(&old); // The root is canonical: on Windows that spelling has a prefix no user // types and no tool prints. let shown = crate::utils::pnpm_workspace::without_verbatim_prefix(file.clone()); @@ -114,10 +157,9 @@ fn sync_blocking(project: &Path, add: bool) -> Result, String> { .collect(); let advice = if !missing.is_empty() { format!( - "add {} to it on a line of its own, with no space before or after, so that Bazel \ - and gazelle do not read the patched Go module copies there as packages (`bazel run \ - //:gazelle` or `bazel build //...` can otherwise break the build)", - missing.join(" and ") + "add {} to it on a line of its own, with no space before or after, {}", + missing.join(" and "), + kept.why ) } else { "the lines under socket-patch's comment in it name directories that no longer exist \ @@ -224,7 +266,7 @@ fn settled(old: &[u8], path: &str) -> bool { /// no line break gets one before the pair and none after it, and loses that /// one (the comment line's own) with a pair that ends the file that way, so /// that the file without the pair is the file of before, byte for byte. -fn edited(old: &[u8], wanted: &[(String, Option)], add: bool) -> Vec { +fn edited(old: &[u8], wanted: &[(String, Option)], add: bool, comment: &str) -> Vec { let gone = |line: &[u8]| { wanted .iter() @@ -254,8 +296,8 @@ fn edited(old: &[u8], wanted: &[(String, Option)], add: bool) -> Vec { continue; } let pair = match new.is_empty() || new.ends_with(b"\n") { - true => format!("{COMMENT}{nl}{line}{nl}"), - false => format!("{nl}{COMMENT}{nl}{line}"), + true => format!("{comment}{nl}{line}{nl}"), + false => format!("{nl}{comment}{nl}{line}"), }; new.extend_from_slice(pair.as_bytes()); } @@ -275,7 +317,7 @@ mod tests { fn edit(old: &str, vendor: bool, patches: bool) -> String { let wanted = [(VENDOR, vendor), (PATCHES, patches)]; let wanted = wanted.map(|(line, exists)| (line.to_string(), Some(exists))); - String::from_utf8(edited(old.as_bytes(), &wanted, true)).unwrap() + String::from_utf8(edited(old.as_bytes(), &wanted, true, COMMENT)).unwrap() } fn pair(line: &str) -> String { @@ -660,6 +702,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, and neither call + /// touches the other's pair or adds one for the other's directory. + #[tokio::test] + async fn the_jars_of_a_hub_have_a_pair_of_their_own() { + let jars = JARS.dirs[0]; + assert_eq!(jars, ".socket/vendor/maven"); + assert!(JARS.comment.starts_with(MARK) && JARS.comment != COMMENT); + let of_jars = format!("{}\n{jars}\n", JARS.comment); + let (_tmp, root, project) = project("", jars); + let file = root.join(".bazelignore"); + let left = || fs::read_to_string(&file).ok(); + assert_eq!(sync(&project).await, Ok(None), "no Go copy"); + assert_eq!(sync_jars(&project, false).await, Ok(None), "Maven left out"); + assert_eq!(left(), None); + assert_eq!(sync_jars(&project, true).await, changed(&root)); + assert_eq!(sync_jars(&project, true).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(); + assert_eq!(sync(&project).await, Ok(None)); + assert_eq!(sync_jars(&project, false).await, changed(&root)); + 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", JARS.comment); + for settled in [".socket\n", ".socket/vendor\n", declined.as_str()] { + fs::write(&file, settled).unwrap(); + assert_eq!(sync_jars(&project, true).await, Ok(None), "{settled:?}"); + assert_eq!(left().as_deref(), Some(settled)); + } + // What cannot be written is said with the line to add, and why. + fs::remove_file(&file).unwrap(); + fs::create_dir(&file).unwrap(); + let detail = sync_jars(&project, true).await.expect_err("a directory"); + assert!( + detail.contains("add `.socket/vendor/maven` to it") && detail.ends_with(JARS.why), + "{detail}" + ); + } + #[tokio::test] async fn a_project_below_the_root_is_named_from_the_root() { let (_tmp, root, project) = project("svc/go", PATCHES); diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 188c8b8d4..ef361b7b4 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -22,6 +22,16 @@ //! [`site`] says for each whether its entry may be written, [`rewrite`] //! writes it, [`pins`] reads the block for `list`, `rollback`, `remove` //! and `vex`, and [`without`] takes an entry out. +//! +//! 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. @@ -615,17 +625,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() } @@ -655,13 +689,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\ @@ -672,10 +716,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") ) @@ -704,13 +764,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)) @@ -774,7 +841,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()), @@ -792,6 +859,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` @@ -845,7 +1003,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. @@ -945,6 +1103,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 { @@ -998,7 +1157,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" @@ -1072,8 +1239,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 @@ -1081,8 +1249,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; }; @@ -1109,19 +1295,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 } @@ -1204,22 +1388,12 @@ 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(); + if held == Some(&dep.patch_uuid) && code != NO_EFFECT { + 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 }); } @@ -1240,6 +1414,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. @@ -1271,8 +1448,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(); @@ -1286,16 +1462,50 @@ pub fn pins(root: &Path, module: &str) -> Result, String> { /// 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) { + (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(); @@ -1447,6 +1657,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) { @@ -2497,7 +2712,7 @@ override_repo( /// What [`site`] says of netty's jar in the checkout: `write