diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index f42bc6af0..e0e9afd8b 100644 --- a/.github/workflows/bazel-go.yml +++ b/.github/workflows/bazel-go.yml @@ -1,16 +1,18 @@ name: Bazel patch compatibility (Go) -# The Go flow of the real-Bazel tests (`go::` in `e2e_bazel_build`): hosted -# mode for a module that gazelle's `go_deps` resolves from `go.mod`, on -# each Bazel release below. bazel-compatibility.yml holds the legs and what -# every ecosystem shares; this file says when the Go legs run and on which -# releases. +# The Go flows of the real-Bazel tests (`go::` in `e2e_bazel_build`): +# hosted, vendored and agent mode for a module that gazelle's `go_deps` +# resolves from `go.mod`, on each Bazel release below. +# bazel-compatibility.yml holds the legs and what every ecosystem shares; +# this file says when the Go legs run and on which releases. # # Beyond what every leg needs, a Go leg downloads the Go SDK from # dl.google.com (about 100 MB, held by its repository cache) and asks go.dev # for the Go release list on every run. A Go module under test never comes # from the repository cache: `go` fetches a module into the output base, -# which every test makes anew. +# which every test makes anew. The same holds for the modules gazelle is +# built from, which a test that runs `bazel run //:gazelle` has `go` fetch +# from proxy.golang.org. # # Not required for merge: no `merge_group` trigger, and no job here is a # `needs` of ci.yml's `ci-ok`. @@ -20,8 +22,9 @@ on: types: [opened, synchronize, reopened, ready_for_review] # What a pull request run covers: the Go flow and its fixture, the # harness and the workflows that run it, the Bazel installer and its - # pins, and the Go files the flow runs through, as go-compatibility.yml - # lists them. Nothing another ecosystem's flow owns is here, so a change + # pins, the Go files the flow runs through, as go-compatibility.yml + # lists them, and what socket-patch does only in a Bazel workspace + # (`bazel/`). Nothing another ecosystem's flow owns is here, so a change # to one ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, @@ -41,6 +44,7 @@ on: - 'crates/*/src/**/*golang*' - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' + - 'crates/socket-patch-core/src/bazel/**' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -60,6 +64,7 @@ on: - 'crates/*/src/**/*golang*' - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' + - 'crates/socket-patch-core/src/bazel/**' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8f2665cba..bae4a14dc 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2399,6 +2399,7 @@ 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`". | | `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 7e577cbcd..5619ca59b 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1848,6 +1848,9 @@ pub(crate) async fn run_locked( } } } + // The copies under `.socket/go-patches` are as this run leaves + // them (a reconcile may have removed the last one). + run_warnings.extend(crate::commands::sync_bazelignore(&args.common, true).await); // Human per-package report BEFORE the embedded VEX runs, so // the VEX step's own notes follow the report instead of diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index ada46feb8..378213a89 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -51,6 +51,64 @@ pub(crate) fn project_state_in_scope(common: &crate::args::GlobalArgs) -> bool { !common.is_global() } +/// 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 +/// 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 +/// 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. +/// +/// A human run is told here that the file changed, or why it could not be; +/// the result is that warning again, for the command's envelope. +pub(crate) async fn sync_bazelignore( + common: &crate::args::GlobalArgs, + adds: bool, +) -> Vec { + use socket_patch_core::{bazel::ignore, crawlers::Ecosystem::Golang}; + let mut warnings = Vec::new(); + if common.dry_run || common.is_global() { + return warnings; + } + // The agent copies are those of `--cwd`, the vendored ones those of + // the manifest's project. A root both are under is named once. + let mut projects = vec![common.cwd.clone()]; + if common.manifest_project_is_foreign() { + projects.push(common.project_root()); + } + let (loud, mut told) = (!common.json && !common.silent, Vec::new()); + 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}"); + } + warnings.push(crate::json_envelope::RunWarning::new( + ignore::NOT_UPDATED, + detail, + )); + } + _ => {} + } + } + warnings +} + /// The vendor-ledger keys (`ledger`, the project's /// [`VendorState::purl_keys`]) that own this run's installed copies. In /// project scope that is the whole ledger. Under global scope the ledger diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index d5fcbbd3e..496f6f578 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -1116,7 +1116,11 @@ pub async fn run(args: RemoveArgs) -> i32 { // Artifacts the sweep examined (repair's `details.checked`), and the // passes that failed (`cleanup_failed` run warnings under `--json`). let mut gc_checked = 0usize; - let mut cleanup_warnings: Vec<(String, String)> = Vec::new(); + // The rollback, the vendored revert and the orphan sweep above are + // done with the Go copies. + let ignored = crate::commands::sync_bazelignore(&args.common, true).await; + let mut cleanup_warnings: Vec<(String, String)> = + ignored.into_iter().map(|w| (w.code, w.detail)).collect(); if !args.preserve_state { let sweep = references.sweep(&socket_dir, args.common.dry_run).await; // repair's posture: a failed pass (or a pass that could not unlink @@ -1860,6 +1864,8 @@ async fn remove_ledger_only( let mut env = Envelope::new(Command::Remove); env.dry_run = args.common.dry_run; env.warnings.extend(commit_recovery); + env.warnings + .extend(crate::commands::sync_bazelignore(&args.common, true).await); // The reverts ARE the removal: every event is recorded, so // `summary.removed` counts the reverted entries (`summary.verified` // the would-be removals on --dry-run). diff --git a/crates/socket-patch-cli/src/commands/repair.rs b/crates/socket-patch-cli/src/commands/repair.rs index fd0757cff..610a70dfb 100644 --- a/crates/socket-patch-cli/src/commands/repair.rs +++ b/crates/socket-patch-cli/src/commands/repair.rs @@ -208,6 +208,8 @@ pub async fn run(args: RepairArgs) -> i32 { // client's public-proxy advisory ahead of its own output. let mut client: Option = None; let result = repair_inner(&args, &manifest_path, &mut client, vendor_references).await; + // A vendored Go copy may be back on disk, also when the repair failed. + let ignored = crate::commands::sync_bazelignore(&args.common, true).await; let auth_fallback = client .as_ref() .and_then(crate::commands::vex_sources::api_auth_fallback_warning); @@ -224,6 +226,7 @@ pub async fn run(args: RepairArgs) -> i32 { Ok((mut env, counts)) => { env.warnings.extend(commit_recovery); env.warnings.extend(auth_fallback); + env.warnings.extend(ignored); let had_failure = matches!(env.status, Status::PartialFailure | Status::Error); if had_failure { track_patch_repair_failed("One or more artifacts failed to download", &telemetry) @@ -248,6 +251,7 @@ pub async fn run(args: RepairArgs) -> i32 { let mut env = error_envelope(Command::Repair, args.common.dry_run, &e.code, &e.message); env.warnings.extend(commit_recovery); + env.warnings.extend(ignored); crate::ui::print_json(&env.to_value()); } else { eprintln!("Error: {}", e.message); diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 36f2e0d1a..dd37e1ac0 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2671,6 +2671,9 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { .iter() .chain(hosted_leg.warnings.iter()) .for_each(|(code, detail)| run_warnings.push((code.clone(), detail.clone()))); + // Every leg and the orphan sweep are done with the Go copies. + let ignored = crate::commands::sync_bazelignore(&args.common, true).await; + run_warnings.extend(ignored.into_iter().map(|w| (w.code, w.detail))); // A restored package whose ownership could not be put back, or // whose stale bytecode could not be removed (the engine reports // it on `error` with `success: true`), is restored but worth a diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index b45add765..a74752506 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2175,6 +2175,12 @@ async fn run_redirect_selected_untracked( .push(socket_patch_core::patch::redirect::RewriteWarning { code, detail }); } } + // A run that took the lock may have removed a vendored Go copy (a + // takeover). One that took none may write no file (`socket.yml`). + let ignored = match &lock { + Some(_) => crate::commands::sync_bazelignore(common, true).await, + None => Vec::new(), + }; let mut warnings: Vec = engine_warnings .iter() .map(|w| RunWarning::new(w.code.as_str(), w.detail.as_str())) @@ -2219,6 +2225,7 @@ async fn run_redirect_selected_untracked( record_hosted_events(&mut env, &confirmed, &unconfirmed, &skipped, common.dry_run); env.set_extra("redirect", redirect_block(done.rewritten.clone())); env.warnings.extend(warnings); + env.warnings.extend(ignored); // Taking the lock may have finished an interrupted run's commit // (stderr said so then). env.warnings.extend( diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 59ff28fc7..f9f6cc0c3 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -620,6 +620,8 @@ async fn vendor_under_lock( env.mark_partial_failure(); } note_classic_migration_risk(&mut env, &common.cwd, common); + env.warnings + .extend(crate::commands::sync_bazelignore(common, true).await); Ok((has_errors, env)) } diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 982fc4d71..6d057f474 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -1282,6 +1282,8 @@ pub async fn run(args: VendorArgs) -> i32 { } note_classic_migration_risk(&mut env, &args.common.cwd, &args.common); + env.warnings + .extend(crate::commands::sync_bazelignore(&args.common, true).await); // Everything below is output and telemetry, so release the lock before // the telemetry round-trip. @@ -2446,6 +2448,10 @@ async fn run_eject( print_vendor_closing(common, &env, 0, &capture.wired_flavors, true, None); } note_classic_migration_risk(&mut env, &common.cwd, common); + // After the rollback, so that the file names no copy the eject made + // and took away again. + env.warnings + .extend(crate::commands::sync_bazelignore(common, true).await); drop(guard); // Embedded VEX: same contract as the manifest-driven arm — only on @@ -5358,6 +5364,11 @@ pub(crate) async fn run_vendor_gc( let warning = orphan_removal_failed(unit, e); out.write_failures.push((warning.code, warning.detail)); } + // A pass that took a vendored copy away may have taken the last Go one, + // after the scan's own step was done with the file: its pair goes too. + if !dry_run && (ledger_dirty || out.orphan_dirs > 0) { + crate::commands::sync_bazelignore(common, false).await; + } out } diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs index 3060b0a77..ba452a93b 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -1,8 +1,8 @@ -//! Hosted mode for a Go module that comes through gazelle's -//! `go_deps.from_file(go_mod = "//:go.mod")` under Bzlmod. +//! A Go module that comes through gazelle's +//! `go_deps.from_file(go_mod = "//:go.mod")` under Bzlmod, in each mode. //! -//! One flow, on the Bazel the run is given ([`FIXTURE`] says which rulesets -//! go with its release), in a fresh output base: +//! Hosted mode is one flow, on the Bazel the run is given ([`FIXTURE`] says +//! which rulesets go with its release), in a fresh output base: //! //! - (a) `bazel build` and `bazel run //:consumer` print the unpatched //! marker. @@ -21,6 +21,13 @@ //! fails the build on the sum, and the upstream module is not fetched in //! its place. //! +//! Vendored and agent mode keep a patched copy of the module in the +//! checkout and point `go.mod` at it with a directory `replace` +//! ([`kept_copy_flow`]): the same steps (a) to (d), and between (c) and (d) +//! what the user does next in a gazelle workspace, `bazel run //:gazelle` +//! and a build, or `bazel build //...` when the module ships a BUILD file +//! of its own. +//! //! The marker is read from what Bazel built, and the patched one holds an //! id made for the run, so no cache of an earlier run can supply it. //! @@ -34,20 +41,26 @@ //! first build on and step (c) changes no flag. `go` asks the first entry //! and goes on to the second after a 404, as it goes from the public proxy //! to the real patch host in a build outside these tests. No public proxy -//! is in the list: on these gazelle releases the two modules of the test -//! are all that `go` asks a proxy for. The caller's other fetch settings -//! are pinned beside it ([`go_env`]), so a `GOPRIVATE` of the machine -//! cannot send `go` past the stand-ins. +//! is in the hosted flow's list: on these gazelle releases the two modules +//! of the test are all that `go` asks a proxy for. The vendored and agent +//! flows have the public proxy last in their list, for the modules gazelle +//! itself is built from. The caller's other fetch settings are pinned +//! beside it ([`go_env`]), so a `GOPRIVATE` of the machine cannot send `go` +//! past the stand-ins. use std::io::Write as _; use std::time::Instant; use base64::Engine as _; use serde_json::json; -use sha2::{Digest, Sha256}; +use sha2::{Digest, Sha256, Sha512}; +use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; -use crate::harness::{fixture_path, Cell, Fixture, StandIn, CONSUMER}; -use crate::hosted_memory_common::Patch; +use crate::envelope::find_event; +use crate::harness::{ + cell_without_bazel, changed, fixture_path, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, +}; +use crate::hosted_memory_common::{Patch, ORG}; /// The workspace the test builds, and the rulesets each Bazel release /// builds it with. @@ -92,10 +105,10 @@ fn h1(files: &[(String, &[u8])]) -> String { format!("h1:{encoded}") } -/// One version of a module holding [`GO_MOD`] and a `lib.go`, as a Go -/// module proxy serves it. An `h1:` covers the names and the contents of -/// the files, not the bytes of the zip, so the zip is built here and no -/// binary is committed. +/// One version of a module holding [`GO_MOD`], a `lib.go` and whatever +/// else it ships, as a Go module proxy serves it. An `h1:` covers the names +/// and the contents of the files, not the bytes of the zip, so the zip is +/// built here and no binary is committed. struct Module { path: String, version: String, @@ -108,8 +121,18 @@ struct Module { impl Module { fn new(path: &str, version: &str, lib: &[u8]) -> Module { + Module::shipping(path, version, lib, &[]) + } + + /// The module with the files `shipped` beside its two. + fn shipping(path: &str, version: &str, lib: &[u8], shipped: &[(&str, &[u8])]) -> Module { let name = |file: &str| format!("{path}@{version}/{file}"); - let files = [(name("go.mod"), GO_MOD), (name("lib.go"), lib)]; + let own: [(&str, &[u8]); 2] = [("go.mod", GO_MOD), ("lib.go", lib)]; + let files: Vec<(String, &[u8])> = own + .iter() + .chain(shipped) + .map(|(file, bytes)| (name(file), *bytes)) + .collect(); let mut archive = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); for (name, bytes) in &files { let options = zip::write::SimpleFileOptions::default(); @@ -157,14 +180,14 @@ fn serve_module(standin: &StandIn, host: &str, module: &Module) { standin.serve(5, &module.route(host, "zip"), &module.zip); } -/// The Socket API on `standin`: one free patch of the upstream module, -/// granted as the module `socket` on the stand-in patch host. `go` fetches -/// the module, not Bazel's downloader, so the grant may name the loopback -/// origin. -fn grant(standin: &StandIn, uuid: &str, socket: &Module) { +/// What the Socket API on `standin` grants for the one free patch of the +/// upstream module: the module `socket` on the stand-in patch host. `go` +/// fetches the module, not Bazel's downloader, so the grant may name the +/// loopback origin. +fn granted(standin: &StandIn, socket: &Module) -> serde_json::Value { let origin = standin.origin(); let url = format!("{origin}{}", socket.route(PATCH_HOST, "zip")); - let reference = json!({ + json!({ "status": "granted", "url": url, "purl": PURL, @@ -181,11 +204,16 @@ fn grant(standin: &StandIn, uuid: &str, socket: &Module) { "goModH1": socket.mod_h1, }, }, - }); + }) +} + +/// The Socket API on `standin`: one free patch of the upstream module, +/// granted as the module `socket`. +fn grant(standin: &StandIn, uuid: &str, socket: &Module) { let patch = Patch { purl: PURL.to_string(), uuid: uuid.to_string(), - reference, + reference: granted(standin, socket), }; standin.api(&[patch]); } @@ -361,6 +389,1146 @@ fn hosted_go_deps() { ); } +/// The BUILD file of a module that is itself built with Bazel, as such a +/// module ships it in its zip: it loads rules_go under the name rules_go +/// had before Bzlmod, which gazelle maps for the module's own repository +/// and nothing maps for a package of the checkout. +const SHIPPED_BUILD: &[u8] = b"load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\") + +go_library( + name = \"upstream\", + srcs = [\"lib.go\"], + importpath = \"example.com/upstream\", + visibility = [\"//visibility:public\"], +) +"; + +/// The line `socket-patch` writes above each of its `.bazelignore` lines. +const IGNORE_COMMENT: &str = + "# socket-patch: patched Go module copies, not Bazel packages (to opt out, comment out the next line)"; + +/// A mode that keeps a patched copy of the module in the checkout and +/// points `go.mod` at it with a directory `replace`. +#[derive(Clone, Copy, PartialEq)] +enum Kept { + /// `scan --mode vendored`: the copy is the archive the patch service + /// serves, committed under `.socket/vendor/golang`. + Vendored, + /// `scan --mode agent`, then the `apply` of every later install: the + /// copy is made from the module in the user's module cache, under + /// `.socket/go-patches`. + Agent, +} + +impl Kept { + /// The directory that holds every copy of the mode, from the project. + fn copies(self) -> &'static str { + match self { + Kept::Vendored => ".socket/vendor/golang", + Kept::Agent => ".socket/go-patches", + } + } + + /// The directory of the copy for the patch `uuid`, from the project. + fn copy_dir(self, uuid: &str) -> String { + match self { + Kept::Vendored => format!("{}/{uuid}/{MODULE}@{VERSION}", self.copies()), + Kept::Agent => format!("{}/{MODULE}@{VERSION}", self.copies()), + } + } + + /// The command of the mode. + fn scan(self) -> [&'static str; 4] { + let mode = match self { + Kept::Vendored => "vendored", + Kept::Agent => "agent", + }; + ["scan", "--mode", mode, "--yes"] + } + + /// What `socket-patch` keeps in the `.bazelignore` at the root of a + /// Bazel workspace while the project in its directory `project` (`""`: + /// the root itself, else with a `/` at its end) has a copy of the mode. + fn ignored(self, project: &str) -> String { + format!("{IGNORE_COMMENT}\n{project}{}\n", self.copies()) + } +} + +/// The Socket API on `standin` for a [`Kept`] mode: one free patch of the +/// upstream module, which changes its `lib.go` to `lib`. Vendored mode +/// downloads the whole patched module, `copy` (the upstream's names with +/// the patched file); agent mode patches the user's own copy from the +/// patch record, which replaces the record [`StandIn::api`] answers with; +/// and hosted mode is granted `socket`, as in [`grant`]. +fn grant_copy(standin: &StandIn, uuid: &str, copy: &Module, socket: &Module, lib: &[u8]) { + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + let archive = format!("/artifacts/{uuid}/upstream.zip"); + standin.serve(5, &archive, ©.zip); + let url = format!("{}{archive}", standin.origin()); + let integrity = json!({ "sha512": format!("sha512-{}", b64(&Sha512::digest(©.zip))) }); + let mut reference = granted(standin, socket); + reference["artifacts"] = json!([{ "kind": "tarball", "url": url, "integrity": integrity }]); + let patch = Patch { + purl: PURL.to_string(), + uuid: uuid.to_string(), + reference, + }; + standin.api(&[patch]); + let record = json!({ + "uuid": uuid, + "purl": PURL, + "publishedAt": "2026-01-01T00:00:00Z", + "files": { "lib.go": { + "beforeHash": compute_git_sha256_from_bytes(UPSTREAM_LIB), + "afterHash": compute_git_sha256_from_bytes(lib), + "blobContent": b64(lib), + "beforeBlobContent": b64(UPSTREAM_LIB), + }}, + "vulnerabilities": { "GHSA-test-aaaa-bbbb": { + "cves": ["CVE-2024-0001"], "summary": "s", "severity": "high", "description": "d", + }}, + "description": "fixture", + "license": "MIT", + "tier": "free", + }); + let route = format!("/v0/orgs/{ORG}/patches/view/{uuid}"); + standin.serve(1, &route, record.to_string().as_bytes()); +} + +/// What a [`Kept`] flow patches with: a stand-in that serves the upstream +/// module and grants one patch of it, and the module cache of the user. +struct Patching { + standin: StandIn, + /// The id of the patch, new for every run. + uuid: String, + /// The `lib.go` the patch makes, which holds the id. + lib: String, + upstream: Module, + /// `GOMODCACHE`: the upstream module as `go mod download` leaves it, + /// which agent mode copies. + modcache: tempfile::TempDir, +} + +impl Patching { + /// For an upstream module that ships the files `shipped` beside its + /// two. + fn new(shipped: &[(&str, &[u8])]) -> Patching { + let uuid = uuid::Uuid::new_v4().to_string(); + let lib = + format!("package upstream\n\nfunc Greeting() string {{ return \"PATCHED {uuid}\" }}\n"); + let upstream = Module::shipping(MODULE, VERSION, UPSTREAM_LIB, shipped); + let copy = Module::shipping(MODULE, VERSION, lib.as_bytes(), shipped); + let socket_path = format!("{PATCH_HOST}/gopatch/{uuid}"); + let socket = Module::shipping(&socket_path, SOCKET_VERSION, lib.as_bytes(), shipped); + let standin = StandIn::start(); + serve_module(&standin, PROXY, &upstream); + serve_module(&standin, PATCH_HOST, &socket); + grant_copy(&standin, &uuid, ©, &socket, lib.as_bytes()); + let modcache = tempfile::tempdir().expect("a module cache"); + let cached = modcache.path().join(format!("{MODULE}@{VERSION}")); + std::fs::create_dir_all(&cached).expect("the cached module"); + let own: [(&str, &[u8]); 2] = [("go.mod", GO_MOD), ("lib.go", UPSTREAM_LIB)]; + for (file, bytes) in own.iter().chain(shipped) { + std::fs::write(cached.join(file), bytes).expect("a file of the cached module"); + } + Patching { + standin, + uuid, + lib, + upstream, + modcache, + } + } + + /// `socket-patch ` in `cell`, with the module cache of the user. + fn ran(&self, cell: &Cell, args: &[&str]) -> Ran { + let modcache = self.modcache.path().to_str().expect("a UTF-8 path"); + let env = [("GOMODCACHE", modcache)]; + cell.socket_patch(&self.standin.origin(), args, &env) + } + + /// [`Patching::ran`] as a person runs it, without `--json`: the lines + /// of its stdout and of its stderr that name a `.bazelignore`. + fn person(&self, cell: &Cell, args: &[&str]) -> [Vec; 2] { + let modcache = self.modcache.path().to_str().expect("a UTF-8 path"); + let env = [("GOMODCACHE", modcache)]; + naming_the_file(cell.socket_patch_person(&self.standin.origin(), args, &env)) + } + + /// [`Patching::ran`] for a command that exits 0 with the status + /// `success`. + fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + let ran = self.ran(cell, args); + assert_eq!(ran.code, 0, "{}: {}", cell.test, ran.dump); + let status = &ran.envelope["status"]; + assert_eq!(*status, "success", "{}: {}", cell.test, ran.dump); + ran + } +} + +/// The user's `bazel run //:gazelle`, which passes. +fn gazelle(cell: &Cell) { + let ran = cell.bazel("run", &["//:gazelle"]); + assert!(ran.ok(), "{}: {}", cell.test, ran.dump()); +} + +/// The flow of a [`Kept`] mode, for a module that ships `SHIPPED_BUILD` +/// (`ships_build`) or no BUILD file: +/// +/// - (a) The unpatched build, and for a module without a BUILD file the +/// user's `bazel run //:gazelle`, which leaves the fixture as it is. +/// - (b) The command of the mode writes the copy, the one `replace` line +/// of `go.mod`, and the line of `.bazelignore` that names the directory +/// of the copies. In the agent flow the user has a `.bazelignore` whose +/// last line has no line break, and the file then ends with that line of +/// `socket-patch`, without a line break as well. +/// - (c) `bazel build` and `bazel run //:consumer` print the patched marker, +/// Bazel changed no file, and a `--lockfile_mode=error` build passes. +/// - (d) What the user does next: for a module without a BUILD file +/// `bazel run //:gazelle`, which writes nothing, and the same build; then +/// `bazel build //...`. Without the line gazelle writes a BUILD file into +/// the copy, or the copy holds the one the module ships; `go_deps` copies +/// the directory with it, and Bazel reads the file as a package that +/// cannot load rules_go. +/// - (e) The undo of the mode removes the copy, the `replace` line and the +/// line of `.bazelignore`, which leaves the user's file as it was, and +/// the build prints the unpatched marker again. +fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + let shipped: &[(&str, &[u8])] = if ships_build { + &[("BUILD.bazel", SHIPPED_BUILD)] + } else { + &[] + }; + let with = Patching::new(shipped); + let patched = format!("OUT: PATCHED {}", with.uuid); + let copy_dir = mode.copy_dir(&with.uuid); + // The public proxy is last, for the modules gazelle is built from: the + // stand-in has the module of the test, and no flow here has a Socket + // module. + let origin = with.standin.origin(); + cell.repo_env = go_env(&format!("{origin}/{PROXY},https://proxy.golang.org")); + if ships_build { + cell.write("go.sum", with.upstream.go_sum().join("\n") + "\n"); + } + + // (a) The unpatched build. The fixture's BUILD file is the one gazelle + // writes, so whatever a later gazelle run changes comes from the patch. + cell.builds_unpatched(UNPATCHED); + if !ships_build { + gazelle(&cell); + } + // The agent flow has a `.bazelignore` of the user's, whose last line + // has no line break: Bazel and gazelle have to honour the line + // `socket-patch` then ends the file with, and the undo has to leave the + // user's file as it was. + let (theirs, ignored) = match mode { + Kept::Agent => ( + "node_modules\n# mine", + mode.ignored("").trim_end().to_string(), + ), + Kept::Vendored => ("", mode.ignored("")), + }; + if !theirs.is_empty() { + cell.write(".bazelignore", theirs); + } + let ignored = [theirs, &ignored].join(if theirs.is_empty() { "" } else { "\n" }); + let before = cell.tree(); + let fixture = std::fs::read(fixture_path(FIXTURE.dir).join("common/BUILD.bazel")); + assert_eq!( + before["BUILD.bazel"], + fixture.expect("the fixture"), + "{test}" + ); + + // (b) The command of the mode: the copy, the one `replace` line, and + // the line that keeps Bazel and gazelle out of the copies. + let scan = with.run(&cell, &mode.scan()); + let event = find_event(&scan.envelope, "applied", None); + assert_eq!(event["purl"], PURL, "{test}: {}", scan.dump); + if mode == Kept::Agent { + with.run(&cell, &["apply"]); + } + let pinned = cell.tree(); + let wrote = changed(&before, &pinned); + let outside: Vec<&String> = wrote + .iter() + .filter(|f| !f.starts_with(".socket/")) + .collect(); + assert_eq!(outside, [".bazelignore", "go.mod"], "{test}: {wrote:?}"); + assert_eq!(pinned[".bazelignore"], ignored.as_bytes(), "{test}"); + let lib = &pinned[&format!("{copy_dir}/lib.go")]; + assert_eq!(*lib, with.lib.as_bytes(), "{test}"); + let go_mod = String::from_utf8(pinned["go.mod"].clone()).expect("a text file"); + let replace = format!("replace {MODULE} {VERSION} => ./{copy_dir}"); + let replaces = go_mod.lines().filter(|line| line.trim() == replace).count(); + assert_eq!(replaces, 1, "{test}: go.mod:\n{go_mod}"); + + // (c) The next build is patched, from the copy. + cell.builds_patched(&pinned, &patched); + + // (d) The user's next step: gazelle writes nothing into the copy, the + // build stays patched, and no package of the checkout is under + // `.socket`. + if !ships_build { + gazelle(&cell); + assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{test}"); + cell.builds_patched(&pinned, &patched); + } + let all = cell.bazel("build", &["//..."]); + assert!(all.ok(), "{test}: {}", all.dump()); + + // (e) The undo. An agent rollback keeps its emptied manifest. + let (undo, counted, left): (&[&str], &str, &[&str]) = match mode { + Kept::Vendored => (&["vendor", "--revert", "--yes"], "removed", &[]), + Kept::Agent => ( + &["rollback", "--yes"], + "rolledBack", + &[".socket/manifest.json"], + ), + }; + let undo = with.run(&cell, undo); + let count = &undo.envelope["summary"][counted]; + assert_eq!(*count, 1, "{test}: {}", undo.dump); + assert_eq!( + changed(&before, &cell.tree()), + left, + "{test}: {}", + undo.dump + ); + cell.builds(UNPATCHED); + assert_eq!(changed(&before, &cell.tree()), left, "{test}"); + + let next = if ships_build { + "`bazel build //...` passed" + } else { + "it built that again after `bazel run //:gazelle`, and `bazel build //...` passed" + }; + println!( + "{test}: Bazel {release} built {patched:?} from {copy_dir} after the command of the mode; \ + {next}; the undo left {left:?} and the {UNPATCHED:?} build; {:?}", + started.elapsed() + ); +} + +/// `scan --mode vendored` for a module without a BUILD file. The command +/// writes the copy, the `replace` and the `.bazelignore` line. The build is +/// patched, and stays patched after the user's `bazel run //:gazelle`, +/// which writes nothing into the copy; `bazel build //...` passes; and +/// `vendor --revert` leaves the checkout as it was before the command. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_go_deps() { + kept_copy_flow("go::vendored_go_deps", Kept::Vendored, false); +} + +/// Agent mode (`scan --mode agent`, then `apply`) for a module without a +/// BUILD file. The commands write the copy, the `replace` and the +/// `.bazelignore` line, here at the end of a file of the user's whose last +/// line has no line break. The build is patched, and stays patched after +/// the user's `bazel run //:gazelle`, which writes nothing into the copy; +/// `bazel build //...` passes; and `rollback` leaves the checkout as it was +/// before, that file included, but for the emptied `.socket/manifest.json`. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn agent_go_deps() { + kept_copy_flow("go::agent_go_deps", Kept::Agent, false); +} + +/// `scan --mode vendored` for a module that ships a BUILD file of its own. +/// The command writes the copy, the `replace` and the `.bazelignore` line. +/// The build is patched, `bazel build //...` passes although the copy holds +/// that BUILD file, and `vendor --revert` leaves the checkout as it was +/// before the command. This test runs no gazelle. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_go_deps_module_with_a_build_file() { + let test = "go::vendored_go_deps_module_with_a_build_file"; + kept_copy_flow(test, Kept::Vendored, true); +} + +/// Without a Bazel: the Go project of the fixture in a checkout of its +/// own, in the directory `project` of it (`""`: the root, else with a `/` +/// at its end), with the file `marks` at the root, which makes the +/// checkout a Bazel workspace when it is one of Bazel's names. +fn checkout(project: &str, marks: &str) -> Cell { + let cell = cell_without_bazel("9.3.2"); + for file in ["go.mod", "go.sum"] { + let bytes = std::fs::read(fixture_path(FIXTURE.dir).join("common").join(file)); + cell.write(&format!("{project}{file}"), bytes.expect("a fixture file")); + } + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + cell.write(marks, ""); + cell +} + +/// Without a Bazel: in a Bazel workspace the `.bazelignore` line follows +/// the directory of the copies, in vendored mode. A second run leaves one +/// pair. What an earlier release left after a gazelle run, a copy without +/// its line and with a BUILD file in it, is put right by the next run, which +/// makes the copy anew, but not by a dry run. A rollback that keeps the +/// copy keeps the line, since the files of the copy are still in the +/// workspace. The revert takes the pair, and the file it made, away, and +/// its dry run nothing. +#[test] +fn a_vendored_copy_has_its_bazelignore_line_while_it_is_on_disk() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + let (mode, before) = (Kept::Vendored, cell.tree()); + for _ in 0..2 { + with.run(&cell, &mode.scan()); + assert_eq!(cell.tree()[".bazelignore"], mode.ignored("").as_bytes()); + } + + let stray = format!("{}/BUILD.bazel", mode.copy_dir(&with.uuid)); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + cell.write(&stray, "# what gazelle wrote\n"); + with.run(&cell, &["scan", "--mode", "vendored", "--yes", "--dry-run"]); + assert!(!cell.tree().contains_key(".bazelignore")); + with.run(&cell, &mode.scan()); + let tree = cell.tree(); + assert_eq!(tree[".bazelignore"], mode.ignored("").as_bytes()); + assert!(!tree.contains_key(&stray)); + + // `repair` brings a lost copy back, and its line with it. + let lib = format!("{}/lib.go", mode.copy_dir(&with.uuid)); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + std::fs::remove_dir_all(cell.path(mode.copies())).expect("remove the copies"); + with.run(&cell, &["repair"]); + let tree = cell.tree(); + assert_eq!(tree[&lib], with.lib.as_bytes()); + assert_eq!(tree[".bazelignore"], mode.ignored("").as_bytes()); + + with.run(&cell, &["rollback", "--yes", "--preserve-state"]); + let kept = cell.tree(); + assert_eq!(kept["go.mod"], before["go.mod"]); + assert!(kept.contains_key(&lib)); + assert_eq!(kept[".bazelignore"], mode.ignored("").as_bytes()); + + with.run(&cell, &["vendor", "--revert", "--yes", "--dry-run"]); + assert_eq!(changed(&kept, &cell.tree()), NOTHING); + with.run(&cell, &["vendor", "--revert", "--yes"]); + assert_eq!(changed(&before, &cell.tree()), NOTHING); +} + +/// Without a Bazel: a dry run of any command writes nothing, also where +/// the run itself would write the file: a project that an earlier release +/// patched has a copy and no line for it. `repair` comes again for a copy +/// it would download anew, which is where its own run ends at the file. +#[test] +fn a_dry_run_leaves_a_copy_without_its_bazelignore_line() { + let commands: [&[&str]; 10] = [ + &["scan", "--yes"], + &["scan", "--mode", "hosted", "--yes"], + &["get", PURL, "--yes"], + &["apply"], + &["vendor", "--yes"], + &["vendor", "--revert", "--yes"], + &["rollback", "--yes"], + &["rollback", "--yes", "--preserve-state"], + &["remove", PURL, "--yes"], + &["repair"], + ]; + for mode in [Kept::Vendored, Kept::Agent] { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &mode.scan()); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + let dry = |command: &[&str]| { + let left = cell.tree(); + let ran = with.ran(&cell, &[command, &["--dry-run"]].concat()); + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(changed(&left, &cell.tree()), NOTHING, "{}", ran.dump); + ran + }; + dry(&mode.scan()); + commands.iter().for_each(|command| drop(dry(command))); + if mode == Kept::Vendored { + let lib = format!("{}/lib.go", mode.copy_dir(&with.uuid)); + std::fs::remove_file(cell.path(&lib)).expect("remove a file of the copy"); + let repair = dry(&["repair"]); + let event = find_event(&repair.envelope, "verified", None); + assert_eq!(event["details"]["wouldRedownload"], true, "{}", repair.dump); + } + } +} + +/// Without a Bazel: two projects under one Bazel root share its +/// `.bazelignore`, and each run holds the lock of its own project only. A +/// scan in each, both started at the same moment, leaves the pair of both, +/// round after round. +#[test] +fn two_projects_patched_at_once_both_get_their_bazelignore_line() { + let (cell, with) = (checkout("a/", "MODULE.bazel"), Patching::new(&[])); + for file in ["go.mod", "go.sum"] { + cell.write(&format!("b/{file}"), &cell.tree()[&format!("a/{file}")]); + } + let (a, b) = (Kept::Vendored.ignored("a/"), Kept::Vendored.ignored("b/")); + for round in 0..8 { + std::thread::scope(|runs| { + for project in ["a", "b"] { + let (cell, with) = (&cell, &with); + let scan = ["scan", "--mode", "vendored", "--yes", "--cwd", project]; + runs.spawn(move || drop(with.run(cell, &scan))); + } + }); + let file = String::from_utf8_lossy(&cell.tree()[".bazelignore"]).into_owned(); + let either = [format!("{a}{b}"), format!("{b}{a}")]; + assert!(either.contains(&file), "round {round}: {file:?}"); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + } +} + +/// Without a Bazel: a hosted scan that takes a vendored module over removes +/// the copy, and the line with it. +#[test] +fn a_hosted_takeover_of_a_vendored_copy_takes_its_line_away() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &Kept::Vendored.scan()); + assert!(cell.tree().contains_key(".bazelignore")); + with.run(&cell, &["scan", "--mode", "hosted", "--yes"]); + let tree = cell.tree(); + let go_mod = String::from_utf8_lossy(&tree["go.mod"]); + let hosted = format!("=> {PATCH_HOST}/gopatch/{} {SOCKET_VERSION}", with.uuid); + assert!(go_mod.contains(&hosted), "{go_mod}"); + let left: Vec<&String> = tree + .keys() + .filter(|f| f.starts_with(".socket/vendor/")) + .collect(); + assert_eq!(left, NOTHING); + assert!(!tree.contains_key(".bazelignore")); +} + +/// Without a Bazel: `vendor` in a hosted project ejects every hosted pin or +/// none. Here the eject vendors the Go module and then fails on a second +/// pin, whose patch the service does not hand out, so it is rolled back: the +/// project is hosted as before, file for file, and no `.bazelignore` names +/// the directory of a copy that is gone again. The group commit is switched +/// off, as it is for an eject whose restore it cannot hold (a Gradle pin +/// beside the Go one), so that the vendored module is on disk when the +/// second pin fails. +#[test] +fn an_eject_that_is_rolled_back_leaves_no_bazelignore_line() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &["scan", "--mode", "hosted", "--yes"]); + let (origin, other) = (with.standin.origin(), uuid::Uuid::new_v4().to_string()); + let pinned = cell.tree(); + let text = |file: &str| String::from_utf8_lossy(&pinned[file]).into_owned(); + let socket = format!("{PATCH_HOST}/gopatch/{other} {SOCKET_VERSION}"); + cell.write( + "go.mod", + format!( + "{}\nrequire example.com/other {VERSION}\n\nreplace example.com/other {VERSION} => {socket}\n", + text("go.mod") + ), + ); + // Any well-formed sums: nothing fetches these modules. + let (zip_h1, mod_h1) = (&with.upstream.zip_h1, &with.upstream.mod_h1); + let sums_of = |path: &str, version: &str| { + format!("{path} {version} {zip_h1}\n{path} {version}/go.mod {mod_h1}") + }; + let socket_sums = sums_of(&format!("{PATCH_HOST}/gopatch/{other}"), SOCKET_VERSION); + cell.write("go.sum", text("go.sum") + &socket_sums + "\n"); + let record = json!({ + "uuid": other, "purl": format!("pkg:golang/example.com/other@{VERSION}"), + "publishedAt": "2026-01-01T00:00:00Z", "files": {}, "vulnerabilities": {}, + "description": "fixture", "license": "MIT", "tier": "free", + }); + let view = format!("/v0/orgs/{ORG}/patches/view/{other}"); + with.standin.serve(1, &view, record.to_string().as_bytes()); + for (module, sums) in [ + (MODULE, with.upstream.go_sum().join("\n")), + ("example.com/other", sums_of("example.com/other", VERSION)), + ] { + let lookup = format!("1\n{sums}\n\ngo.sum database tree\n1\nAAAA\n"); + let route = format!("/{SUMDB}/lookup/{module}@{VERSION}"); + with.standin.serve(5, &route, lookup.as_bytes()); + } + let hosted = cell.tree(); + let env = [ + ("SOCKET_GOSUMDB_URL", format!("{origin}/{SUMDB}")), + ("SOCKET_PATCH_SWITCH_OFF", "group_commit".to_string()), + ]; + let env = env.each_ref().map(|(name, value)| (*name, value.as_str())); + let eject = cell.socket_patch(&origin, &["vendor", "--yes"], &env); + assert_eq!(eject.code, 1, "{}", eject.dump); + let warnings = eject.envelope["warnings"].as_array(); + let rolled_back = |w: &serde_json::Value| w["code"] == "eject_rolled_back"; + assert!( + warnings.is_some_and(|w| w.iter().any(rolled_back)), + "{}", + eject.dump + ); + assert_eq!(changed(&hosted, &cell.tree()), NOTHING, "{}", eject.dump); +} + +/// Without a Bazel: the same in agent mode, where `apply` is what finds a +/// copy without its line, and `rollback` leaves its emptied manifest. A dry +/// run of either changes nothing. +#[test] +fn an_agent_copy_has_its_bazelignore_line_while_it_is_on_disk() { + let (cell, with, mode) = (checkout("", "WORKSPACE"), Patching::new(&[]), Kept::Agent); + let before = cell.tree(); + with.run(&cell, &mode.scan()); + assert_eq!(cell.tree()[".bazelignore"], mode.ignored("").as_bytes()); + + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + with.run(&cell, &["apply", "--dry-run"]); + assert!(!cell.tree().contains_key(".bazelignore")); + with.run(&cell, &["apply"]); + let patched = cell.tree(); + assert_eq!(patched[".bazelignore"], mode.ignored("").as_bytes()); + + with.run(&cell, &["rollback", "--yes", "--dry-run"]); + assert_eq!(changed(&patched, &cell.tree()), NOTHING); + with.run(&cell, &["rollback", "--yes"]); + assert_eq!(changed(&before, &cell.tree()), [".socket/manifest.json"]); +} + +/// Without a Bazel: Bazel reads `.bazelignore` at the root of the workspace +/// only, so a project below the root gets its line there, with its path +/// from the root, after the lines the user has, in their line breaks. A +/// file whose last line has no line break still has none at its end. The +/// revert leaves the file of before, byte for byte, a last byte that is a +/// carriage return on its own included. +#[test] +fn a_project_below_the_bazel_root_is_named_from_the_root() { + let mode = Kept::Vendored; + let pair = mode.ignored("svc/go/"); + let files = [ + ("node_modules\n", pair.clone()), + ( + "node_modules\r\nthird_party\r\n", + pair.replace('\n', "\r\n"), + ), + ( + "node_modules\r\nthird_party", + format!("\r\n{}", pair.trim_end().replace('\n', "\r\n")), + ), + ("node_modules\r", format!("\n{}", pair.trim_end())), + ]; + for (old, added) in files { + let (cell, with) = (checkout("svc/go/", "WORKSPACE.bazel"), Patching::new(&[])); + cell.write(".bazelignore", old); + with.run(&cell, &[&mode.scan()[..], &["--cwd", "svc/go"]].concat()); + let tree = cell.tree(); + let file = String::from_utf8_lossy(&tree[".bazelignore"]); + assert_eq!(file, format!("{old}{added}")); + assert!(!tree.contains_key("svc/go/.bazelignore")); + with.run(&cell, &["vendor", "--revert", "--yes", "--cwd", "svc/go"]); + assert_eq!(cell.tree()[".bazelignore"], old.as_bytes()); + } +} + +/// Without a Bazel: a project that is in no Bazel workspace gets what it +/// got before there was a line to write: every file the run writes in a +/// workspace, byte for byte, and no `.bazelignore`, the one file the two +/// checkouts then differ in. A directory named like a workspace file marks +/// no workspace. +#[test] +fn a_project_in_no_bazel_workspace_gets_no_bazelignore() { + for mode in [Kept::Vendored, Kept::Agent] { + let with = Patching::new(&[]); + let (plain, marked) = ( + checkout("", "WORKSPACE/README"), + checkout("", "MODULE.bazel"), + ); + let trees = [&plain, &marked].map(|cell| { + let before = cell.tree(); + let scan = with.run(cell, &mode.scan()); + let warnings = scan.envelope["warnings"].as_array(); + assert!(warnings.is_none_or(Vec::is_empty), "{}", scan.dump); + let after = cell.tree(); + (changed(&before, &after), after) + }); + let [(plain_wrote, plain), (_, marked)] = trees; + assert!( + plain_wrote.contains(&"go.mod".to_string()), + "{plain_wrote:?}" + ); + assert!(!plain.contains_key(".bazelignore")); + // Apart from the file that marks each checkout, and the marker of a + // vendored copy, which holds the second it was written in. + let apart = |file: &String| { + ["WORKSPACE/README", "MODULE.bazel"].contains(&file.as_str()) + || file.ends_with("/socket-patch.vendor.json") + }; + let mut differ = changed(&plain, &marked); + differ.retain(|file| !apart(file)); + assert_eq!(differ, [".bazelignore"]); + } +} + +/// Without a Bazel: a project that is in no git checkout looks no further +/// than its own directory. Below a Bazel root it is patched as anywhere +/// else, and gets no line and no warning: nothing above it is read, not +/// the `.bazelignore` of that root either, here a directory that no read +/// gets through. With a workspace file of its own it has its line in its +/// own directory. `GIT_CEILING_DIRECTORIES` ends the walk at the workspace +/// copy, so that a checkout above the temp directory changes nothing. +#[test] +fn a_project_in_no_git_checkout_looks_at_its_own_directory_only() { + for mode in [Kept::Vendored, Kept::Agent] { + let (cell, with) = (checkout("svc/", "MODULE.bazel"), Patching::new(&[])); + std::fs::remove_dir_all(cell.path(".git")).expect("remove .git"); + cell.write(".bazelignore/README", "a directory in the file's place"); + let ceiling = cell.path(".."); + let env = [ + ("GOMODCACHE", with.modcache.path().to_str().expect("UTF-8")), + ("GIT_CEILING_DIRECTORIES", ceiling.to_str().expect("UTF-8")), + ]; + let scan = [&mode.scan()[..], &["--cwd", "svc"]].concat(); + let before = cell.tree(); + for own_root in [false, true] { + if own_root { + cell.write("svc/WORKSPACE", ""); + } + let ran = cell.socket_patch(&with.standin.origin(), &scan, &env); + assert_eq!(ran.code, 0, "{}", ran.dump); + assert_eq!(not_updated(&ran), NOTHING, "{}", ran.dump); + let wrote = changed(&before, &cell.tree()); + let ignores: Vec<_> = wrote + .iter() + .filter(|f| f.contains(".bazelignore")) + .collect(); + let own: &[&str] = if own_root { &["svc/.bazelignore"] } else { &[] }; + assert_eq!(ignores, own, "{}", ran.dump); + assert!(wrote.contains(&"svc/go.mod".to_string()), "{wrote:?}"); + } + let file = String::from_utf8_lossy(&cell.tree()["svc/.bazelignore"]).into_owned(); + assert_eq!(file, mode.ignored("")); + } +} + +/// The `bazelignore_not_updated` warnings of a run. +fn not_updated(ran: &Ran) -> Vec<&str> { + let warnings = ran.envelope["warnings"].as_array(); + let ours = |w: &&serde_json::Value| w["code"] == "bazelignore_not_updated"; + let details = warnings.into_iter().flatten().filter(ours); + details + .map(|w| w["detail"].as_str().expect("a detail")) + .collect() +} + +/// Make the `.bazelignore` of `cell` read-only. `false`: this user writes a +/// read-only file all the same (root). +fn read_only(cell: &Cell) -> bool { + let file = cell.path(".bazelignore"); + let mut bits = std::fs::metadata(&file).expect("the file").permissions(); + bits.set_readonly(true); + std::fs::set_permissions(&file, bits).expect("make the file read-only"); + std::fs::OpenOptions::new() + .append(true) + .open(&file) + .is_err() +} + +/// Without a Bazel: a `.bazelignore` that socket-patch cannot write fails +/// no command: a directory in its place, and a read-only file. Each +/// command that ends with the copy on disk warns once, with the line +/// the user has to add, the patch stands, and the file stays as it is: a +/// scan whose prune pass comes to the file a second time included, in its +/// envelope and on the stderr a person reads. The undo, which leaves +/// nothing to add, warns of nothing. +#[test] +fn a_bazelignore_that_cannot_be_written_is_one_warning() { + for (mode, obstacle) in [Kept::Vendored, Kept::Agent] + .into_iter() + .flat_map(|mode| ["a directory", "read-only"].map(|obstacle| (mode, obstacle))) + { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + if obstacle == "a directory" { + cell.write(".bazelignore/README", "a directory in the file's place"); + } else { + cell.write(".bazelignore", "node_modules\n"); + if !read_only(&cell) { + continue; + } + } + let before = cell.tree(); + let prune = ["scan", "--mode", "vendored", "--yes", "--prune"]; + let (keeping, undo): (&[&[&str]], &[&str]) = match mode { + Kept::Vendored => ( + &[ + &["repair"], + &["rollback", "--yes", "--preserve-state"], + &prune, + ], + &["vendor", "--revert", "--yes"], + ), + Kept::Agent => (&[&["apply"]], &["rollback", "--yes"]), + }; + let scan = mode.scan(); + // A copy no ledger entry owns, which the prune pass sweeps: the scan + // comes to the file a second time after that, and warns once. + let orphan = format!("{}/{}", mode.copies(), uuid::Uuid::new_v4()); + for command in [&scan[..]].iter().chain(keeping) { + if *command == prune { + cell.write( + &format!("{orphan}/example.com/orphan@v1.0.0/go.mod"), + "module x\n", + ); + } + let ran = with.run(&cell, command); + assert!(!cell.path(&orphan).exists(), "{obstacle}: {}", ran.dump); + let [detail] = not_updated(&ran)[..] else { + panic!("{obstacle}: {}", ran.dump); + }; + let line = format!("add `{}` to it", mode.copies()); + assert!(detail.contains(&line), "{obstacle}: {detail}"); + } + // The same scan as a person runs it: the pass that sweeps the copy + // comes to the file after the scan has warned, and says no more. + if mode == Kept::Vendored { + let swept = format!("{orphan}/example.com/orphan@v1.0.0/go.mod"); + cell.write(&swept, "module x\n"); + let [_, stderr] = with.person(&cell, &prune); + assert!(!cell.path(&swept).exists(), "{obstacle}"); + assert_eq!(stderr.len(), 1, "{obstacle}: {stderr:?}"); + } + let tree = cell.tree(); + let lib = format!("{}/lib.go", mode.copy_dir(&with.uuid)); + assert!(tree.contains_key(&lib), "{obstacle}: {:?}", tree.keys()); + let ignore = |tree: &Tree| -> Vec<(String, Vec)> { + let ours = tree + .iter() + .filter(|(file, _)| file.starts_with(".bazelignore")); + ours.map(|(file, bytes)| (file.clone(), bytes.clone())) + .collect() + }; + assert_eq!(ignore(&tree), ignore(&before), "{obstacle}"); + let ran = with.run(&cell, undo); + assert_eq!(not_updated(&ran), NOTHING, "{obstacle}: {}", ran.dump); + assert_eq!(ignore(&cell.tree()), ignore(&before), "{obstacle}"); + } +} + +/// Without a Bazel: a read-only `.bazelignore` that holds the pair of a +/// copy the undo removes is neither replaced nor deleted: the undo stands, +/// and warns once that the two lines can go. +#[test] +fn a_read_only_bazelignore_keeps_the_pair_of_a_copy_that_is_gone() { + for (mode, old) in [Kept::Vendored, Kept::Agent] + .into_iter() + .flat_map(|mode| ["", "node_modules\n"].map(|old| (mode, old))) + { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + cell.write(".bazelignore", old); + with.run(&cell, &mode.scan()); + let patched = cell.tree(); + assert_eq!( + patched[".bazelignore"], + format!("{old}{}", mode.ignored("")).as_bytes() + ); + if !read_only(&cell) { + return; + } + let undo: &[&str] = match mode { + Kept::Vendored => &["vendor", "--revert", "--yes"], + Kept::Agent => &["rollback", "--yes"], + }; + let ran = with.run(&cell, undo); + let [detail] = not_updated(&ran)[..] else { + panic!("{}", ran.dump); + }; + assert!(detail.contains("can be deleted"), "{detail}"); + let tree = cell.tree(); + assert_eq!(tree[".bazelignore"], patched[".bazelignore"]); + let copies: Vec<&String> = tree + .keys() + .filter(|f| f.starts_with(mode.copies())) + .collect(); + assert_eq!(copies, NOTHING, "{}", ran.dump); + let bits = std::fs::metadata(cell.path(".bazelignore")).expect("the file"); + assert!(bits.permissions().readonly()); + } +} + +/// Without a Bazel: the user's "no". With the path line commented out +/// under socket-patch's comment line, no command adds a line for that +/// directory, warns about it, or touches the two lines, whether the copy +/// is written, repaired, unwired or removed. The pair of the other +/// directory comes with that directory and goes with it. +#[test] +fn a_commented_out_bazelignore_line_stays_declined() { + for mode in [Kept::Vendored, Kept::Agent] { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &mode.scan()); + let declined = mode.ignored("").replace("\n.socket", "\n# .socket"); + assert_ne!(declined, mode.ignored("")); + cell.write(".bazelignore", &declined); + let (other, scan) = match mode { + Kept::Vendored => (Kept::Agent, mode.scan()), + Kept::Agent => (Kept::Vendored, mode.scan()), + }; + let unrelated = format!("{}/README", other.copies()); + cell.write(&unrelated, "a directory of the other mode"); + let commands: &[&[&str]] = match mode { + Kept::Vendored => &[ + &scan, + &["repair"], + &["rollback", "--yes", "--preserve-state"], + &scan, + &["vendor", "--revert", "--yes"], + ], + Kept::Agent => &[&scan, &["apply"], &["rollback", "--yes"]], + }; + for (n, command) in commands.iter().enumerate() { + if n + 1 == commands.len() { + let _ = std::fs::remove_dir_all(cell.path(other.copies())); + } + let ran = with.run(&cell, command); + assert_eq!(not_updated(&ran), NOTHING, "{}", ran.dump); + let mut file = declined.clone(); + if cell.path(other.copies()).is_dir() { + file += &other.ignored(""); + } + let tree = cell.tree(); + assert_eq!( + String::from_utf8_lossy(&tree[".bazelignore"]), + file, + "{command:?}" + ); + } + let tree = cell.tree(); + assert_eq!(tree[".bazelignore"], declined.as_bytes()); + let copies: Vec<&String> = tree + .keys() + .filter(|f| f.starts_with(mode.copies())) + .collect(); + assert_eq!(copies, NOTHING); + } +} + +/// Without a Bazel: `scan --prune` reverts a vendored module that the +/// project no longer uses: its lines are gone from `go.mod` and `go.sum`, +/// and the module from the module cache. That removes the last copy, and +/// the line goes with it. +#[test] +fn a_prune_that_removes_the_last_copy_takes_its_line_away() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &Kept::Vendored.scan()); + let patched = cell.tree(); + assert!(patched.contains_key(".bazelignore")); + let go_mod = String::from_utf8_lossy(&patched["go.mod"]); + let unused: Vec<&str> = go_mod + .lines() + .filter(|line| !line.starts_with("require ") && !line.starts_with("replace ")) + .collect(); + assert_eq!(unused.len() + 2, go_mod.lines().count(), "{go_mod}"); + cell.write("go.mod", unused.join("\n") + "\n"); + cell.write("go.sum", ""); + let empty = with.modcache.path().join("empty"); + let env = [("GOMODCACHE", empty.to_str().expect("a UTF-8 path"))]; + let prune = ["scan", "--mode", "vendored", "--yes", "--prune"]; + let prune = cell.socket_patch(&with.standin.origin(), &prune, &env); + assert_eq!(prune.code, 0, "{}", prune.dump); + let tree = cell.tree(); + let copies: Vec<&String> = tree + .keys() + .filter(|f| f.starts_with(".socket/vendor/")) + .collect(); + assert_eq!(copies, NOTHING, "{}", prune.dump); + assert!(!tree.contains_key(".bazelignore"), "{}", prune.dump); +} + +/// Without a Bazel: a command whose `--ecosystems` leaves Go out adds no +/// line for a Go copy; the same command without the option leaves the file +/// in line with the copy. `remove` of the Go patch and `vendor --revert` +/// remove the Go copy whatever the option says, and then its pair goes +/// with it, out of a file that keeps the user's line. +#[test] +fn a_run_that_leaves_go_out_adds_no_line_and_takes_the_pair_of_a_copy_it_removed_away() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &Kept::Vendored.scan()); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + for command in [&["repair"][..], &["scan", "--mode", "vendored", "--yes"]] { + with.run(&cell, &[command, &["--ecosystems", "npm"]].concat()); + assert!(!cell.tree().contains_key(".bazelignore"), "{command:?}"); + } + with.run(&cell, &["repair"]); + let pair = Kept::Vendored.ignored(""); + assert_eq!(cell.tree()[".bazelignore"], pair.as_bytes()); + + let undos: [&[&str]; 2] = [&["remove", PURL, "--yes"], &["vendor", "--revert", "--yes"]]; + for undo in undos { + with.run(&cell, &Kept::Vendored.scan()); + cell.write(".bazelignore", format!("node_modules\n{pair}")); + let ran = with.run(&cell, &[undo, &["--ecosystems", "npm"]].concat()); + let tree = cell.tree(); + let copies: Vec<&String> = tree + .keys() + .filter(|f| f.starts_with(Kept::Vendored.copies())) + .collect(); + assert_eq!(copies, NOTHING, "{}", ran.dump); + assert_eq!(tree[".bazelignore"], b"node_modules\n", "{}", ran.dump); + assert_eq!(not_updated(&ran), NOTHING, "{}", ran.dump); + } +} + +/// Without a Bazel: a scan that `socket.yml` lets write nothing +/// (`patches.enabled: false`: report only) leaves the file alone too, in +/// every mode, with a copy on disk that has no line. That is why the +/// hosted scan comes to the file only when it took the apply lock, which +/// it takes only when it has something to write. +#[test] +fn a_scan_that_may_write_nothing_leaves_the_file_alone() { + let scans: [&[&str]; 6] = [ + &["scan", "--yes"], + &["scan", "--mode", "hosted", "--yes"], + &["scan", "--mode", "vendored", "--yes"], + &["scan", "--mode", "agent", "--yes"], + &["scan", "--mode", "vendored", "--yes", "--prune"], + &["scan", "--sync", "--yes"], + ]; + for mode in [Kept::Vendored, Kept::Agent] { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + with.run(&cell, &mode.scan()); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + cell.write("socket.yml", "version: 2\npatches:\n enabled: false\n"); + let before = cell.tree(); + for scan in scans { + let ran = with.run(&cell, scan); + let warnings = ran.envelope["warnings"].as_array(); + let disabled = |w: &serde_json::Value| w["code"] == "patches_disabled"; + assert!( + warnings.is_some_and(|w| w.iter().any(disabled)), + "{}", + ran.dump + ); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{}", ran.dump); + } + } +} + +/// The lines of a run's stdout and of its stderr that name a `.bazelignore`. +fn naming_the_file(streams: [String; 2]) -> [Vec; 2] { + streams.map(|text| { + let named = text.lines().filter(|line| line.contains(".bazelignore")); + named.map(str::to_string).collect() + }) +} + +/// What a person is told of a `.bazelignore` whose lines changed. +const UPDATED: &str = + ".bazelignore: the lines that keep patched Go module copies under .socket out of \ + Bazel's packages"; + +/// Without a Bazel: what a person reads. A run that changes the file says +/// so on stdout, in words that hold for lines that came and for lines that +/// went; one that deletes the file says that; and one that cannot write it +/// warns on stderr. +#[test] +fn a_person_is_told_that_the_file_changed() { + let (cell, with) = (checkout("", "MODULE.bazel"), Patching::new(&[])); + let mode = Kept::Agent; + with.run(&cell, &mode.scan()); + let person = |args: &[&str]| with.person(&cell, args); + let told = + |line: &String, start: &str, end: &str| line.starts_with(start) && line.ends_with(end); + assert_eq!(person(&["apply"]), [NOTHING, NOTHING], "nothing changed"); + + // A pair that came. + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + let [stdout, stderr] = person(&["apply"]); + assert!( + matches!(&stdout[..], [line] if told(line, "Updated ", UPDATED)), + "{stdout:?}" + ); + assert_eq!(stderr, NOTHING); + + // A pair that went, out of a file that keeps the user's line, and then + // out of one that held nothing else. + cell.write( + ".bazelignore", + format!("node_modules\n{}", mode.ignored("")), + ); + let [stdout, stderr] = person(&["rollback", "--yes"]); + assert!( + matches!(&stdout[..], [line] if told(line, "Updated ", UPDATED)), + "{stdout:?}" + ); + assert_eq!(stderr, NOTHING); + assert_eq!(cell.tree()[".bazelignore"], b"node_modules\n"); + with.run(&cell, &mode.scan()); + cell.write(".bazelignore", mode.ignored("")); + let [stdout, stderr] = person(&["rollback", "--yes"]); + let gone = ".bazelignore: no patched Go module copy is left under .socket"; + assert!( + matches!(&stdout[..], [line] if told(line, "Removed ", gone)), + "{stdout:?}" + ); + assert_eq!(stderr, NOTHING); + assert!(!cell.tree().contains_key(".bazelignore")); + + // A file that cannot be written. + with.run(&cell, &mode.scan()); + std::fs::remove_file(cell.path(".bazelignore")).expect("remove the file"); + cell.write(".bazelignore/README", "a directory in the file's place"); + let [stdout, stderr] = person(&["apply"]); + assert_eq!(stdout, NOTHING); + let warned = |line: &String| line.starts_with("Warning: could not update "); + assert!(matches!(&stderr[..], [line] if warned(line)), "{stderr:?}"); +} + +/// Without a Bazel: `--manifest-path` can name the manifest of another +/// project. The agent copies are those of `--cwd` and the vendored ones +/// those of the manifest's project, so one command brings the file of each +/// project's Bazel root in line: one file when both are under one root, +/// which a person is told of once, and two when the manifest's project is +/// in another checkout with a Bazel root of its own. +#[test] +fn a_manifest_in_another_project_brings_the_file_of_both_projects_in_line() { + for (other, files) in [("b/", 1), ("other/c/", 2)] { + let cell = checkout("a/", "MODULE.bazel"); + cell.write("a/.socket/go-patches/README", "the agent copies of `a`"); + cell.write( + &format!("{other}.socket/manifest.json"), + "{\"patches\":{}}\n", + ); + cell.write( + &format!("{other}.socket/vendor/golang/README"), + "the vendored copies of the other project", + ); + if files == 2 { + cell.write("other/.git/HEAD", "ref: refs/heads/main\n"); + cell.write("other/WORKSPACE", ""); + } + let manifest = format!("../{other}.socket/manifest.json"); + let apply = [ + "apply", + "--offline", + "--cwd", + "a", + "--manifest-path", + &manifest, + ]; + // No API: the run is offline. + let ran = cell.socket_patch_person("http://127.0.0.1:9", &apply, &[]); + let [stdout, stderr] = naming_the_file(ran); + assert_eq!(stderr, NOTHING); + assert_eq!(stdout.len(), files, "{stdout:?}"); + assert!( + stdout.iter().all(|line| line.starts_with("Updated ")), + "{stdout:?}" + ); + let tree = cell.tree(); + let (agent, vendored) = (Kept::Agent.ignored("a/"), Kept::Vendored); + let (root, others) = match files { + 1 => (format!("{agent}{}", vendored.ignored("b/")), None), + _ => (agent, Some(vendored.ignored("c/"))), + }; + assert_eq!(String::from_utf8_lossy(&tree[".bazelignore"]), root); + let theirs = tree.get("other/.bazelignore"); + assert_eq!( + theirs.map(|file| String::from_utf8_lossy(file).into_owned()), + others + ); + } +} + /// Without a Bazel: the fixture's directories are those of its table, and /// its `go.sum` pins the module the test serves, which holds the `h1:` /// arithmetic here to sums that `go` computed. 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 50c9e1ad4..7ac2c500f 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -764,6 +764,11 @@ impl Cell { std::fs::write(&path, bytes).unwrap_or_else(|e| panic!("write {}: {e}", path.display())); } + /// The path of `rel` in the workspace copy. + pub fn path(&self, rel: &str) -> PathBuf { + self.scratch.workspace.join(rel) + } + /// Every regular file of the workspace copy. Bazel's `bazel-*` links /// into the output base are links, so they are not followed. pub fn tree(&self) -> Tree { @@ -898,18 +903,18 @@ impl Cell { assert_eq!(changed(before, &self.tree()), NOTHING, "{test}"); } - /// `socket-patch --json` in the workspace copy, as a user in - /// that directory runs it, against the Socket API at `api`. Its home - /// and temp directory are the cell's, and every proxy is a closed port, - /// so it reaches no host but loopback. - pub fn socket_patch(&self, api: &str, args: &[&str], env: &[(&str, &str)]) -> Ran { + /// `socket-patch ` in the workspace copy, as a user in that + /// directory runs it, against the Socket API at `api`. Its home and + /// temp directory are the cell's, and every proxy is a closed port, so + /// it reaches no host but loopback. + fn socket_patch_command(&self, api: &str, args: &[&str], env: &[(&str, &str)]) -> Command { let mut cmd = match &self.socket_bin { Some(bin) => hermetic::command(bin), None => hermetic::binary_command(), }; cmd.current_dir(&self.scratch.workspace) .args(args) - .args(["--json", "--api-url", api, "--org", ORG]) + .args(["--api-url", api, "--org", ORG]) .args(["--api-token", "fake-token"]); hermetic::scrub_crawler_inputs(&mut cmd); cmd.env("HOME", &self.scratch.home) @@ -921,6 +926,14 @@ impl Cell { cmd.env("NO_PROXY", LOOPBACK.join(",")); cmd.env("no_proxy", LOOPBACK.join(",")); cmd.envs(env.iter().copied()); + cmd + } + + /// [`Cell::socket_patch_command`] with `--json`: the run and its + /// envelope. + pub fn socket_patch(&self, api: &str, args: &[&str], env: &[(&str, &str)]) -> Ran { + let mut cmd = self.socket_patch_command(api, args, env); + cmd.arg("--json"); let line = format!("{cmd:?}"); let out = cmd.output().unwrap_or_else(|e| panic!("spawn {line}: {e}")); let stdout = String::from_utf8_lossy(&out.stdout); @@ -936,6 +949,19 @@ impl Cell { } } + /// [`Cell::socket_patch_command`] as a person runs it, without + /// `--json`: what it printed on stdout and on stderr. + pub fn socket_patch_person( + &self, + api: &str, + args: &[&str], + env: &[(&str, &str)], + ) -> [String; 2] { + let mut cmd = self.socket_patch_command(api, args, env); + let out = cmd.output().expect("spawn socket-patch"); + [out.stdout, out.stderr].map(|stream| String::from_utf8_lossy(&stream).into_owned()) + } + /// `bazel shutdown`, when the pid file of a server is there. No command /// options: the startup options are what address the server. fn shutdown(&self) -> Result<(), String> { @@ -999,8 +1025,9 @@ fn a_release_builds_the_era_whose_range_holds_it() { } /// A cell no Bazel stands behind, for what is decided without one: the -/// command line of the release `release`. -fn cell_without_bazel(release: &str) -> Cell { +/// command line of the release `release`, and what `socket-patch` writes +/// in a checkout. Its workspace copy is empty. +pub fn cell_without_bazel(release: &str) -> Cell { Cell { test: "a test".to_string(), repo_env: Vec::new(), diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs index f65382bcf..bd9f102b7 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -6,7 +6,7 @@ //! binary in it the way a user does, and builds again. What a test asserts, //! it reads from what Bazel built: the line `bazel run //:consumer` prints. //! -//! The tests are `#[ignore]`d: they need a Bazel release and the network +//! Those tests are `#[ignore]`d: they need a Bazel release and the network //! (the Bazel registry, the ruleset archives and the language toolchain), //! and a host that does not answer fails them. The package under test and //! every Socket host are loopback stand-ins. @@ -19,10 +19,15 @@ //! cargo test -p socket-patch-cli --test e2e_bazel_build -- --ignored go:: --nocapture //! ``` //! -//! A test takes its release from the Bazel it runs: the one +//! The other tests of the target need neither and run with a plain +//! `cargo test`: the checks of the harness and of the fixtures, and in +//! `go.rs` the tests that run `socket-patch` in a checkout no Bazel builds +//! and read the files it wrote. +//! +//! An `#[ignore]`d test takes its release from the Bazel it runs: the one //! `SOCKET_PATCH_BAZEL_E2E_BAZEL` names, else `bazel` on `PATH` (a bazelisk //! there picks its release as it does anywhere, from `USE_BAZEL_VERSION`). -//! With no Bazel a test prints `SKIP ` and passes; with +//! With no Bazel it prints `SKIP ` and passes; with //! `SOCKET_PATCH_BAZEL_E2E_REQUIRED=1` (CI) it fails instead. `harness.rs` //! lists the other variables. //! diff --git a/crates/socket-patch-cli/tests/fixtures/bazel/gazelle/bzlmod/common/BUILD.bazel b/crates/socket-patch-cli/tests/fixtures/bazel/gazelle/bzlmod/common/BUILD.bazel index 29489e934..9d623670e 100644 --- a/crates/socket-patch-cli/tests/fixtures/bazel/gazelle/bzlmod/common/BUILD.bazel +++ b/crates/socket-patch-cli/tests/fixtures/bazel/gazelle/bzlmod/common/BUILD.bazel @@ -1,8 +1,22 @@ -load("@rules_go//go:def.bzl", "go_binary") +load("@gazelle//:def.bzl", "gazelle") +load("@rules_go//go:def.bzl", "go_binary", "go_library") # Prints OUT: PRISTINE until the module is patched. go_binary( name = "consumer", + embed = [":consumer_lib"], + visibility = ["//visibility:public"], +) + +# This file is what `bazel run //:gazelle` writes for it: a run changes +# nothing here. +# gazelle:prefix example.com/consumer +gazelle(name = "gazelle") + +go_library( + name = "consumer_lib", srcs = ["main.go"], + importpath = "example.com/consumer", + visibility = ["//visibility:private"], deps = ["@com_example_upstream//:upstream"], ) diff --git a/crates/socket-patch-core/src/bazel/ignore.rs b/crates/socket-patch-core/src/bazel/ignore.rs new file mode 100644 index 000000000..aad0e4476 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/ignore.rs @@ -0,0 +1,849 @@ +//! The `.bazelignore` lines that keep patched Go module copies out of the +//! packages of a Bazel workspace. +//! +//! Vendored and agent mode patch a Go module by keeping a copy of it under +//! the project's `.socket` directory, which a `go.mod` `replace` points +//! at. Bazel and gazelle walk that copy like any directory of the +//! workspace: a BUILD file in it (one the module ships, or the one +//! `bazel run //:gazelle` writes there) is a package of the workspace, +//! gazelle's `go_deps` copies the directory with that file, and the build +//! 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. + +use std::path::{Path, PathBuf}; + +use crate::utils::fs::{atomic_write_sync, read_regular_to_bytes_sync, run_blocking}; +use crate::vendor::go_mod_edit::{GO_PATCHES_DIR, GO_VENDOR_DIR}; + +/// The warning code of a `.bazelignore` that [`sync`] could not update. +pub const NOT_UPDATED: &str = "bazelignore_not_updated"; + +/// The line above every line [`sync`] writes. +const COMMENT: &str = + "# socket-patch: patched Go module copies, not Bazel packages (to opt out, comment out the next line)"; + +/// How [`COMMENT`] starts, in this wording and in any other. A line is +/// [`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`] +/// leaves both lines alone. +const MARK: &str = "# socket-patch:"; + +/// Make the `.bazelignore` at the Bazel root of `project` agree with the Go +/// module copies of the project: for each of `.socket/vendor/golang` and +/// `.socket/go-patches`, one line under [`COMMENT`] while the directory +/// exists and the file neither covers nor declines it ([`settled`]), and no +/// such pair once it is gone; without `add`, pairs are only taken away. A +/// directory that cannot be probed keeps what the file says of it. A file +/// left empty is deleted. Outside a Bazel workspace ([`super::bazel_root`]) +/// nothing is read or written, and that lookup is all the call costs. +/// +/// The pair follows the directory, not the `replace`: a rollback that +/// keeps the copy on disk keeps its BUILD files in the workspace too. +/// +/// The file may belong to several projects, and the lock a command holds is +/// its project's, so the edit, from its read to its write, is made under a +/// lock of the root ([`lock`]). +/// +/// `Ok(Some)` is the file, when it was changed. `Err` is the detail of a +/// [`NOT_UPDATED`] warning: the file could not be read or written, or is a +/// link, which socket-patch does not write through. The command that asked +/// has done its work either way. +pub async fn sync(project: &Path, add: bool) -> Result, String> { + let project = project.to_path_buf(); + run_blocking(move || sync_blocking(&project, add)).await +} + +fn sync_blocking(project: &Path, add: bool) -> Result, String> { + let Some(root) = super::bazel_root(project) else { + return Ok(None); + }; + // Bazel wants `/` on every system. + let from_root: String = (root.project.components()) + .map(|part| format!("{}/", part.as_os_str().to_string_lossy())) + .collect(); + let project = root.dir.join(&root.project); + // `None`: it cannot be told (a directory above it that may not be + // searched). Only a directory that is not found is gone. + let exists = |dir: &str| match std::fs::metadata(project.join(dir)) { + 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 file = root.dir.join(".bazelignore"); + let read = || match read_regular_to_bytes_sync(&file) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), + read => read, + }; + // 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 { + return Ok(None); + } + let _lock = lock(&root.dir); + let (old, unreadable) = match read() { + Ok(old) => (old, None), + Err(e) => (Vec::new(), Some(e)), + }; + let new = edited(&old, &wanted, add); + // 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()); + let failed = match unreadable { + Some(e) => e, + None if new == old => return Ok(None), + // The target of a link is not the workspace's file to change, and + // a replacement would turn the link into a regular file. + None if crate::utils::containment::is_link(&file) => std::io::Error::other( + "it is a symbolic link, which socket-patch does not write through", + ), + None => match write(&file, &old, &new) { + Ok(()) => return Ok(Some(shown)), + Err(e) => e, + }, + }; + // A missing line is what the user has to act on. A pair that stays + // behind for a directory that is gone ignores nothing. + let missing: Vec = wanted + .iter() + .filter(|(line, exists)| add && *exists == Some(true) && !settled(&old, line)) + .map(|(line, _)| format!("`{line}`")) + .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 ") + ) + } else { + "the lines under socket-patch's comment in it name directories that no longer exist \ + and can be deleted" + .to_string() + }; + Err(format!( + "could not update {}: {failed}; {advice}", + shown.display() + )) +} + +/// The lock of the `.bazelignore` at `root`, which a process holds from its +/// read of the file to its write: without it, a pair that one project adds +/// between the read and the replacement of another project's removal is +/// lost. It is an advisory lock on the root directory itself, so that no +/// lock file is made anywhere. `None` when the directory cannot be opened +/// (on Windows no directory can be, this way) or locked, or stays held for +/// a second: the edit is then made without it. +fn lock(root: &Path) -> Option { + let dir = std::fs::File::open(root).ok()?; + for _ in 0..200 { + match fs2::FileExt::try_lock_exclusive(&dir) { + Ok(()) => return Some(dir), + Err(e) if crate::patch::apply_lock::is_lock_contended(&e) => { + std::thread::sleep(std::time::Duration::from_millis(5)) + } + Err(_) => break, + } + } + None +} + +/// Make `file`, which holds `old`, hold `new`. It is opened for appending +/// first, which creates it when it is missing (with the permission bits of +/// any new file), follows no link and fails for a read-only file, so that +/// such a file is neither replaced nor deleted. What is only added is then +/// one write at the end of that file, which is not replaced; a removal +/// replaces the file, or deletes it when nothing is left. +fn write(file: &Path, old: &[u8], new: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + let mut options = std::fs::OpenOptions::new(); + options.append(true).create(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, libc::O_NOFOLLOW); + let mut end = options.open(file)?; + let Some(added) = new.strip_prefix(old) else { + drop(end); + return match new.is_empty() { + true => std::fs::remove_file(file), + false => atomic_write_sync(file, new, true), + }; + }; + end.write_all(added)?; + end.sync_all() +} + +/// A line of the file without its line break (`\n`, or `\r\n`). +fn content(line: &[u8]) -> &[u8] { + let line = line.strip_suffix(b"\n").unwrap_or(line); + line.strip_suffix(b"\r").unwrap_or(line) +} + +/// `path` without one trailing `/` and a leading `./`: the same directory to Bazel. +fn plain(path: &[u8]) -> &[u8] { + let path = path.strip_suffix(b"/").unwrap_or(path); + path.strip_prefix(b"./").unwrap_or(path) +} + +/// Whether some line of `old` makes Bazel and gazelle skip the directory +/// `path`: the path itself or a directory above it, however spelled +/// ([`plain`]). Bazel takes a line literally, so one with a blank before or +/// after it, a `#` line, a pattern, or a mere string prefix of the path +/// does not. +fn covers(old: &[u8], path: &str) -> bool { + old.split_inclusive(|byte| *byte == b'\n').any(|line| { + let line = plain(content(line)); + let rest = path.as_bytes().strip_prefix(line); + !line.is_empty() && rest.is_some_and(|rest| rest.is_empty() || rest[0] == b'/') + }) +} + +/// Whether `old` needs no pair for the directory `path`: a line covers it +/// ([`covers`]), or the user declined the pair by commenting its path line +/// out: a [`MARK`] line, then a line of `#`, any blanks, and the [`plain`] +/// path. +fn settled(old: &[u8], path: &str) -> bool { + let lines: Vec<&[u8]> = (old.split_inclusive(|byte| *byte == b'\n')) + .map(content) + .collect(); + let declined = |pair: &[&[u8]]| { + let commented = pair[1].strip_prefix(b"#"); + pair[0].starts_with(MARK.as_bytes()) + && commented.is_some_and(|rest| plain(rest.trim_ascii_start()) == path.as_bytes()) + }; + covers(old, path) || lines.windows(2).any(declined) +} + +/// `old` as [`sync`] leaves it for `wanted`, the line of each directory and +/// whether the directory exists (`None`: unknown, and nothing changes for +/// it): without the pairs of the directories that are gone, and, with +/// `add`, with a pair at its end, in the file's own line ending, for each +/// directory that exists and is not [`settled`]. A file whose last line has +/// 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 { + let gone = |line: &[u8]| { + wanted + .iter() + .any(|(l, exists)| *exists == Some(false) && l.as_bytes() == content(line)) + }; + let lines: Vec<&[u8]> = old.split_inclusive(|byte| *byte == b'\n').collect(); + let mut new = Vec::with_capacity(old.len()); + let mut at = 0; + while at < lines.len() { + match lines.get(at + 1).filter(|next| gone(next)) { + Some(path) if lines[at].starts_with(MARK.as_bytes()) => { + let nl = &lines[at][content(lines[at]).len()..]; + if !path.ends_with(b"\n") && new.ends_with(nl) { + new.truncate(new.len() - nl.len()); + } + at += 2; + } + _ => { + new.extend_from_slice(lines[at]); + at += 1; + } + } + } + let nl = crate::utils::line_endings::terminator(&String::from_utf8_lossy(old)); + for (line, exists) in wanted { + if !add || *exists != Some(true) || settled(&new, line) { + continue; + } + let pair = match new.is_empty() || new.ends_with(b"\n") { + true => format!("{COMMENT}{nl}{line}{nl}"), + false => format!("{nl}{COMMENT}{nl}{line}"), + }; + new.extend_from_slice(pair.as_bytes()); + } + new +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + const VENDOR: &str = ".socket/vendor/golang"; + const PATCHES: &str = ".socket/go-patches"; + + /// [`edited`] for the two directories of a project at the root, each + /// existing or not. + 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() + } + + fn pair(line: &str) -> String { + format!("{COMMENT}\n{line}\n") + } + + /// What Bazel 9.3.2, 8.8.2 and 7.7.2 and gazelle 0.45.0 and 0.54.0 do + /// with each form of line, for a project at the root and for one in + /// `svc`. + #[test] + fn a_line_covers_the_path_or_a_directory_above_it_and_nothing_else() { + let covering = [ + VENDOR, + ".socket/vendor/golang/", + "./.socket/vendor/golang", + ".socket/vendor/golang\r", + ".socket/vendor", + ".socket", + ".socket/", + "./.socket/\r", + ]; + for line in covering { + let old = format!("node_modules\n{line}\nthird_party\n"); + assert!(covers(old.as_bytes(), VENDOR), "{line:?}"); + assert!(covers(line.as_bytes(), VENDOR), "{line:?}, no line break"); + } + let not_covering = [ + " .socket/vendor/golang", + ".socket/vendor/golang ", + ".socket/vendor/golang\t", + "#.socket/vendor/golang", + "# .socket", + ".socket/**", + ".socket/*", + ".socket/vendor/golan?", + ".socket/vendor/[g]olang", + ".socket/vendor/gol", + ".sock", + ".socket/vendor/golang/uuid", + ".socket/go-patches", + ".socket//", + "/", + "./", + "", + ]; + for line in not_covering { + let old = format!("{line}\n"); + assert!(!covers(old.as_bytes(), VENDOR), "{line:?}"); + } + // Below the root only a path from the root covers. + let below = "svc/.socket/vendor/golang"; + for line in [below, "svc/.socket", "svc", "./svc/"] { + assert!(covers(line.as_bytes(), below), "{line:?}"); + } + for line in [VENDOR, ".socket", "sv", "svc/.sock", "other/.socket"] { + assert!(!covers(line.as_bytes(), below), "{line:?}"); + } + } + + #[test] + fn a_pair_is_appended_once_for_each_directory_no_line_covers() { + assert_eq!(edit("", false, false), ""); + assert_eq!(edit("", true, false), pair(VENDOR)); + assert_eq!(edit("", false, true), pair(PATCHES)); + let both = pair(VENDOR) + &pair(PATCHES); + assert_eq!(edit("", true, true), both); + // A second run leaves one pair of each. + assert_eq!(edit(&both, true, true), both); + assert_eq!(edit(&pair(VENDOR), true, true), both); + // After the user's lines, in the line breaks of the file: Bazel + // and gazelle read a line that ends in CRLF as the path. + let crlf = pair(VENDOR).replace('\n', "\r\n"); + assert_eq!( + edit("a\nb\n", true, false), + format!("a\nb\n{}", pair(VENDOR)) + ); + assert_eq!(edit("a\r\nb\r\n", true, false), format!("a\r\nb\r\n{crlf}")); + // A line of the user's that covers the directory is enough, and a + // line that does not is not. + for covered in [".socket\n", "./.socket/vendor/golang/\n", ".socket/vendor"] { + assert_eq!(edit(covered, true, false), covered); + } + assert_eq!( + edit(".socket/vendor/golang \n", true, false), + format!(".socket/vendor/golang \n{}", pair(VENDOR)) + ); + assert_eq!(edit(".socket\n", true, true), ".socket\n"); + } + + #[test] + fn only_a_pair_of_a_directory_that_is_gone_is_removed() { + let both = pair(VENDOR) + &pair(PATCHES); + assert_eq!(edit(&both, false, true), pair(PATCHES)); + assert_eq!(edit(&both, true, false), pair(VENDOR)); + // The user's lines stay byte for byte, around the pair and in + // place of it: a line without the comment above it is theirs. + let own = "# mine\n\n indented\t\nnode_modules/\n"; + let around = format!("{own}{}{own}", pair(VENDOR)); + assert_eq!(edit(&around, false, false), format!("{own}{own}")); + for theirs in [ + format!("{VENDOR}\n"), + format!("{COMMENT}\n{VENDOR}/\n"), + format!(" {COMMENT}\n{VENDOR}\n"), + format!("# socket-patch\n{VENDOR}\n"), + format!("#socket-patch: mine\n{VENDOR}\n"), + format!("{COMMENT}\n\n{VENDOR}\n"), + format!("{COMMENT}\n"), + ] { + assert_eq!(edit(&theirs, false, false), theirs); + } + } + + /// socket-patch knows its lines by the start of the comment line, so a + /// pair under another wording of it (an earlier or a later release's) is + /// still its own: it stays, alone, while the copy is there, goes with + /// the copy, byte for byte, and is declined by a commented-out path line. + #[test] + fn a_pair_under_another_wording_of_the_comment_is_known() { + assert!(COMMENT.starts_with(MARK)); + for comment in [MARK, "# socket-patch: said otherwise", "# socket-patch:\t"] { + let reworded = format!("node_modules\n{comment}\n{VENDOR}\n"); + assert_eq!(edit(&reworded, true, false), reworded, "{comment:?}"); + assert_eq!(edit(&reworded, false, false), "node_modules\n"); + let ending = format!("node_modules\r\n{comment}\r\n{VENDOR}"); + assert_eq!(edit(&ending, false, false), "node_modules"); + let declined = format!("node_modules\n{comment}\n# {VENDOR}\n"); + for vendor in [true, false] { + assert_eq!(edit(&declined, vendor, false), declined, "{comment:?}"); + } + } + } + + /// The pairs go as they came, one by one in either order or both at + /// once: what is left is the file of before, byte for byte, also when + /// its last line had no line break, or ended in a carriage return on + /// its own. Lines the user wrote after a pair stay, with the line break + /// that set the pair apart from the file. + #[test] + fn taking_the_pairs_away_leaves_the_file_of_before() { + // Each file, and the line break it gets before its first pair. + let files = [ + ("", ""), + ("a\n", ""), + ("a\nb", "\n"), + ("a\r\nb\r\n", ""), + ("a\r\nb", "\r\n"), + ("# mine\n\n x\t", "\n"), + ("a\r", "\n"), + ("a\n\r", "\n"), + ("a\rb\rc\r", "\n"), + ("x\r\ny\r", "\r\n"), + ]; + for (old, nl) in files { + let ended = old.is_empty() || old.ends_with('\n'); + assert_eq!(ended, nl.is_empty(), "{old:?}"); + let one = edit(old, true, false); + assert!(one.starts_with(&format!("{old}{nl}{COMMENT}")), "{old:?}"); + let two = edit(&one, true, true); + assert!(one.starts_with(old) && two.starts_with(&one), "{old:?}"); + assert_eq!(two, edit(old, true, true), "{old:?}"); + assert_eq!(two.ends_with('\n'), ended, "{old:?}"); + assert!(two.ends_with(PATCHES) || two.ends_with('\n'), "{old:?}"); + for first in [ + edit(&two, false, true), + edit(&two, true, false), + two.clone(), + ] { + assert_eq!(edit(&first, false, false), old, "{old:?} from {first:?}"); + } + let more = format!("{one}{nl}mine\n"); + assert_eq!(edit(&more, false, false), format!("{old}{nl}mine\n")); + } + // A pair that ends the file without a line break goes with the + // line break before it, whoever took its own away, when that is + // the line break of its comment line: another one was not written + // with the pair. + assert_eq!(edit(&format!("a\n{COMMENT}\n{VENDOR}"), false, false), "a"); + let other = format!("a\r\n{COMMENT}\n{VENDOR}"); + assert_eq!(edit(&other, false, false), "a\r"); + let other = format!("a\n{COMMENT}\r\n{VENDOR}"); + assert_eq!(edit(&other, false, false), "a\n"); + } + + /// The user's "no": the comment line with the path line commented out + /// under it. Nothing is added for that directory and the two lines + /// stay, whether the directory is there or not, while the pair of the + /// other directory comes and goes. + #[test] + fn a_commented_out_path_line_declines_the_pair() { + let spellings = [ + format!("#{VENDOR}"), + format!("# \t{VENDOR}"), + format!("# {VENDOR}/"), + format!("# ./{VENDOR}"), + ]; + for path in spellings { + let declined = format!("node_modules\n{COMMENT}\n{path}\n"); + for vendor in [true, false] { + assert_eq!(edit(&declined, vendor, false), declined); + let other = edit(&declined, vendor, true); + assert_eq!(other, format!("{declined}{}", pair(PATCHES))); + assert_eq!(edit(&other, vendor, false), declined); + } + assert!(settled(declined.as_bytes(), VENDOR)); + assert!(!settled(declined.as_bytes(), PATCHES)); + } + // No "no": without the comment line above it (a commented-out + // one included), or not that path. + for other in [ + format!("#{VENDOR}\n"), + format!("# {COMMENT}\n# {VENDOR}\n"), + format!("{COMMENT}\n\n#{VENDOR}\n"), + format!("{COMMENT}\n#{VENDOR}//\n"), + format!("{COMMENT}\n#{VENDOR} \n"), + format!("{COMMENT}\n #{VENDOR}\n"), + format!("{COMMENT}\n##{VENDOR}\n"), + format!("{COMMENT}\n# .socket\n"), + format!("{COMMENT}\n#{PATCHES}\n"), + ] { + assert_eq!(edit(&other, true, false), other.clone() + &pair(VENDOR)); + } + } + + /// A Bazel workspace with a checkout at its root and a project in + /// `rel` of it (`""`: the root), which has the copy directory `dir`. + fn project(rel: &str, dir: &str) -> (tempfile::TempDir, PathBuf, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let root = fs::canonicalize(tmp.path()).unwrap(); + let project = root.join(rel); + fs::create_dir_all(root.join(".git")).unwrap(); + fs::create_dir_all(project.join(dir)).unwrap(); + fs::write(root.join("MODULE.bazel"), "").unwrap(); + (tmp, root, project) + } + + /// [`super::sync`] for a run that has Go in scope. + async fn sync(project: &Path) -> Result, String> { + super::sync(project, true).await + } + + /// The file [`sync`] says it changed, as the test spells it. + fn changed(root: &Path) -> Result, String> { + let file = root.join(".bazelignore"); + Ok(Some(crate::utils::pnpm_workspace::without_verbatim_prefix( + file, + ))) + } + + #[tokio::test] + async fn the_file_at_the_root_follows_the_directories_of_the_project() { + let (_tmp, root, project) = project("", VENDOR); + let file = root.join(".bazelignore"); + assert_eq!(sync(&project).await, changed(&root)); + assert_eq!(sync(&project).await, Ok(None), "a second run"); + assert_eq!(fs::read_to_string(&file).unwrap(), pair(VENDOR)); + fs::create_dir_all(project.join(PATCHES)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + let both = pair(VENDOR) + &pair(PATCHES); + assert_eq!(fs::read_to_string(&file).unwrap(), both); + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert_eq!(fs::read_to_string(&file).unwrap(), pair(PATCHES)); + // The file `sync` made goes with its last pair, and so does an + // empty one the user had. + fs::remove_dir_all(project.join(PATCHES)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert!(!file.exists()); + fs::write(&file, "").unwrap(); + assert_eq!(sync(&project).await, Ok(None)); + assert_eq!(fs::read_to_string(&file).unwrap(), "", "nothing to change"); + } + + /// A pair is written at the end of the file that is there, whatever its + /// last line break, and that file is not replaced: a hard link to it + /// reads the pair too. A missing file is created, with the permission + /// bits of any new file. Without the directory the file is the one of + /// before again. + #[tokio::test] + async fn a_pair_is_appended_to_the_file_that_is_there() { + let crlf = pair(VENDOR).replace('\n', "\r\n"); + let files = [ + (None, pair(VENDOR)), + (Some(""), pair(VENDOR)), + (Some("node_modules\n# mine\n"), pair(VENDOR)), + ( + Some("node_modules\nthird_party"), + format!("\n{COMMENT}\n{VENDOR}"), + ), + (Some("a\r\nb\r\n"), crlf.clone()), + (Some("a\r\nb"), format!("\r\n{}", crlf.trim_end())), + ]; + for (old, added) in files { + let (_tmp, root, project) = project("", VENDOR); + let (file, other) = (root.join(".bazelignore"), root.join("other")); + if let Some(old) = old { + fs::write(&file, old).unwrap(); + fs::hard_link(&file, &other).unwrap(); + } + assert_eq!(sync(&project).await, changed(&root)); + let new = format!("{}{added}", old.unwrap_or("")); + assert_eq!(fs::read_to_string(&file).unwrap(), new, "{old:?}"); + if old.is_some() { + assert_eq!(fs::read_to_string(&other).unwrap(), new, "{old:?}"); + } else { + fs::write(&other, "").unwrap(); + let bits = |path| fs::metadata(path).unwrap().permissions(); + assert_eq!(bits(&file), bits(&other)); + } + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + let left = fs::read_to_string(&file).ok(); + assert_eq!( + left.as_deref(), + old.filter(|old| !old.is_empty()), + "{old:?}" + ); + } + } + + /// A run that leaves Go out adds no pair for a copy that is there, and + /// says nothing of one it cannot add; it takes the pair of a copy that + /// is gone away, and says so when it cannot. + #[tokio::test] + async fn a_run_that_leaves_go_out_only_takes_pairs_away() { + let (_tmp, root, project) = project("", VENDOR); + let file = root.join(".bazelignore"); + assert_eq!(super::sync(&project, false).await, Ok(None)); + assert!(!file.exists()); + fs::create_dir(&file).unwrap(); + assert_eq!(super::sync(&project, false).await, Ok(None), "unreadable"); + fs::remove_dir(&file).unwrap(); + // The pair of the copy that is there stays, and the one of the copy + // that is gone goes. + let kept = format!("node_modules\n{}", pair(VENDOR)); + fs::write(&file, format!("{kept}{}", pair(PATCHES))).unwrap(); + assert_eq!(super::sync(&project, false).await, changed(&root)); + assert_eq!(fs::read_to_string(&file).unwrap(), kept); + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + let mut bits = fs::metadata(&file).unwrap().permissions(); + bits.set_readonly(true); + fs::set_permissions(&file, bits).unwrap(); + if fs::OpenOptions::new().append(true).open(&file).is_err() { + let detail = super::sync(&project, false).await.expect_err("read-only"); + assert!(detail.contains("can be deleted"), "{detail}"); + assert_eq!(fs::read_to_string(&file).unwrap(), kept); + } + } + + /// Two projects under one root share the file. What each does to it at + /// the same moment as the other stays: two pairs added at once, and, + /// under the lock of the root, which Windows does not have, a pair + /// added while the other project's is removed. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn two_projects_that_edit_at_once_both_have_their_way() { + let (_tmp, root, a) = project("a", VENDOR); + let (b, file) = (root.join("b"), root.join(".bazelignore")); + fs::create_dir_all(b.join(PATCHES)).unwrap(); + let (pair_a, pair_b) = ( + pair("a/.socket/vendor/golang"), + pair("b/.socket/go-patches"), + ); + let at_once = || async { + let runs = [a.clone(), b.clone()] + .map(|project| tokio::spawn(async move { sync(&project).await.is_ok() })); + for run in runs { + assert!(run.await.unwrap()); + } + fs::read_to_string(&file).unwrap() + }; + for round in 0..25 { + let _ = fs::remove_file(&file); + let both = at_once().await; + let either = [format!("{pair_a}{pair_b}"), format!("{pair_b}{pair_a}")]; + assert!(either.contains(&both), "round {round}: {both:?}"); + // `a` loses its copy while `b`, whose pair is not there, adds. + if cfg!(unix) { + fs::write(&file, &pair_a).unwrap(); + fs::remove_dir_all(a.join(VENDOR)).unwrap(); + assert_eq!(at_once().await, pair_b, "round {round}"); + fs::create_dir_all(a.join(VENDOR)).unwrap(); + } + } + } + + #[tokio::test] + async fn a_project_below_the_root_is_named_from_the_root() { + let (_tmp, root, project) = project("svc/go", PATCHES); + assert_eq!(sync(&project).await, changed(&root)); + let file = fs::read_to_string(root.join(".bazelignore")).unwrap(); + assert_eq!(file, pair("svc/go/.socket/go-patches")); + assert!(!project.join(".bazelignore").exists()); + // A line that names the directory from the project covers nothing + // there, and a sibling's pair is not this project's to remove. + let sibling = pair("svc/js/.socket/go-patches") + ".socket/go-patches\n"; + fs::write(root.join(".bazelignore"), &sibling).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + let file = fs::read_to_string(root.join(".bazelignore")).unwrap(); + assert_eq!(file, sibling.clone() + &pair("svc/go/.socket/go-patches")); + fs::remove_dir_all(project.join(PATCHES)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert_eq!( + fs::read_to_string(root.join(".bazelignore")).unwrap(), + sibling + ); + } + + #[tokio::test] + async fn outside_a_bazel_workspace_nothing_is_written() { + let (_tmp, root, project) = project("", VENDOR); + fs::remove_file(root.join("MODULE.bazel")).unwrap(); + fs::create_dir(root.join("WORKSPACE")).unwrap(); + fs::write(root.join(".bazelignore"), pair(PATCHES)).unwrap(); + assert_eq!(sync(&project).await, Ok(None)); + assert_eq!( + fs::read_to_string(root.join(".bazelignore")).unwrap(), + pair(PATCHES) + ); + } + + /// A copy directory that cannot be probed, here below a directory that + /// may not be searched, is not gone: its pair stays, and it gets none. + #[cfg(unix)] + #[tokio::test] + async fn a_directory_that_cannot_be_probed_keeps_what_the_file_says() { + use std::os::unix::fs::PermissionsExt; + let (_tmp, root, project) = project("", VENDOR); + let (file, above) = (root.join(".bazelignore"), project.join(".socket/vendor")); + let search = |bits| fs::set_permissions(&above, fs::Permissions::from_mode(bits)).unwrap(); + search(0o000); + let mut seen = Vec::new(); + for old in [pair(VENDOR), "node_modules\n".to_string()] { + fs::write(&file, &old).unwrap(); + seen.push((sync(&project).await, fs::read_to_string(&file).ok(), old)); + } + // Root searches any directory, and tells that the copy is there. + let told = fs::metadata(project.join(VENDOR)).is_ok(); + search(0o755); + for (said, left, old) in seen.into_iter().filter(|_| !told) { + assert_eq!((said, left), (Ok(None), Some(old))); + } + // Not found is gone, as before. + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + fs::write(&file, pair(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, changed(&root)); + assert!(!file.exists()); + } + + /// A file that cannot be read or replaced is the caller's warning, with + /// the line to add, and stays as it is. + #[tokio::test] + async fn a_file_that_cannot_be_updated_is_reported_with_the_line() { + let (_tmp, root, project) = project("", VENDOR); + let file = root.join(".bazelignore"); + fs::create_dir(&file).unwrap(); + let detail = sync(&project) + .await + .expect_err("a directory in the file's place"); + assert!( + detail.contains("add `.socket/vendor/golang` to it"), + "{detail}" + ); + let shown = crate::utils::pnpm_workspace::without_verbatim_prefix(file); + let start = format!("could not update {}: ", shown.display()); + assert!(detail.starts_with(&start), "{detail}"); + // Nothing to add: nothing to report. + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + assert_eq!(sync(&project).await, Ok(None)); + } + + /// The lock is one on the root directory itself, and no file anywhere. + /// An edit waits a second for whoever holds it and is then made without + /// it. A run that has nothing to change takes none, and so does not + /// wait: the file is as it should be, or it cannot be read and the + /// project has no copy to name in it. + #[cfg(unix)] + #[tokio::test] + async fn only_an_edit_takes_the_lock_of_the_root_directory() { + let (_tmp, root, project) = project("", ""); + let (file, held) = (root.join(".bazelignore"), fs::File::open(&root).unwrap()); + fs2::FileExt::lock_exclusive(&held).unwrap(); + let start = std::time::Instant::now(); + for unreadable in [false, true] { + if unreadable { + fs::create_dir(&file).unwrap(); + } + assert_eq!(sync(&project).await, Ok(None), "unreadable: {unreadable}"); + } + fs::remove_dir(&file).unwrap(); + let idle = start.elapsed(); + fs::create_dir_all(project.join(VENDOR)).unwrap(); + let start = std::time::Instant::now(); + assert_eq!(sync(&project).await, changed(&root)); + let second = std::time::Duration::from_secs(1); + // With a lock to take, each of the two idle runs waits that second. + assert!(idle < 2 * second && start.elapsed() >= second, "{idle:?}"); + assert_eq!(fs::read_to_string(&file).unwrap(), pair(VENDOR)); + let mut names: Vec<_> = fs::read_dir(&root).unwrap().flatten().collect(); + names.sort_by_key(|entry| entry.file_name()); + let names: Vec<_> = names.iter().map(|entry| entry.file_name()).collect(); + assert_eq!(names, [".bazelignore", ".git", ".socket", "MODULE.bazel"]); + } + + /// A read-only file stays as it is, bytes and permission bits: it is + /// neither replaced to get a pair in or out, nor deleted with its last + /// pair. What it lacks, or holds too much, is the caller's warning. + #[tokio::test] + async fn a_read_only_file_is_reported_and_stays() { + let stale = "the lines under socket-patch's comment in it name directories that no longer"; + let files = [ + ( + "node_modules\n".to_string(), + true, + "add `.socket/vendor/golang` to it", + ), + (format!("node_modules\n{}", pair(VENDOR)), false, stale), + (pair(VENDOR), false, stale), + ]; + for (old, copy, advice) in files { + let (_tmp, root, project) = project("", VENDOR); + let file = root.join(".bazelignore"); + fs::write(&file, &old).unwrap(); + let mut bits = fs::metadata(&file).unwrap().permissions(); + bits.set_readonly(true); + fs::set_permissions(&file, bits.clone()).unwrap(); + if fs::OpenOptions::new().append(true).open(&file).is_ok() { + return; // A root process writes a read-only file. + } + if !copy { + fs::remove_dir_all(project.join(VENDOR)).unwrap(); + } + let detail = sync(&project).await.expect_err("a read-only file"); + assert!(detail.contains(advice), "{detail}"); + assert_eq!(fs::read_to_string(&file).unwrap(), old); + assert_eq!(fs::metadata(&file).unwrap().permissions(), bits); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn a_linked_file_is_not_written_through() { + let (_tmp, root, project) = project("", VENDOR); + let (file, target) = (root.join(".bazelignore"), root.join("shared-ignore")); + std::os::unix::fs::symlink(&target, &file).unwrap(); + // A pair to add, and then one to take away. + for (old, advice) in [ + ( + "node_modules\n".to_string(), + "add `.socket/vendor/golang` to it", + ), + (pair(VENDOR), "can be deleted"), + ] { + fs::write(&target, &old).unwrap(); + let detail = sync(&project) + .await + .expect_err("a link in the file's place"); + assert!(detail.contains("symbolic link"), "{detail}"); + assert!(detail.contains(advice), "{detail}"); + assert!(fs::symlink_metadata(&file) + .unwrap() + .file_type() + .is_symlink()); + assert_eq!(fs::read_to_string(&target).unwrap(), old); + let _ = fs::remove_dir_all(project.join(VENDOR)); + } + // The user's own line through the link covers, and nothing is + // written. + fs::create_dir_all(project.join(VENDOR)).unwrap(); + fs::write(&target, ".socket\n").unwrap(); + assert_eq!(sync(&project).await, Ok(None)); + } +} diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs new file mode 100644 index 000000000..7147e02a2 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -0,0 +1,158 @@ +//! What socket-patch knows about Bazel workspaces. + +/// The files that mark the root of a Bazel workspace: the names Bazel's own +/// client looks for from the working directory up (7.7.2, 8.8.2 and 9.3.2, +/// `WorkspaceLayout::InWorkspace`). Only a regular file of one of these +/// names counts (a link to a file is followed); a directory does not: on a +/// disk that folds case, a directory `workspace` answers for `WORKSPACE`. +pub const WORKSPACE_FILES: [&str; 4] = + ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; + +pub mod ignore; + +use std::path::{Path, PathBuf}; + +use crate::utils::repo_root::{repo_at_end_of, search_dirs, GitRepo}; + +/// The Bazel workspace a project is in. +#[derive(Debug, PartialEq)] +pub struct BazelRoot { + /// The root: the nearest directory, from the project up, that holds one + /// of [`WORKSPACE_FILES`]. Canonical. + pub dir: PathBuf, + /// The project's directory from `dir`: empty for a project at the root. + pub project: PathBuf, +} + +/// The Bazel workspace the project at `project` is in, from one walk +/// ([`search_dirs`], whose bounds and canonical paths these are): the +/// project's own directory, or one up to the root of its git checkout. That +/// is the checkout [`crate::utils::repo_root::find_git_repo`] finds, when +/// its `.git` belongs to a trusted owner; in no such checkout only the +/// project's own directory is looked at. So nothing above the checkout, or +/// above a project outside one, is read, and no file is written there. +pub fn bazel_root(project: &Path) -> Option { + let dirs = search_dirs(project); + root_in(&dirs, repo_at_end_of(dirs.clone())) +} + +/// [`bazel_root`] for the walk `dirs`, which ended at the checkout `repo`. +fn root_in(dirs: &[PathBuf], repo: Option) -> Option { + let within = repo.filter(|repo| repo.trusted).map_or(1, |_| dirs.len()); + let at = dirs.iter().take(within).position(|dir| { + let marks = |name| std::fs::metadata(dir.join(name)).is_ok_and(|meta| meta.is_file()); + WORKSPACE_FILES.into_iter().any(marks) + })?; + Some(BazelRoot { + dir: dirs[at].clone(), + project: dirs[0].strip_prefix(&dirs[at]).ok()?.to_path_buf(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + /// A temp directory, canonical, holding the directories `dirs` and the + /// empty files `files`. + fn tree(dirs: &[&str], files: &[&str]) -> (tempfile::TempDir, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let base = fs::canonicalize(tmp.path()).unwrap(); + for dir in dirs { + fs::create_dir_all(base.join(dir)).unwrap(); + } + for file in files { + fs::write(base.join(file), "").unwrap(); + } + (tmp, base) + } + + /// The root of `project`'s workspace. + fn root(project: &Path) -> Option { + bazel_root(project).map(|found| found.dir) + } + + #[test] + fn the_root_is_the_nearest_directory_with_a_workspace_file() { + let (_tmp, base) = tree(&["repo/.git", "repo/svc/app"], &["repo/MODULE.bazel"]); + let (repo, app) = (base.join("repo"), base.join("repo/svc/app")); + // The project at the root, and one below it. + let at_root = bazel_root(&repo).unwrap(); + assert_eq!( + (at_root.dir, at_root.project), + (repo.clone(), PathBuf::new()) + ); + let below = bazel_root(&app).unwrap(); + assert_eq!( + (below.dir, below.project), + (repo.clone(), PathBuf::from("svc/app")) + ); + // The nearest wins, under each name. + for name in ["WORKSPACE", "WORKSPACE.bazel", "REPO.bazel", "MODULE.bazel"] { + let file = base.join("repo/svc").join(name); + fs::write(&file, "").unwrap(); + assert_eq!(root(&app), Some(base.join("repo/svc")), "{name}"); + fs::remove_file(&file).unwrap(); + } + fs::remove_file(repo.join("MODULE.bazel")).unwrap(); + assert_eq!(bazel_root(&app), None); + } + + #[test] + fn a_workspace_file_above_the_checkout_is_not_seen() { + let (_tmp, base) = tree(&["repo/.git", "repo/app"], &["MODULE.bazel", "WORKSPACE"]); + assert_eq!(bazel_root(&base.join("repo/app")), None); + assert_eq!(bazel_root(&base.join("repo")), None); + } + + /// `/workspace/proj`: where the disk folds case, the directory + /// `workspace` is what a lookup of `WORKSPACE` in the checkout finds. + #[test] + fn a_directory_named_like_a_workspace_file_is_no_root() { + let dirs = [".git", "workspace/proj", "sub/MODULE.bazel", "sub/proj"]; + let (_tmp, base) = tree(&dirs, &[]); + assert_eq!(bazel_root(&base.join("workspace/proj")), None); + assert_eq!(bazel_root(&base.join("sub/proj")), None); + } + + #[cfg(unix)] + #[test] + fn a_link_counts_when_it_leads_to_a_file() { + use std::os::unix::fs::symlink; + let (_tmp, base) = tree(&["repo/.git", "repo/app", "dir"], &["module"]); + let (repo, name) = (base.join("repo"), base.join("repo/MODULE.bazel")); + symlink(base.join("dir"), &name).unwrap(); + assert_eq!(bazel_root(&repo.join("app")), None, "a link to a directory"); + fs::remove_file(&name).unwrap(); + symlink(base.join("missing"), &name).unwrap(); + assert_eq!(bazel_root(&repo.join("app")), None, "a link to nothing"); + fs::remove_file(&name).unwrap(); + symlink(base.join("module"), &name).unwrap(); + assert_eq!(root(&repo.join("app")), Some(repo)); + } + + /// `tmp/.git` and `tmp/MODULE.bazel` of another user, and a project of + /// one's own in `tmp/job/proj`: a checkout whose `.git` belongs to an + /// owner that is not trusted is none, and a project in no checkout is + /// looked for in its own directory only, whatever lies above it. + #[test] + fn only_a_trusted_checkout_reaches_above_the_project() { + let (_tmp, base) = tree(&[".git", "job/proj"], &["MODULE.bazel"]); + let proj = base.join("job/proj"); + let dirs = search_dirs(&proj); + assert_eq!(dirs.last(), Some(&base)); + let found = |trusted: Option| { + let repo = repo_at_end_of(dirs.clone()).expect("the checkout"); + let repo = trusted.map(|trusted| GitRepo { trusted, ..repo }); + root_in(&dirs, repo).map(|found| (found.dir, found.project)) + }; + assert_eq!(found(Some(true)), Some((base, PathBuf::from("job/proj")))); + for none in [Some(false), None] { + assert_eq!(found(none), None, "{none:?}"); + fs::write(proj.join("WORKSPACE.bazel"), "").unwrap(); + assert_eq!(found(none), Some((proj.clone(), PathBuf::new()))); + fs::remove_file(proj.join("WORKSPACE.bazel")).unwrap(); + } + } +} diff --git a/crates/socket-patch-core/src/lib.rs b/crates/socket-patch-core/src/lib.rs index 10a9a5893..31b991ba2 100644 --- a/crates/socket-patch-core/src/lib.rs +++ b/crates/socket-patch-core/src/lib.rs @@ -37,6 +37,7 @@ macro_rules! eprint { } pub mod api; +pub mod bazel; pub mod constants; pub mod crawlers; pub mod formats; diff --git a/crates/socket-patch-core/src/utils/repo_root.rs b/crates/socket-patch-core/src/utils/repo_root.rs index ad3ccea1e..4c9099539 100644 --- a/crates/socket-patch-core/src/utils/repo_root.rs +++ b/crates/socket-patch-core/src/utils/repo_root.rs @@ -390,7 +390,7 @@ fn home_repo_beyond(dirs: &[PathBuf], home: Option<&Path>) -> Option { /// The checkout at the last directory of a [`search_dirs`] walk, if the /// walk ended on one. -fn repo_at_end_of(mut dirs: Vec) -> Option { +pub(crate) fn repo_at_end_of(mut dirs: Vec) -> Option { let root = dirs.pop()?; let meta = dot_git_metadata(&root)?; Some(GitRepo { diff --git a/crates/socket-patch-core/src/vendor/go_mod_edit.rs b/crates/socket-patch-core/src/vendor/go_mod_edit.rs index 6bffc966f..8a186c17c 100644 --- a/crates/socket-patch-core/src/vendor/go_mod_edit.rs +++ b/crates/socket-patch-core/src/vendor/go_mod_edit.rs @@ -53,7 +53,7 @@ pub const GO_PATCHES_DIR: &str = ".socket/go-patches"; /// Project-relative directory holding `vendor`'s committed module copies /// (`//@`). A `replace` whose /// target path is under this prefix is owned by [`ReplaceOwner::Vendor`]. -const GO_VENDOR_DIR: &str = ".socket/vendor/golang"; +pub(crate) const GO_VENDOR_DIR: &str = ".socket/vendor/golang"; /// Module-path namespace of Socket's hosted patched Go modules. A /// module-to-module `replace` whose RIGHT-hand module path is this prefix diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 236ad6665..fe0242d50 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1912,6 +1912,118 @@ with the command that does, and | `go_vendor_modules_txt_out_of_sync` | A committed `vendor/` directory (`go mod vendor`; `go work vendor` for a workspace) whose `vendor/modules.txt` does not record a socket `replace`, or still records one that was removed. go builds with `-mod=vendor` and fails with "inconsistent vendoring" | `go mod vendor` (or `go work vendor`), then commit `vendor/` | | `go_requirements_out_of_sync` | The patched module's own `go.mod` requires a dependency at a version above the one the project's `go.mod` lists (agent and vendored modes; `apply` also reports a requirement the patch added). The default `-mod=readonly` build fails with "updates to go.mod needed" or "missing go.sum entry" | `go mod tidy`, then commit `go.mod` and `go.sum` | +### Bazel workspaces: `.bazelignore` + +In a Bazel workspace the module copies of vendored and agent mode are directories that Bazel +and gazelle walk like any other. A BUILD file in a copy (one the module ships, or the one +`bazel run //:gazelle` writes there) is then a package of the workspace, gazelle's `go_deps` +copies the directory with that file, and every target that uses the module fails to load +(`No repository visible as '@rules_go'`). So socket-patch keeps the copies out of the +workspace's packages with `.bazelignore`. + +A project is in a Bazel workspace when its directory, or one above it up to the root of its git +checkout, holds a regular file `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel` +(the names Bazel itself looks for); the nearest such directory is the Bazel root. The checkout +is the one the `socket.yml` lookup takes for the repository root: on Unix its `.git` belongs to +you, to root, or to the user `sudo` ran for (a root process takes any owner's). A project in no +such checkout is looked for in its own directory only: nothing above it is read or written. In +a Bazel workspace, every command that can write or remove a copy (`scan`, `get`, `apply`, +`vendor`, `vendor --revert`, `rollback`, `remove`, `repair`) ends by bringing the root's +`.bazelignore` in line with the copies on disk, unless it is a dry run. A command whose +`--ecosystems` leaves `golang` out adds no line; it still takes away the pair of a copy that is +gone: + +- While `/.socket/vendor/golang` (vendored mode) or `/.socket/go-patches` + (agent mode) exists, the file names that directory by its path from the Bazel root, on a line + of its own under the comment line + `# socket-patch: patched Go module copies, not Bazel packages (to opt out, comment out the next line)`. + The two lines are added at the end of the file, in its line breaks, and the file is created + when it is missing. Nothing is added when a line already covers the directory: its path or a + directory above it. Bazel reads a line literally, so a pattern, or a line with a space before + or after it, covers nothing. +- Once the directory is gone, the pair is removed, and the file is the one of before, byte for + byte: a last line that had no line break has none again. A file that is left empty is + deleted, also when it was an empty file of yours. socket-patch knows its pair by the start + of the comment line, `# socket-patch:`: a path line under a line that starts so is its own, + whatever the rest of that line says, and a line without one above it is never changed. Only a + directory that is not there is gone: one that cannot be looked at (a directory above it that + you may not search) keeps its pair, and gets none. `rollback --preserve-state` keeps a + vendored copy on disk, and with it the line. +- To keep the copies visible to Bazel (see the first limit below), comment the path line out + and leave the comment line above it: `# .socket/vendor/golang`. socket-patch then adds no + line for that directory, gives no warning about it, and never touches the two lines again. + The commented path may end in one `/` or start with `./`. Deleting both lines is no opt-out: + the next command writes them back. Neither is commenting out both lines, or a path line + changed in any other way (a space after it, a second `#`, a blank line above it). + +Commit `.bazelignore` with `go.mod` and the copy. A command that changed the file says so +(`Updated ` or `Removed `, on stdout, not under `--json` or `--silent`). With a +`--manifest-path` into another project, the agent copies are those of `--cwd` and the vendored +ones those of the manifest's project, and the command brings the file of each project's Bazel +root in line. Bazel 8 and 9 also take `ignore_directories` in `REPO.bazel`, which socket-patch +does not read: a workspace that ignores `.socket` there gets the line as well, and both +together are fine. + +When the file cannot be written (a symbolic link or a directory in its place, a read-only +directory, a read-only file, which is neither replaced nor deleted), the command still succeeds +and warns `bazelignore_not_updated` with the line to add, or, for a copy that is gone, that its +two lines can be deleted. + +Side effects and limits: + +- Bazel leaves an ignored directory out of every `glob()` of a package above it as well. A + target that hands the project's Go files to a `go` command of its own through such a glob (a + `genrule` that runs `go build`, a source archive, an image layer) no longer receives the + copies, and its `go build` fails in the sandbox: + `replacement directory ./.socket/vendor/golang/... does not exist` (Bazel 9.3.2). Without the + line the same target builds until the first `bazel run //:gazelle`, whose BUILD file in the + copy takes the copy out of the glob in the same way. With the line it builds when it names + the files of the copy one by one beside the glob, or runs outside the sandbox. Such a + workspace can opt out as above. +- Only Go module copies are covered. The unpacked packages other ecosystems keep under + `.socket/vendor/` get no line. +- A Bazel root that socket-patch does not look for gets no line, and no warning is given: add + the line by hand, with the directory's path from that root. That is a root above the root of + the project's git checkout (the project is a git submodule, or several checkouts sit below + one Bazel workspace), and a root above a project that is in no git checkout (a Docker build + context, an unpacked source archive) or in a checkout of another user. Nothing outside the + checkout, or above such a project, is read. +- The Bazel root is the nearest directory with a workspace file. When that workspace is nested + in a larger one (`outer/MODULE.bazel`, `outer/inner/MODULE.bazel`, the project in `inner`), + the line is in `inner/.bazelignore`, which only a Bazel or gazelle run from `inner` reads. A + run from `outer` takes `inner` for part of its own tree (Bazel 9.3.2, gazelle 0.54.0): + `bazel build //...` loads the packages under `inner`, a BUILD file in the copy among them, + and `bazel run //:gazelle` writes a `BUILD.bazel` into the copy, after which the build in + `inner` fails as above. Unless `outer/.bazelignore` already names `inner`, add the line there + with the path from the outer root: `inner/.socket/vendor/golang`. +- A project patched by an earlier socket-patch gets its line from the next `scan` or `get` + that patches in the project's mode, `repair`, `rollback`, `remove` or `vendor --revert`, and + from `apply` or `vendor` where the project has a manifest (a project that is only vendored + has none, and both end before this step). A `scan` that writes nothing else (hosted mode with + nothing to pin, `patches.enabled: false` in `socket.yml`) does not write this file either, + and `list`, `vex` and the `--check` audits never do. So the first such command after an + upgrade changes `.bazelignore` in a workspace that already has a copy: commit it. The line + does not undo what gazelle wrote before: a gazelle run may have left a `BUILD.bazel` inside + the copy, and the build stays broken until that file is gone. In vendored mode the next + `scan --mode vendored` rebuilds the copy; in agent mode delete the `BUILD.bazel` files under + `.socket/go-patches` by hand. +- `scan --prune` removes vendored copies the project no longer uses after the scan's own step + has brought the file in line, and then takes away the pair of a copy it removed. A warning + the scan gave for that copy before is then out of date, and a file that pass cannot write is + reported by the next command. +- Two projects under one Bazel root share the file. Each command edits it under an advisory + lock on the root directory itself (no lock file is made anywhere, and a command with nothing + to change takes no lock), so commands that run at the same moment each keep their lines. + Without the lock (on Windows, where a directory cannot be locked this way; on a file system + without such locks; when the lock stays held for a second) a pair that one project adds while + another project's pair is removed can be lost until the next command in that project. Pairs + that are only added are safe without it: each is one write at the end of the file. A command + that fails after it removed a copy can leave the pair of that copy behind, which ignores + nothing; the next command removes it. +- A project directory whose path from the Bazel root starts with `#` or white space, or holds + `*`, `?` or `[`, cannot be named in `.bazelignore`: the line is written, and Bazel or gazelle + does not honour it. + ### Go workspaces (go.work) Every Go path (`apply`, `vendor`, `scan --mode hosted`, `vex`, `list`, diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index ca3759654..193eef887 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -1,5 +1,11 @@ { "groups": { + "bazel": { + "paths": [ + "crates/socket-patch-core/src/bazel/" + ], + "max": 192 + }, "lock-readers": { "paths": [ "crates/socket-patch-core/src/origin.rs",