From 6f85989f7c74550f01fa3d1388a4b6aeab6ad3e3 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 10:47:54 -0500 Subject: [PATCH 01/13] Test the vendored and agent Go flows through a gazelle run on real Bazel `scan --mode vendored` and agent mode (`scan --mode agent`, `apply`) patch a Go module by keeping a patched copy of it in the checkout, under `.socket/vendor/golang` or `.socket/go-patches`, and pointing `go.mod` at it with a directory `replace`. Only the hosted flow had a test on a real Bazel. This adds the two other modes for the same gazelle `go_deps` workspace, on Bazel 9.3.2, 8.8.2 and 7.7.2, and records what the code does there today. The next build is patched in both modes, and the undo is clean (`vendor --revert`) or leaves only the emptied `.socket/manifest.json` (`rollback`). The user's next step breaks the build: - `bazel run //:gazelle` writes a BUILD.bazel into the copy. 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'`. - When the module ships a BUILD file of its own, `bazel build //...` fails right after the command: the copy is a package of the checkout whose load of `@io_bazel_rules_go` nothing maps. Each test asserts that break by its error, so that the commit that fixes it has to change the expectation. The fixture gains a `gazelle` target, and its BUILD file is now the one gazelle writes, so a gazelle run on the unpatched checkout changes nothing and what a later run writes comes from the patch. Agent mode copies the module from the user's module cache; the test lays that directory out itself, so the runner needs no Go toolchain beyond the one rules_go downloads. gazelle is built from Go modules of its own: a flow that runs it has proxy.golang.org last in its GOPROXY list, after the stand-in that serves the module under test. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-go.yml | 14 +- .../tests/e2e_bazel_build/go.rs | 371 +++++++++++++++++- .../bazel/gazelle/bzlmod/common/BUILD.bazel | 16 +- 3 files changed, 378 insertions(+), 23 deletions(-) diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index f42bc6af0..c6dabb173 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`. 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..30115ea95 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,24 @@ //! 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::{changed, fixture_path, Cell, Fixture, Ran, StandIn, CONSUMER}; +use crate::hosted_memory_common::{Patch, ORG}; /// The workspace the test builds, and the rulesets each Bazel release /// builds it with. @@ -92,10 +103,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 +119,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(); @@ -361,6 +382,324 @@ 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\"], +) +"; + +/// 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"] + } +} + +/// 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. +fn grant_copy(standin: &StandIn, uuid: &str, copy: &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 reference = json!({ + "status": "granted", + "url": url, + "purl": PURL, + "artifacts": [{ "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 standin = StandIn::start(); + serve_module(&standin, PROXY, &upstream); + grant_copy(&standin, &uuid, ©, 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`, which exits 0 with the status + /// `success`. + fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + let modcache = self.modcache.path().to_str().expect("a UTF-8 path"); + let env = [("GOMODCACHE", modcache)]; + let ran = cell.socket_patch(&self.standin.origin(), args, &env); + 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 and the one `replace` line +/// of `go.mod`. +/// - (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: `bazel run //:gazelle` and a build, or, +/// for a module that ships a BUILD file, `bazel build //...`. The build +/// breaks here: 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 and the `replace` line, 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); + } + 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, and the one `replace` line. + 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, ["go.mod"], "{test}: {wrote:?}"); + 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 breaks the build. + let (build, sign) = if ships_build { + let sign = "No repository visible as '@io_bazel_rules_go'"; + (cell.bazel("build", &["//..."]), sign) + } else { + gazelle(&cell); + let wrote = changed(&pinned, &cell.tree()); + assert_eq!(wrote, [format!("{copy_dir}/BUILD.bazel")], "{test}"); + let sign = "No repository visible as '@rules_go'"; + (cell.bazel("build", &[CONSUMER]), sign) + }; + assert!( + !build.ok() && build.stderr().contains(sign), + "{test}: the build did not fail on {sign:?}:\n{}", + build.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}"); + + println!( + "{test}: Bazel {release} built {patched:?} from {copy_dir} after the command of the mode; \ + then the build failed ({sign}); the undo left {left:?} and the {UNPATCHED:?} build; {:?}", + started.elapsed() + ); +} + +/// `scan --mode vendored` for a module without a BUILD file. What the code +/// does today: the build is patched after the command; the user's +/// `bazel run //:gazelle` then writes a BUILD.bazel into the copy, and the +/// next build fails to load the module +/// (`No repository visible as '@rules_go'`); `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. What the code does today: the build is patched after the +/// commands; the user's `bazel run //:gazelle` then writes a BUILD.bazel +/// into the copy, and the next build fails to load the module +/// (`No repository visible as '@rules_go'`); `rollback` leaves the checkout +/// as it was before, 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. +/// What the code does today: `//:consumer` builds patched after the +/// command, and `bazel build //...` fails right away on the BUILD file in +/// the copy (`No repository visible as '@io_bazel_rules_go'`); +/// `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 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/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"], ) From cdf3a5fb679b58d176760c63c3a8b98ea8450e71 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 17 Nov 2026 15:00:46 -0500 Subject: [PATCH 02/13] Keep Go module copies under .socket out of Bazel packages Vendored and agent mode patch a Go module by keeping a copy of it under the project's `.socket` directory and pointing `go.mod` at it with a directory `replace`. In a Bazel workspace that copy is a directory Bazel and gazelle walk like any other. The next build is patched, and then the user's ordinary steps break it, on Bazel 9.3.2, 8.8.2 and 7.7.2 with gazelle's `go_deps`: - `bazel run //:gazelle` writes a BUILD.bazel into the copy, `go_deps` copies the directory with it, and every target that uses the module fails to load (`No repository visible as '@rules_go'`); - when the module ships a BUILD file of its own, `bazel build //...` fails right after the command. One line in the `.bazelignore` at the root of the workspace prevents both, and socket-patch now writes it. This is the first Bazel file socket-patch writes. Where it applies 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`. Those are the names Bazel's client looks for from the working directory up (`WorkspaceLayout::InWorkspace`, src/main/cpp/workspace_layout.cc line 36 at the tags 7.7.2, 8.8.2 and 9.3.2). The nearest such directory is the Bazel root; a directory of that name does not count. Without such a file nothing is read or written, and the run writes the same files as before, byte for byte. The checkout is the one `repo_root::find_git_repo` finds, and it counts only when its `.git` belongs to a trusted owner (`GitRepo::trusted`: the user, root, or the user sudo ran for; a root process trusts any), which is the rule the `socket.yml` lookup has for the repository root. Without it, another user's `/tmp/.git` and `/tmp/MODULE.bazel` on a shared machine would make a command in `/tmp/job/proj` create `/tmp/.bazelignore`. A project in no such checkout (a Docker build context, an unpacked source archive, a checkout of another user) is looked for in its own directory only: nothing above it is read, so a workspace file there gives no line and no warning. Neither does a Bazel root above the root of the checkout (a git submodule, several checkouts below one workspace): this repository reads no project file outside the checkout, so a look there could see the workspace file and not whether the line is in place, and its warning would never end. The nearest directory with a workspace file is the root. In a workspace that is nested in a larger one the line is therefore in the inner file, which a run from the outer workspace does not read. Measured on Bazel 9.3.2 with gazelle 0.54.0, outside the committed tests: from the outer root `bazel build //...` loads the packages of the inner tree, a BUILD file in the copy among them, and `bazel run //:gazelle` writes a BUILD.bazel into the copy, after which the inner build fails as above; with the line in the outer file, by its path from the outer root, neither happens. The writes are not widened for that. The docs name these limits and the line to add by hand. What is written - While `/.socket/vendor/golang` or `/.socket/go-patches` exists, the root's `.bazelignore` names it by its path from the 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 pair is added at the end of the file, in the file's line breaks, and the file is created when missing. Never `.socket` alone: other things live there. - Nothing is added when a line already covers the directory: the path or a directory above it, with or without a trailing `/` or a leading `./`. Bazel reads a line literally, so a line with a blank before or after it, a pattern or a string prefix covers nothing. - Nothing is added either when the user declined the pair: the comment line with the path line commented out under it (`#`, blanks, the path, which may end in one `/` or start with `./` as in a line that covers). No command adds a line for that directory, warns about it or touches the two lines again, on removal either. Deleting the pair is no opt-out: the next command writes it back. Neither is commenting out both lines, or a path line changed in another way. - socket-patch knows its pair by the start of the comment line, `# socket-patch:`, not by the whole sentence: a path line under a line that starts so is its own, and that path line commented out is the opt-out. A later release can reword the comment without leaving the pairs of this one behind. - Only a directory that is not found is gone. One that cannot be probed (a directory above it that may not be searched, a transient error) keeps its pair, and gets none. - Once the directory is gone the pair is removed, and the file is the one of before, byte for byte. A file whose last line has no line break gets a line break and the pair without a final one, and loses that line break again with the pair: exactly the one the comment line ends in, which is the one that was written before it, so that a last byte that is a carriage return on its own stays. Bazel and gazelle honour a last line without a line break: the agent test on real Bazel has one. A file left empty is deleted, an empty one the user had included: it cannot be told from one socket-patch created. Only a line under such a comment line is ever removed. - The line follows the directory, not the `replace`: `rollback --preserve-state` drops the `replace` and keeps the vendored copy, whose BUILD files would be back in the workspace without the line. - A read-only file is neither replaced nor deleted. The file is opened for appending before any change, a removal included, because a rename or an unlink succeeds in a writable directory. - A file that is not updated is the new warning `bazelignore_not_updated`: it could not be read or written (a directory or a symbolic link 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 succeeds as before. - A human run reads `Updated ` or `Removed ` on stdout when the file changed, once for each file, in words that hold for lines that came and for lines that went, and the warning on stderr. Under `--json` the warning is a run-level `warnings[]` entry; there is no new field. Which commands `commands::sync_bazelignore` is the one place the CLI asks for the file, behind one gate: not in a dry run and not in a `--global` run. Each command that can write or remove a copy calls it once, after its last step that can change a copy or take one back: `apply` (and with it `scan --mode agent` and `get`), the vendored step of `scan` and `get`, `vendor`, `vendor --revert`, `rollback`, `remove`, `repair` (also when it failed), and a hosted scan that took the lock, since a takeover removes the vendored copy. A hosted scan that took no lock may write nothing (`patches.enabled: false` in `socket.yml`, a rollout cap, no granted reference) and leaves this file alone too. The eject of a hosted project calls it after its rollback, so that an eject which vendored the Go module and was then rolled back leaves no pair for a copy that is gone again. `apply` and `vendor` in a project with no manifest end before that step. A run whose `--ecosystems` leaves `golang` out adds no line. It still takes away the pair of a copy that is gone, because `remove` of a Go patch and `vendor --revert` remove the Go copy whatever that option says. With a `--manifest-path` into another project the agent copies are those of `--cwd` and the vendored ones those of the manifest's project, so the helper brings the file of each project's Bazel root in line. `scan --prune` comes to the file a second time, after a pass that reverted a vendored entry or swept an orphan directory, which can remove the last copy after the scan's own step. That second call only takes a pair away: it adds no line and gives no warning, so the run warns once and no state is kept between the two. What it costs: a warning the scan's own step gave for a copy the pass then removed is out of date, and a file the pass cannot write is reported by the next command. The scan's own call cannot be left to that pass instead: the pass also follows the nested apply of `scan --mode agent --prune`, and it does not run at all when it cannot take the apply lock. The file is written after the commands' group commits, outside them: it is no part of a commit journal. A run that dies in between leaves a copy without its line, which the next command adds; a command that fails after it removed a copy can leave the pair behind, which ignores nothing, until the next command. A file several projects share Two projects under one Bazel root share the file, and each command holds only its own project's apply lock. So the edit, from its read to its write, is made under an advisory lock on the root directory itself: `fs2` on a handle to the directory, with contention told as the apply lock tells it (`apply_lock::is_lock_contended`). No lock file is made, in the workspace or anywhere else. A run that finds nothing to change takes no lock, also when the file cannot be read and the project has no copy to name in it. Where the directory cannot be locked (Windows, where it cannot be opened this way; a file system without such locks), or the lock stays held for a second, the edit is made without it: an add is still one appending write, which keeps what another project adds at that moment, and a removal replaces the file and can then lose such a pair until the next command in that project. With the lock, a removal in one project against an add in its sibling keeps the added pair in every one of 25 rounds of a unit test, which asserts that half on Unix only; without the lock that test fails. What a run costs The Bazel root and the bound of the checkout come from one walk up (`search_dirs`), which runs with the rest of the edit on the blocking pool. For a project outside a Bazel workspace, `d` directories below the root of its checkout, that is 2 path canonicalisations, `d + 2` stats of `.git` and `4 (d + 1)` stats of the four names, and nothing else. In a Bazel workspace it adds two stats of the copy directories and one read of `.bazelignore`; the lock and the write come only when something changes. (Counted from the code, not traced.) A side effect The line does more than keep gazelle out. Bazel leaves an ignored directory out of every `glob()` of a package above it (9.3.2, 8.8.2 and 7.7.2), so a target that hands the project's Go files to a `go` command of its own through such a glob no longer receives the copies. Built on Bazel 9.3.2 with a genrule that runs the Go SDK's `go build` over `glob(["**/*.go", "**/go.mod", "**/go.sum"])`, outside the committed tests: without the line it builds patched until the first `bazel run //:gazelle`, whose BUILD file in the copy takes the copy out of the glob in the same way, and then fails (`replacement directory ./.socket/vendor/golang/... does not exist`) together with every rules_go target that uses the module. With the line the rules_go targets build, and that genrule fails with the same error from the start; it builds when it names the copy's files as labels beside the glob, or runs outside the sandbox. A workspace that has such a target and never runs gazelle can decline the line as above. Not covered Only Go module copies get a line. Other ecosystems keep unpacked packages under `.socket/vendor/` too (a crate can ship a BUILD.bazel); nothing was measured for them under Bazel, so nothing is written for them. A BUILD file that gazelle wrote into a copy before the line existed stays there: the next `scan --mode vendored` rebuilds the copy, and in agent mode the BUILD files under `.socket/go-patches` have to be deleted by hand. A project directory whose path from the root starts with `#` or white space, or holds `*`, `?` or `[`, cannot be named in `.bazelignore`: its line is written, and Bazel or gazelle does not honour it. `ignore_directories` in REPO.bazel is not read; a workspace that has it gets the line too. Tests The real-Bazel tests now assert the fixed outcome: the build prints the patched marker after the command and `bazel build //...` passes, the two tests of a module without a BUILD file build it again after `bazel run //:gazelle`, which writes nothing, and the undo takes the line away. The agent test starts from a `.bazelignore` of the user's whose last line has no line break, and ends with that file as it was. Tests without Bazel hold: the root finder (each of the four names, a directory of such a name, a link, a file above the checkout, a checkout of an owner that is not trusted and a project in no checkout, which both reach no further than the project); the line rules (what covers, the opt-out and what is none, a pair under another wording of the comment, the pair in LF and CRLF files and after a last line without a line break, the removal that leaves the file of before, a last carriage return included, a run that leaves Go out); the write (appended to the file that is there, a read-only file and a link left alone on an add and on a removal, a copy directory that cannot be probed, the lock on the root directory and none where nothing can change); two edits at once; and through the built binary each command's call: that a dry run of ten commands writes nothing in either mode, that a declined pair stays declined over scan, repair, apply, rollback and revert, that a rolled-back eject leaves the project as it was, that a prune pass and a hosted takeover take the line away with the last copy, that `--ecosystems npm` adds no line and takes the pair of a copy it removed away, that a scan which `socket.yml` lets write nothing leaves the file alone in every mode, that a manifest in another project brings both files in line, that a file which cannot be written is one warning for each command (in the envelope, and on stderr for a scan whose prune pass comes to the file a second time), what a human run prints for lines that came, lines that went and a file that went, that a project in no git checkout below a Bazel root gets no line and no warning, and that the same run in a project with no Bazel workspace file writes the same files, byte for byte but for the time in a vendored copy's marker, and no `.bazelignore`. No test depends on what lies above the temp directory: they pass with it inside a git checkout and outside one. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-go.yml | 7 +- crates/socket-patch-cli/CLI_CONTRACT.md | 1 + crates/socket-patch-cli/src/commands/apply.rs | 3 + crates/socket-patch-cli/src/commands/mod.rs | 58 ++ .../socket-patch-cli/src/commands/remove.rs | 8 +- .../socket-patch-cli/src/commands/repair.rs | 4 + .../socket-patch-cli/src/commands/rollback.rs | 3 + .../src/commands/scan/hosted.rs | 7 + .../src/commands/scan/vendor_flow.rs | 2 + .../socket-patch-cli/src/commands/vendor.rs | 11 + .../tests/e2e_bazel_build/go.rs | 957 ++++++++++++++++-- .../tests/e2e_bazel_build/harness.rs | 43 +- .../tests/e2e_bazel_build/main.rs | 11 +- crates/socket-patch-core/src/bazel/ignore.rs | 849 ++++++++++++++++ crates/socket-patch-core/src/bazel/mod.rs | 158 +++ crates/socket-patch-core/src/lib.rs | 1 + .../socket-patch-core/src/utils/repo_root.rs | 2 +- .../src/vendor/go_mod_edit.rs | 2 +- docs/ecosystems.md | 112 ++ scripts/loc-budget.json | 6 + 20 files changed, 2165 insertions(+), 80 deletions(-) create mode 100644 crates/socket-patch-core/src/bazel/ignore.rs create mode 100644 crates/socket-patch-core/src/bazel/mod.rs diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index c6dabb173..e0e9afd8b 100644 --- a/.github/workflows/bazel-go.yml +++ b/.github/workflows/bazel-go.yml @@ -22,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, @@ -43,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 @@ -62,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 74e5e02d1..7dd4f11b8 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2328,6 +2328,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 04bb6a828..19c9ce81b 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1842,6 +1842,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 1a79c5247..6e27db106 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -1109,7 +1109,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 @@ -1851,6 +1855,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 d312d38ba..cdf0522a5 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -2641,6 +2641,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 2cd93365c..35bdbe0f3 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -2048,6 +2048,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())) @@ -2092,6 +2098,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 19c3557ef..c21ce9b7d 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 @@ -5320,6 +5326,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 30115ea95..ba452a93b 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -57,7 +57,9 @@ use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::envelope::find_event; -use crate::harness::{changed, fixture_path, Cell, Fixture, Ran, StandIn, CONSUMER}; +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 @@ -178,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, @@ -202,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]); } @@ -396,6 +403,10 @@ go_library( ) "; +/// 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)] @@ -434,25 +445,29 @@ impl Kept { }; ["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. -fn grant_copy(standin: &StandIn, uuid: &str, copy: &Module, lib: &[u8]) { +/// 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 reference = json!({ - "status": "granted", - "url": url, - "purl": PURL, - "artifacts": [{ "kind": "tarball", "url": url, "integrity": integrity }], - }); + 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(), @@ -503,9 +518,12 @@ impl Patching { 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); - grant_copy(&standin, &uuid, ©, lib.as_bytes()); + 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"); @@ -522,12 +540,25 @@ impl Patching { } } - /// `socket-patch ` in `cell`, which exits 0 with the status - /// `success`. - fn run(&self, cell: &Cell, args: &[&str]) -> Ran { + /// `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)]; - let ran = cell.socket_patch(&self.standin.origin(), args, &env); + 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); @@ -546,16 +577,21 @@ fn gazelle(cell: &Cell) { /// /// - (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 and the one `replace` line -/// of `go.mod`. +/// - (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: `bazel run //:gazelle` and a build, or, -/// for a module that ships a BUILD file, `bazel build //...`. The build -/// breaks here: 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 and the `replace` line, and +/// - (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(); @@ -586,6 +622,21 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { 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!( @@ -594,7 +645,8 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { "{test}" ); - // (b) The command of the mode: the copy, and the one `replace` line. + // (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); @@ -607,7 +659,8 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { .iter() .filter(|f| !f.starts_with(".socket/")) .collect(); - assert_eq!(outside, ["go.mod"], "{test}: {wrote:?}"); + 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"); @@ -618,22 +671,16 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { // (c) The next build is patched, from the copy. cell.builds_patched(&pinned, &patched); - // (d) The user's next step breaks the build. - let (build, sign) = if ships_build { - let sign = "No repository visible as '@io_bazel_rules_go'"; - (cell.bazel("build", &["//..."]), sign) - } else { + // (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); - let wrote = changed(&pinned, &cell.tree()); - assert_eq!(wrote, [format!("{copy_dir}/BUILD.bazel")], "{test}"); - let sign = "No repository visible as '@rules_go'"; - (cell.bazel("build", &[CONSUMER]), sign) - }; - assert!( - !build.ok() && build.stderr().contains(sign), - "{test}: the build did not fail on {sign:?}:\n{}", - build.dump() - ); + 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 { @@ -656,19 +703,23 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { 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; \ - then the build failed ({sign}); the undo left {left:?} and the {UNPATCHED:?} build; {:?}", + {next}; the undo left {left:?} and the {UNPATCHED:?} build; {:?}", started.elapsed() ); } -/// `scan --mode vendored` for a module without a BUILD file. What the code -/// does today: the build is patched after the command; the user's -/// `bazel run //:gazelle` then writes a BUILD.bazel into the copy, and the -/// next build fails to load the module -/// (`No repository visible as '@rules_go'`); `vendor --revert` leaves the -/// checkout as it was before the command. +/// `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() { @@ -676,11 +727,12 @@ fn vendored_go_deps() { } /// Agent mode (`scan --mode agent`, then `apply`) for a module without a -/// BUILD file. What the code does today: the build is patched after the -/// commands; the user's `bazel run //:gazelle` then writes a BUILD.bazel -/// into the copy, and the next build fails to load the module -/// (`No repository visible as '@rules_go'`); `rollback` leaves the checkout -/// as it was before, but for the emptied `.socket/manifest.json`. +/// 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() { @@ -688,11 +740,10 @@ fn agent_go_deps() { } /// `scan --mode vendored` for a module that ships a BUILD file of its own. -/// What the code does today: `//:consumer` builds patched after the -/// command, and `bazel build //...` fails right away on the BUILD file in -/// the copy (`No repository visible as '@io_bazel_rules_go'`); -/// `vendor --revert` leaves the checkout as it was before the command. This -/// test runs no gazelle. +/// 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() { @@ -700,6 +751,784 @@ fn 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 3d23f1b6d..b1d88b0c1 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -736,6 +736,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 { @@ -870,18 +875,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) @@ -893,6 +898,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); @@ -908,6 +921,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> { @@ -971,8 +997,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 ccf843414..37df7b056 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-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 317516802..62b73f26b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1634,6 +1634,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", From f67ab5402d667d2f22943cbdfcf04fefcee1a146 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 13:42:19 -0500 Subject: [PATCH 03/13] Assert the VEX document in the Bazel flows that build patched `vex` and `--vex` read what socket-patch wrote and what the project's package manager installed. They read no Bazel file, so under Bazel a document can say `not_affected` for a package Bazel builds unpatched. Before the product learns to tell, this records where the document and the build agree today. It changes tests, one docs section and four workflow path lists; no file under `crates/*/src`. Each of the eight real-Bazel flows whose build is patched (Go hosted, vendored, agent, and vendored with a module that ships a BUILD file; npm hosted and vendored; PyPI hosted; RubyGems hosted) now also asserts: - the command of the mode, given `--vex`, writes the document of its own run in the checkout Bazel has built in; - `vex` writes one before the patched build and one after it, and one with `--no-verify`; - after the undo `vex` writes none and removes the last: exit 2 `manifest_not_found`, or exit 1 `no_patches` after an agent rollback, which keeps its emptied manifest; - the command and `vex` write the same two documents in a checkout that no Bazel has built in, whose files outside `.socket/` are those of the checkout that built patched. A document is held to one statement: `not_affected`, `inline_mitigations_already_exist`, the advisory of the record, the package as the one subcomponent of the product, and `Patched via Socket patch ` with the id of this run, ` (redirected)` or ` (vendored)` by mode, and `; not verified on disk` exactly under `--no-verify`. The envelope is held to its exact warnings. Agent mode's `apply --vex` and the second scan of the npm flows are held to the same. All of it passes on Bazel 9.3.2, 8.8.2 and 7.7.2 (macOS arm64) as the product is: no expectation had to follow a wrong document. One thing a reader of such a document should know is now asserted. For a hosted pin no form hashes a file, since the bytes come with the next build and `vex` never reads Bazel's output: the statement rests on the lock entry and the patch record. The scan says so (`vex_hosted_unverified` in `vex.warnings`); stand-alone `vex` gives no warning, before the build or after it. The added socket-patch runs take 0.2 to 0.5 seconds per flow. `e2e_vex_lockfile/bazel_beside.rs` holds what later changes must keep. A pnpm project in `web/`, beside a root `MODULE.bazel` or `WORKSPACE` that builds Java and names none of its files, gets from `vex --json`, `vex` and `apply --vex` the exit code, both streams and the document it gets without Bazel, byte for byte but for the checkout's path, the document id and the time, for a hosted pin and for an installed patch. With Bazel files that do name the project's lock the output is the same today as well (tried, not kept): that is the case later work changes. In the harness a VEX document goes beside the workspace copy, so no comparison of a checkout's files sees one, and `Cell::twin` is a shutdown plus the new `Cell::unbuilt`. The push paths of the four Bazel workflows gain `crates/socket-patch-core/src/vex/**`. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-go.yml | 1 + .github/workflows/bazel-npm.yml | 1 + .github/workflows/bazel-pypi.yml | 1 + .github/workflows/bazel-ruby.yml | 1 + .../tests/e2e_bazel_build/go.rs | 66 ++++- .../tests/e2e_bazel_build/harness.rs | 244 +++++++++++++++++- .../tests/e2e_bazel_build/main.rs | 11 + .../tests/e2e_bazel_build/npm.rs | 79 +++--- .../tests/e2e_bazel_build/pypi.rs | 24 +- .../tests/e2e_bazel_build/ruby.rs | 25 +- .../tests/e2e_vex_lockfile/bazel_beside.rs | 208 +++++++++++++++ .../tests/e2e_vex_lockfile/main.rs | 1 + docs/ecosystems.md | 32 +++ 13 files changed, 642 insertions(+), 52 deletions(-) create mode 100644 crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index e0e9afd8b..e940d5f3e 100644 --- a/.github/workflows/bazel-go.yml +++ b/.github/workflows/bazel-go.yml @@ -69,6 +69,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' + - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index ec106bc7c..35f945467 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -97,6 +97,7 @@ on: - 'crates/socket-patch-core/src/vendor/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' + - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index bbacdb4ed..48ec24d21 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -104,6 +104,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' + - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index b11dcde9c..0686db0e1 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -87,6 +87,7 @@ on: - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' + - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' 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 ba452a93b..3a0589fbc 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -29,7 +29,9 @@ //! 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. +//! id made for the run, so no cache of an earlier run can supply it. Each +//! flow asserts the VEX document of its patch as `main.rs` says; agent mode +//! also has its `apply` write one. //! //! One loopback server stands in for four hosts, by route prefix: the //! Socket API, `proxy.golang.org` (the upstream module), `patch.socket.dev` @@ -58,7 +60,8 @@ use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; use crate::envelope::find_event; use crate::harness::{ - cell_without_bazel, changed, fixture_path, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, + cell_without_bazel, changed, fixture_path, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, + Tree, CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -304,7 +307,10 @@ fn hosted_go_deps() { // (b) The one command of hosted mode. It rewrites those two files and // no other: the one `replace` line, and the two sums of the Socket // module in place of the upstream module's. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let in_run = cell.document("in-run"); + let scan = socket_patch(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &["go.mod", "go.sum"]); let text = |rel: &str| String::from_utf8(pinned[rel].clone()).expect("a text file"); @@ -315,6 +321,10 @@ fn hosted_go_deps() { let mut sums: Vec<&str> = go_sum.lines().collect(); sums.sort_unstable(); assert_eq!(sums, socket.go_sum(), "{test}: go.sum:\n{go_sum}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the Socket module. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(socket_patch, &claim, true); assert_eq!(standin.asked(&socket_zip), 0, "{test}: {said}"); // (c) The same build, no step in between: patched, from the patch @@ -330,10 +340,18 @@ fn hosted_go_deps() { upstream_fetches, "{test}: the patched build fetched the upstream module" ); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(socket_patch, &claim, true); + cell.stands_alone(socket_patch, &claim, false); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, UNPATCHED); + cell.attests_nothing(socket_patch, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(socket_patch, &hosted, &before, &pinned, &claim); // (e) A second machine with the rewritten files, and a patch host that // serves other bytes at the pinned URL: still a module zip `go` @@ -437,6 +455,14 @@ impl Kept { } } + /// What a VEX document says of a patch of the mode. + fn how(self) -> How { + match self { + Kept::Vendored => How::Vendored, + Kept::Agent => How::Agent, + } + } + /// The command of the mode. fn scan(self) -> [&'static str; 4] { let mode = match self { @@ -647,11 +673,17 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { // (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 claim = Claim::new(PURL, &with.uuid, mode.how()); + let run = |cell: &Cell, args: &[&str]| with.ran(cell, args); + let in_run = cell.document("in-run"); + let scan = with.run(&cell, &[&mode.scan()[..], &with_vex(&in_run)].concat()); let event = find_event(&scan.envelope, "applied", None); assert_eq!(event["purl"], PURL, "{test}: {}", scan.dump); + cell.wrote_in_run(&scan, &in_run, &claim); if mode == Kept::Agent { - with.run(&cell, &["apply"]); + let again = cell.document("apply"); + let apply = with.run(&cell, &[&["apply"][..], &with_vex(&again)].concat()); + cell.wrote_in_run(&apply, &again, &claim); } let pinned = cell.tree(); let wrote = changed(&before, &pinned); @@ -667,9 +699,13 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { 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}"); + cell.stands_alone(run, &claim, true); - // (c) The next build is patched, from the copy. + // (c) The next build is patched, from the copy, and `vex` says so; with + // `--no-verify` it says that it checked no file. cell.builds_patched(&pinned, &patched); + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); // (d) The user's next step: gazelle writes nothing into the copy, the // build stays patched, and no package of the checkout is under @@ -682,13 +718,20 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { 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", &[]), + // (e) The undo. An agent rollback keeps its emptied manifest, which + // `vex` then finds empty, where the other undo leaves it none to find. + let (undo, counted, left, nothing): (&[&str], &str, &[&str], (i32, &str)) = match mode { + Kept::Vendored => ( + &["vendor", "--revert", "--yes"], + "removed", + &[], + (2, "manifest_not_found"), + ), Kept::Agent => ( &["rollback", "--yes"], "rolledBack", &[".socket/manifest.json"], + (1, "no_patches"), ), }; let undo = with.run(&cell, undo); @@ -702,6 +745,9 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { ); cell.builds(UNPATCHED); assert_eq!(changed(&before, &cell.tree()), left, "{test}"); + cell.attests_nothing(run, nothing.0, nothing.1); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &mode.scan(), &before, &pinned, &claim); let next = if ships_build { "`bazel build //...` passed" 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 b1d88b0c1..dbe30b3d3 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -15,7 +15,9 @@ use serde_json::{json, Value}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; -use crate::envelope::event_for; +use socket_patch_core::utils::purl::normalize_purl; + +use crate::envelope::{codes_in, event_for, events}; use crate::fs_tree; use crate::hosted_memory_common::hermetic::{self, Extra}; use crate::hosted_memory_common::{mount_api, read_tree, Patch, ORG}; @@ -111,6 +113,65 @@ pub type Tree = BTreeMap>; /// What [`changed`] gives for two equal trees. pub const NOTHING: [&str; 0] = []; +/// The product every form of `vex` is told: no flow depends on what its +/// fixture lets `socket-patch` detect one from, and the PyPI and the +/// RubyGems fixture have no project file. +const PRODUCT: &str = "pkg:generic/socket-fixture@0.0.0"; + +/// The advisory of every patch record a flow is served: the one of the +/// shared API stand-in, and of the records a flow writes itself. +const ADVISORY: &str = "GHSA-test-aaaa-bbbb"; + +/// The mode a flow patched its package in, which a document says after the +/// patch id. +#[derive(Clone, Copy)] +pub enum How { + Hosted, + Vendored, + Agent, +} + +impl How { + fn words(self) -> &'static str { + match self { + How::Hosted => " (redirected)", + How::Vendored => " (vendored)", + How::Agent => "", + } + } +} + +/// What a document has to say: the package `purl` is not affected, through +/// the patch `uuid` of this run. The id is new for every run, so no +/// document of an earlier run says it. +pub struct Claim<'a> { + pub purl: &'a str, + pub uuid: &'a str, + pub how: How, +} + +impl<'a> Claim<'a> { + pub fn new(purl: &'a str, uuid: &'a str, how: How) -> Claim<'a> { + Claim { purl, uuid, how } + } +} + +/// `path` as an argument of `socket-patch`. +fn argument(path: &Path) -> &str { + path.to_str().expect("a UTF-8 path") +} + +/// The stand-alone `vex` that writes its document to `path`. +fn vex(path: &Path) -> [&str; 5] { + ["vex", "--output", argument(path), "--product", PRODUCT] +} + +/// What a `scan` or an `apply` is given to write the document of its own +/// run to `path`. +pub fn with_vex(path: &Path) -> [&str; 4] { + ["--vex", argument(path), "--vex-product", PRODUCT] +} + /// `name`'s value when it is set and non-empty. fn var(name: &str) -> Option { std::env::var_os(name).filter(|value| !value.is_empty()) @@ -273,6 +334,9 @@ struct Scratch { /// The downloader config, which only [`Cell::route_downloads`] writes. /// Beside the workspace copy, so it is no file of the checkout. downloads: PathBuf, + /// The VEX documents of a flow ([`Cell::document`]), beside the + /// workspace copy for the same reason. + documents: PathBuf, /// Removed on drop, after [`Scratch::drop`] made it removable. dir: tempfile::TempDir, } @@ -302,6 +366,7 @@ impl Scratch { repository_cache: made(repository_cache.unwrap_or_else(|| root.join("cache"))), contents_cache: made(root.join("contents")), downloads: root.join("downloader.cfg"), + documents: made(root.join("vex")), dir, } } @@ -697,7 +762,16 @@ impl Cell { if let Err(why) = self.shutdown() { panic!("{}: {why}", self.test); } - let mut twin = Cell { + self.unbuilt(&self.tree()) + } + + /// A checkout that no Bazel has built in: `files` in a workspace copy + /// of its own, which has no output base and none of Bazel's `bazel-*` + /// links, with the settings of this cell. Nothing but `socket-patch` + /// runs in it unless the caller builds there ([`Cell::twin`]), so this + /// cell's server keeps running. + pub fn unbuilt(&self, files: &Tree) -> Cell { + let mut copy = Cell { test: self.test.clone(), repo_env: self.repo_env.clone(), bazel: self.bazel.clone(), @@ -706,14 +780,14 @@ impl Cell { downloads: None, scratch: Scratch::new(Some(self.scratch.repository_cache.clone())), }; - for (rel, bytes) in self.tree() { - twin.write(&rel, bytes); + for (rel, bytes) in files { + copy.write(rel, bytes); } - std::fs::create_dir(twin.scratch.workspace.join(".git")).expect("create .git"); + std::fs::create_dir(copy.scratch.workspace.join(".git")).expect("create .git"); if let Some(rules) = &self.downloads { - twin.route_downloads(rules); + copy.route_downloads(rules); } - twin + copy } /// Send the downloads of Bazel's own downloader where `rules` say: the @@ -934,6 +1008,144 @@ impl Cell { [out.stdout, out.stderr].map(|stream| String::from_utf8_lossy(&stream).into_owned()) } + /// Where a flow has `socket-patch` write the VEX document `name`: + /// beside the workspace copy, so it is no file of the checkout, and no + /// comparison of the checkout's files sees it. + pub fn document(&self, name: &str) -> PathBuf { + self.scratch.documents.join(format!("{name}.vex.json")) + } + + /// The document at `path` says `claim` and nothing else: one statement, + /// `not_affected` for the one advisory, with the package as the one + /// subcomponent of the one product and the patch of this run in its + /// impact statement, which ends with `; not verified on disk` exactly + /// when the run did not check the files (`verified` is false). + fn attests(&self, path: &Path, claim: &Claim, verified: bool) { + let test = &self.test; + let text = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("{test}: no document {}: {e}", path.display())); + let document: Value = serde_json::from_str(&text) + .unwrap_or_else(|e| panic!("{test}: no JSON ({e}):\n{text}")); + let context = "https://openvex.dev/ns/v0.2.0"; + assert_eq!(document["@context"], context, "{test}: {text}"); + let statements = document["statements"].as_array(); + let Some([statement]) = statements.map(Vec::as_slice) else { + panic!("{test}: not one statement:\n{text}"); + }; + assert_eq!(statement["status"], "not_affected", "{test}: {text}"); + let justification = "inline_mitigations_already_exist"; + assert_eq!(statement["justification"], justification, "{test}: {text}"); + let advisory = &statement["vulnerability"]["name"]; + assert_eq!(*advisory, ADVISORY, "{test}: {text}"); + // The package is named as its record names it: with `%40` or with + // `@` for the scope of an npm name. + let named = statement["products"][0]["subcomponents"][0]["@id"].as_str(); + let named = named.unwrap_or_default(); + let purl = normalize_purl(claim.purl); + assert_eq!(normalize_purl(named), purl, "{test}: {text}"); + let products = json!([{ "@id": PRODUCT, "subcomponents": [{ "@id": named }] }]); + assert_eq!(statement["products"], products, "{test}: {text}"); + let (uuid, how) = (claim.uuid, claim.how.words()); + let mut impact = format!("Patched via Socket patch {uuid}{how}"); + if !verified { + impact += "; not verified on disk"; + } + assert_eq!(statement["impact_statement"], impact, "{test}: {text}"); + } + + /// The stand-alone `vex` of this checkout, through `run`, the flow's way + /// to run `socket-patch` in a cell. It attests `claim` and nothing + /// else, in its envelope and in the document it writes, which is not + /// the one of an earlier call. `verified` is false for + /// `vex --no-verify`, which says in a warning, and in the document, + /// that it checked no file. + pub fn stands_alone(&self, run: impl Fn(&Cell, &[&str]) -> Ran, claim: &Claim, verified: bool) { + let path = self.document("stand-alone"); + let _ = std::fs::remove_file(&path); + let unchecked: &[&str] = if verified { &[] } else { &["--no-verify"] }; + let ran = run(self, &[&vex(&path), unchecked].concat()); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "success", "{test}: {said}"); + let [event] = events(&ran.envelope) else { + panic!("{test}: not one event: {said}"); + }; + assert_eq!(event["action"], "verified", "{test}: {said}"); + let purl = normalize_purl(event["purl"].as_str().unwrap_or_default()); + assert_eq!(purl, normalize_purl(claim.purl), "{test}: {said}"); + let details = &event["details"]; + assert_eq!(details["status"], "not_affected", "{test}: {said}"); + assert_eq!(details["vulnerability"], ADVISORY, "{test}: {said}"); + let warned: &[&str] = if verified { &[] } else { &["vex_not_verified"] }; + let warnings = codes_in(&ran.envelope["warnings"]); + assert_eq!(warnings, warned, "{test}: {said}"); + self.attests(&path, claim, verified); + } + + /// For a finished command that was given [`with_vex`] for `path`: it + /// passed, and wrote the document of its own run, which attests + /// `claim` and nothing else. A hosted scan says of its document that + /// no file was hashed for it: the lock names the patch, and the bytes + /// come with the next build. + pub fn wrote_in_run(&self, ran: &Ran, path: &Path, claim: &Claim) { + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, 0, "{test}: {said}"); + let vex = &ran.envelope["vex"]; + assert_eq!(vex["statements"], 1, "{test}: {said}"); + assert_eq!(vex["format"], "openvex-0.2.0", "{test}: {said}"); + assert_eq!(vex["path"], argument(path), "{test}: {said}"); + let warned: &[&str] = match claim.how { + How::Hosted => &["vex_hosted_unverified"], + How::Vendored | How::Agent => &[], + }; + assert_eq!(codes_in(&vex["warnings"]), warned, "{test}: {said}"); + self.attests(path, claim, true); + } + + /// The same two documents from a checkout that no Bazel has built in: + /// one with the files `before`, where `command`, the command of the + /// mode, applies the patch and writes the document of its run, and the + /// stand-alone `vex` writes its own. The command leaves the files + /// `patched`, those the patched build started from (only the marker + /// of a vendored copy differs: it holds the time of its run), so both + /// checkouts attest the same files. + pub fn attests_unbuilt( + &self, + run: impl Fn(&Cell, &[&str]) -> Ran, + command: &[&str], + before: &Tree, + patched: &Tree, + claim: &Claim, + ) { + let fresh = self.unbuilt(before); + let in_run = fresh.document("in-run"); + let ran = run(&fresh, &[command, &with_vex(&in_run)].concat()); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.envelope["summary"]["applied"], 1, "{test}: {said}"); + fresh.wrote_in_run(&ran, &in_run, claim); + let mut differ = changed(patched, &fresh.tree()); + // The marker of a vendored copy holds the time of its run. + differ.retain(|file| !file.ends_with("/socket-patch.vendor.json")); + assert_eq!(differ, NOTHING, "{test}: {said}"); + fresh.stands_alone(run, claim, true); + } + + /// The stand-alone `vex` of a checkout that holds no patch any more, + /// through `run`: it exits `code` with the error `error` and leaves no + /// document, and says that it removed the one [`Cell::stands_alone`] + /// left. + pub fn attests_nothing(&self, run: impl Fn(&Cell, &[&str]) -> Ran, code: i32, error: &str) { + let path = self.document("stand-alone"); + let ran = run(self, &vex(&path)); + let (test, said) = (&self.test, &ran.dump); + assert_eq!(ran.code, code, "{test}: {said}"); + assert_eq!(ran.envelope["error"]["code"], error, "{test}: {said}"); + assert!(!path.exists(), "{test}: a document is left: {said}"); + let warned = codes_in(&ran.envelope["warnings"]); + let removed = warned.iter().any(|code| code == "vex_stale_doc_removed"); + assert!(removed, "{test}: {said}"); + } + /// `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> { @@ -1057,6 +1269,24 @@ fn a_downloader_config_is_named_by_the_option_of_the_release() { } } +/// Without a Bazel: a document is no file of the checkout it is about, nor +/// of a checkout made from it, which has documents of its own. +#[test] +fn a_document_is_no_file_of_the_checkout() { + let cell = cell_without_bazel("9.3.2"); + cell.write("MODULE.bazel", ""); + let fresh = cell.unbuilt(&cell.tree()); + assert_eq!(changed(&cell.tree(), &fresh.tree()), NOTHING); + let documents = [cell.document("one"), fresh.document("one")]; + assert_ne!(documents[0], documents[1]); + for document in &documents { + assert!(document.parent().is_some_and(Path::is_dir), "{document:?}"); + for copy in [&cell, &fresh] { + assert!(!document.starts_with(©.scratch.workspace)); + } + } +} + /// Set in the copy of this test binary that the next test starts, which /// then plays the shell of a developer. const PLAYS_THE_SHELL: &str = "SOCKET_PATCH_BAZEL_E2E_PLAYS_THE_SHELL"; 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 37df7b056..c44e4000e 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -31,6 +31,17 @@ //! `SOCKET_PATCH_BAZEL_E2E_REQUIRED=1` (CI) it fails instead. `harness.rs` //! lists the other variables. //! +//! Every flow whose build is patched also holds `socket-patch` to the VEX +//! document it writes about that build. The command of the mode writes one +//! for its own run (`--vex`), in the checkout Bazel has built in; `vex` +//! writes one before the patched build and after it, and one with +//! `--no-verify`; after the undo `vex` writes none and removes the last; +//! and the command and `vex` write the same two in a checkout with the +//! same files that no Bazel has built in. Each document is one statement: +//! the package under test is `not_affected`, through the patch of this +//! run. Nothing in `socket-patch` reads a Bazel file for it, so these tests +//! say for which workspaces the document and the build agree. +//! //! A flow is one `#[ignore]`d test in its ecosystem's module, and its //! fixture is one directory of files that every release builds beside one //! `MODULE.bazel` per era of rulesets; the fixture's table in the test code diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index f97459091..ffa54c242 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -39,8 +39,9 @@ //! root included, where the checkout's `package.json` shows up again: //! both commands see the package as they do in a checkout without the //! links. The hosted scan reports the patch applied again and the -//! vendored one reports it `already_vendored`, `vex` attests the package, -//! no file changes, and the build is still the patched one. +//! vendored one reports it `already_vendored`, each writes the VEX +//! document of its run, `vex` attests the package, no file changes, and +//! the build is still the patched one. //! - (d) The undo (`rollback --yes`, or `vendor --revert`): every file of //! the checkout is the one of before, byte for byte, and the build prints //! the unpatched marker again. @@ -50,6 +51,8 @@ //! or they replace the committed file (vendored). The build fails on the //! checksum and does not take the registry's tarball in its place. //! +//! Both flows assert the VEX document of their patch as `main.rs` says. +//! //! A marker is read from what Bazel built. Bazel's downloader keeps every //! file it fetches in the repository cache, under its checksum, and hands it //! out again without a request; the tests of a leg share that cache, and CI @@ -83,7 +86,8 @@ use socket_patch_core::utils::purl::canonical_purl; use crate::envelope::event_triples; use crate::harness::{ - changed, fixture_path, rewrite, Cell, Fixture, Ran, Run, StandIn, Tree, CONSUMER, NOTHING, + changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, Run, StandIn, Tree, + CONSUMER, NOTHING, }; use crate::hosted_memory_common::{Patch, ORG}; @@ -406,15 +410,16 @@ fn second_machine( /// built in and that holds the files of `patched`. Beside Bazel's links, /// `scan --mode --yes` scans the package and reports the one event /// `seen` for it (an action and an error code), which is what it reports in -/// a checkout without those links; `vex` attests the package in its -/// document; no file of the checkout changes; and the build still prints -/// `marker`. +/// a checkout without those links; the document of that run, and those of +/// `vex` and of `vex --no-verify`, attest `claim`; no file of the checkout +/// changes; and the build still prints `marker`. fn runs_again( cell: &Cell, standin: &StandIn, mode: &str, seen: (&str, &str), patched: &Tree, + claim: &Claim, marker: &str, ) { let test = &cell.test; @@ -430,30 +435,22 @@ fn runs_again( } let one = |action: &str, code: &str| [(canonical_purl(PURL), action.into(), code.into())]; - let scan = socket_patch(cell, standin, &["scan", "--mode", mode, "--yes"]); + let again = cell.document("again"); + let scan = ["scan", "--mode", mode, "--yes"]; + let scan = socket_patch(cell, standin, &[&scan[..], &with_vex(&again)].concat()); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); let seen = one(seen.0, seen.1); assert_eq!(reported(&scan.envelope), seen, "{test}: {said}"); assert_eq!(scan.envelope["scannedPackages"], 1, "{test}: {said}"); + cell.wrote_in_run(&scan, &again, claim); - // The document goes beside the checkout, into the scratch root of the - // cell, where nothing has that name: it is no file of the checkout, and - // none of the machine's shared temp directory. - let document = checkout.parent().expect("a scratch root").join("vex.json"); - assert!(!document.exists(), "{test}: {}", document.display()); - let output = document.to_string_lossy(); - let vex = socket_patch(cell, standin, &["vex", "--output", &output]); - let said = &vex.dump; - assert_eq!(vex.code, 0, "{test}: {said}"); - let attested = one("verified", ""); - assert_eq!(reported(&vex.envelope), attested, "{test}: {said}"); - let written = std::fs::read_to_string(&document).unwrap_or_default(); - // With its closing quote, as the document writes `"@id": ""`: a - // longer version that only starts so is another package. - let names = written.contains(&format!("\"{PURL}\"")); - assert!(names, "{test}: {said}\n{written}"); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, args); + cell.stands_alone(run, claim, true); + cell.stands_alone(run, claim, false); assert_eq!(changed(patched, &cell.tree()), NOTHING, "{test}"); cell.builds_patched(patched, marker); @@ -507,7 +504,11 @@ fn hosted_npm_translate_lock() { // (b) The one command of hosted mode. It rewrites those two files and // no other: the entry of the package names the patched tarball, by its // sum and by its URL on the patch host. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &patch.uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let written = [LOCK, "pnpm-workspace.yaml"]; let pinned = cell.pinned_by(&scan, PURL, &patch.uuid, &before, &written); let lock = text(&pinned, LOCK); @@ -519,6 +520,10 @@ fn hosted_npm_translate_lock() { assert!(lock.contains(&entry), "{test}: {LOCK}:\n{lock}"); let workspace = text(&pinned, "pnpm-workspace.yaml"); assert_eq!(workspace, TRUSTING_WORKSPACE, "{test}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before the patched build. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); // (c) The same build, no step in between: patched, from the patch host. let patched_fetches = standin.asked(&patch.route); @@ -530,11 +535,15 @@ fn hosted_npm_translate_lock() { // The same command and `vex`, now that Bazel has built in the checkout. let (seen, marker) = (("applied", ""), &patch.package.marker); - runs_again(&cell, &standin, "hosted", seen, &pinned, marker); + runs_again(&cell, &standin, "hosted", seen, &pinned, &claim, marker); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &standin, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, &upstream.marker); + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &hosted, &before, &pinned, &claim); // (e) A second machine, a second patch, and a patch host that serves // other bytes at the URL the lock pins: still a tarball of the package, @@ -583,7 +592,11 @@ fn vendored_npm_translate_lock() { let before = builds_upstream(&cell, &standin, &upstream); // (b) The one command of vendored mode. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "vendored", "--yes"]); + let vendoring = ["scan", "--mode", "vendored", "--yes"]; + let claim = Claim::new(PURL, &patch.uuid, How::Vendored); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&vendoring[..], &with_vex(&in_run)].concat()); let said = &scan.dump; assert_eq!(scan.code, 0, "{test}: {said}"); assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); @@ -622,6 +635,10 @@ fn vendored_npm_translate_lock() { assert_eq!(*overridden, format!("file:{copy}"), "{test}: {manifest:#}"); let workspace = text(&vendored, "pnpm-workspace.yaml"); assert_eq!(workspace, overriding_workspace(©), "{test}"); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before the patched build. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); // (c) The same build, no step in between: patched, from the committed // file. Bazel asks the stand-in for nothing. @@ -631,11 +648,15 @@ fn vendored_npm_translate_lock() { // The same command and `vex`, now that Bazel has built in the checkout. let (seen, marker) = (("skipped", "already_vendored"), &patch.package.marker); - runs_again(&cell, &standin, "vendored", seen, &vendored, marker); + runs_again(&cell, &standin, "vendored", seen, &vendored, &claim, marker); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &standin, &["vendor", "--revert"]); cell.undone(&undo, "removed", &before, &upstream.marker); + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &vendoring, &before, &vendored, &claim); // (e) A second machine and a second patch, vendored there, and then // other bytes in the committed file: still a tarball of the package, diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index b88838988..3f17432b6 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -39,7 +39,8 @@ //! grant pins: after the same `scan`, the build fails on the sha256. //! //! 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. +//! id made for the run, so no cache of an earlier run can supply it. The +//! flow asserts the VEX document of its patch as `main.rs` says. //! //! One loopback server stands in for four hosts. The Socket API and the //! patch host answer at their own paths; `pypi.org` (the project pages of @@ -81,7 +82,8 @@ use base64::Engine as _; use serde_json::{json, Value}; use crate::harness::{ - changed, fixture_path, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, + changed, fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, Tree, + CONSUMER, NOTHING, }; use crate::hosted_memory_common::Patch; @@ -397,7 +399,11 @@ fn hosted_pip_parse() { // (b) The one command of hosted mode. It rewrites that file and no // other: the pin of the dependency as it was, and the package as a // direct reference to the patched wheel with its sha256. - let scan = socket_patch(&cell, &standin, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, args); + let in_run = cell.document("in-run"); + let scan = run(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &[REQUIREMENTS]); let direct = format!("{NAME} @ {origin}{patched_route}"); @@ -410,6 +416,10 @@ fn hosted_pip_parse() { ), "{test}" ); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the patched wheel. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(run, &claim, true); assert_eq!(standin.asked(&patched_route), 0, "{test}: {said}"); let index_requests = standin.asked(&page); // The scan left Bazel's lock as it was, so a frozen lock fails here @@ -435,6 +445,10 @@ fn hosted_pip_parse() { // From here on the checkout stands: the next build changes no file, // and that lock holds when Bazel may not update it. cell.builds_patched(&built, &marker); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(run, &claim, true); + cell.stands_alone(run, &claim, false); // (d) The undo: `requirements.txt` is the one of before at once, and // the lock is still the one of the patched build, so a frozen lock @@ -461,6 +475,10 @@ fn hosted_pip_parse() { standin.asked(&page) > index_requests, "{test}: the build after the undo did not ask the index about {NAME}" ); + // `vex` has no document for the checkout of before. + cell.attests_nothing(run, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(run, &hosted, &before, &pinned, &claim); // (e) A second machine. Bazel keeps a download that has a checksum in // the repository cache, which the two machines share, so this one gets diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index bdb225970..b000b0dd4 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -24,6 +24,8 @@ //! patch registry that serves other bytes fails the build, and the //! upstream gem is not fetched in its place. //! +//! The flow asserts the VEX document of its patch as `main.rs` says. +//! //! Both markers are read from what Bazel built, and each holds an id made //! for the run, so no cache of an earlier run can supply either gem. The //! fixture's lock therefore holds no sha256 of a gem: it has a placeholder @@ -66,7 +68,9 @@ use std::time::Instant; use serde_json::json; use sha2::{Digest, Sha256}; -use crate::harness::{fixture_path, rewrite, Cell, Fixture, StandIn, CONSUMER}; +use crate::harness::{ + fixture_path, rewrite, with_vex, Cell, Claim, Fixture, How, StandIn, CONSUMER, +}; use crate::hosted_memory_common::Patch; /// The sha256 of `bytes` in lowercase hex, as a `Gemfile.lock` and the gem @@ -288,7 +292,10 @@ fn hosted_bundle_fetch() { // no other: the declaration gains the patch registry as its source, and // the lock resolves the gem from it, in a section of its own, with the // sha256 of the patched gem. - let scan = socket_patch(&cell, &["scan", "--mode", "hosted", "--yes"]); + let hosted = ["scan", "--mode", "hosted", "--yes"]; + let claim = Claim::new(PURL, &uuid, How::Hosted); + let in_run = cell.document("in-run"); + let scan = socket_patch(&cell, &[&hosted[..], &with_vex(&in_run)].concat()); let said = &scan.dump; let pinned = cell.pinned_by(&scan, PURL, &uuid, &before, &["Gemfile", "Gemfile.lock"]); let text = |rel: &str| String::from_utf8(pinned[rel].clone()).expect("a text file"); @@ -306,6 +313,10 @@ fn hosted_bundle_fetch() { !lock.contains(&sum(&upstream_gem)), "{test}: Gemfile.lock:\n{lock}" ); + // The document of that run and the one of `vex` say so, in a checkout + // Bazel has built in, before anything has fetched the patched gem. + cell.wrote_in_run(&scan, &in_run, &claim); + cell.stands_alone(socket_patch, &claim, true); assert_eq!(standin.asked(&patched_route), 0, "{test}: {said}"); // (c) The same build, no step in between: patched, from the patch @@ -321,10 +332,18 @@ fn hosted_bundle_fetch() { upstream_fetches, "{test}: the patched build fetched the upstream gem" ); + // `vex` says the same of the build that printed the patched marker, + // and with `--no-verify` that it checked no file. + cell.stands_alone(socket_patch, &claim, true); + cell.stands_alone(socket_patch, &claim, false); - // (d) The undo: every file is the one of before, and so is the build. + // (d) The undo: every file is the one of before, and so is the build, + // and `vex` has no document for it. let undo = socket_patch(&cell, &["rollback", "--yes"]); cell.undone(&undo, "rolledBack", &before, &unpatched); + cell.attests_nothing(socket_patch, 2, "manifest_not_found"); + // The same two documents where no Bazel has built. + cell.attests_unbuilt(socket_patch, &hosted, &before, &pinned, &claim); // (e) A second machine with the rewritten files, and a patch registry // that serves other bytes at the pinned URL: still a gem RubyGems diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs new file mode 100644 index 000000000..5b1034a91 --- /dev/null +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs @@ -0,0 +1,208 @@ +//! `vex` for a project that Bazel does not build, in a checkout where Bazel +//! builds something else. +//! +//! `web/` is a plain pnpm project. The root of its checkout is a Bazel +//! workspace that builds Java and nothing of `web/`: its one hub is +//! `maven.install` of rules_jvm_external in a `MODULE.bazel`, or +//! `maven_install` in a `WORKSPACE`, and no Bazel file names the project's +//! lock. So what `socket-patch` patched there is what the project's own +//! package manager installs, as in a checkout without Bazel, and `vex` must +//! say what it says there: the exit code, both streams and the document of +//! each form are those of that checkout, byte for byte (but for the path of +//! the checkout, the id of a document and the time). +//! +//! These two tests are the fixed point for every change to what `vex` says +//! in a Bazel workspace. A change that makes one of them fail, or that +//! needs an edit to this file, has changed the answer for a project Bazel +//! does not build. A change that makes `vex` read a Bazel file adds a test +//! of its own for the case it touches. + +use std::path::{Path, PathBuf}; + +use crate::vex_e2e_common; +use vex_e2e_common::*; + +const PURL: &str = "pkg:npm/left-pad@1.3.0"; +const UUID: &str = "6d2f8b1c-4e7a-4c3d-9b5e-0a1f2e3d4c5b"; +const VULNS: &[(&str, &[&str])] = &[("GHSA-bzl-besd-0001", &["CVE-2026-6161"])]; +/// The entry file of the package, before the patch and with it. +const UPSTREAM: &str = "module.exports = (s) => s;\n"; +const PATCHED: &str = "/* patched */\nmodule.exports = (s) => s;\n"; +/// The sum of a tarball, as a lock spells it. +const INTEGRITY: &str = "sha512-UEFUQ0hFRHBhdGNoZWRQQVRDSEVEcGF0Y2hlZA=="; + +/// A root `MODULE.bazel` whose one hub is Maven's, and the package of the +/// root that it builds. +const JAVA_MODULE: &str = r#"module(name = "shop", version = "0.0.0") + +bazel_dep(name = "rules_jvm_external", version = "6.7") + +maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven") +maven.install(artifacts = ["com.google.guava:guava:33.4.0-jre"]) +use_repo(maven, "maven") +"#; +const JAVA_BUILD: &str = r#"java_library( + name = "server", + srcs = glob(["server/**/*.java"]), + deps = ["@maven//:com_google_guava_guava"], +) +"#; + +/// A root `WORKSPACE` whose one hub is Maven's. +const JAVA_WORKSPACE: &str = r#"workspace(name = "shop") + +load("@rules_jvm_external//:defs.bzl", "maven_install") + +maven_install( + artifacts = ["com.google.guava:guava:33.4.0-jre"], + repositories = ["https://repo1.maven.org/maven2"], +) +"#; + +/// What is at the root of each checkout, and its files: no Bazel, then the +/// two workspaces that build Java. +const AROUND: [(&str, &[(&str, &str)]); 3] = [ + ("no Bazel", &[]), + ( + "a Java MODULE.bazel", + &[("MODULE.bazel", JAVA_MODULE), ("BUILD.bazel", JAVA_BUILD)], + ), + ("a Java WORKSPACE", &[("WORKSPACE", JAVA_WORKSPACE)]), +]; + +/// The files of the pnpm project: its `package.json`, and a lock as pnpm 9 +/// and later write it, which holds `resolution` for the one package. +fn project(resolution: &str) -> Vec<(String, String)> { + let package = r#"{"name": "web", "version": "1.0.0", "dependencies": {"left-pad": "1.3.0"}}"#; + let lock = format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\nimporters:\n\n .:\n dependencies:\n \ + left-pad:\n specifier: 1.3.0\n version: 1.3.0\n\npackages:\n\n \ + left-pad@1.3.0:\n resolution: {{{resolution}}}\n\nsnapshots:\n\n \ + left-pad@1.3.0: {{}}\n" + ); + let files = [ + ("package.json", package.to_string()), + ("pnpm-lock.yaml", lock), + ]; + files.map(|(rel, text)| (rel.to_string(), text)).to_vec() +} + +/// What a run said: its exit code, its stdout, its stderr and its +/// document, with what differs from one checkout and one run to the next +/// in fixed words: the path of the checkout, the id `vex` makes for a +/// document, and the time. +fn settled(out: &VexOutcome, checkout: &Path) -> (Option, String, String, String) { + let document = std::fs::read_to_string(&out.output).unwrap_or_default(); + // The path as the test names it and as the system resolves it, each as + // plain text and as a JSON string spells it. + let resolved = checkout.canonicalize().expect("the checkout"); + let mut paths = Vec::new(); + for path in [resolved.as_path(), checkout] { + let plain = path.to_string_lossy().into_owned(); + let quoted = serde_json::to_string(&plain).expect("a JSON string"); + paths.extend([quoted[1..quoted.len() - 1].to_string(), plain]); + } + let id = regex::Regex::new("urn:uuid:[0-9a-f-]{36}").expect("an id"); + let time = regex::Regex::new(r#""timestamp": "[^"]*""#).expect("a time"); + let fixed = |text: &str| { + let text = paths.iter().fold(text.to_string(), |text, path| { + text.replace(path.as_str(), "") + }); + let text = id.replace_all(&text, "urn:uuid:"); + time.replace_all(&text, r#""timestamp": """#) + .into_owned() + }; + let streams = [&out.stdout, &out.stderr, &document].map(|text| fixed(text)); + let [stdout, stderr, document] = streams; + (out.code, stdout, stderr, document) +} + +/// `vex` as JSON and as a person reads it, and `apply --vex`, each as `run` +/// says, in a checkout with the project's `files` in `web/` and each set of +/// Bazel files at its root. Without Bazel a form attests the package +/// through the patch, as `marker` says; beside each workspace it says what +/// it said there. +fn says_the_same_beside_bazel(files: &[(String, String)], run: VexRun, marker: Marker) { + let person = VexRun { + human: true, + ..run.clone() + }; + let forms = [run.clone(), person, run.via(VexVia::Apply)]; + let mut without_bazel = Vec::new(); + for (around, bazel) in AROUND { + let root = tempfile::tempdir().expect("a temp root"); + let web = root.path().join("web"); + let write = |path: PathBuf, text: &str| { + std::fs::create_dir_all(path.parent().expect("a file path")).expect("a directory"); + std::fs::write(path, text).expect("a file of the checkout"); + }; + write(root.path().join(".git/HEAD"), "ref: refs/heads/main\n"); + for (rel, text) in bazel { + write(root.path().join(rel), text); + } + for (rel, text) in files { + write(web.join(rel), text); + } + for (n, form) in forms.iter().enumerate() { + // Each form writes the same path: the document compared is its own. + let _ = std::fs::remove_file(web.join(DEFAULT_OUTPUT)); + let out = run_vex(&binary(), &web, form); + let said = settled(&out, root.path()); + if bazel.is_empty() { + assert_eq!(out.code, Some(0), "form {n}: {out}"); + assert_attested(out.doc(), PURL, UUID, marker, VULNS); + without_bazel.push(said); + } else { + assert_eq!(said, without_bazel[n], "{around}, form {n}: {out}"); + } + } + } +} + +/// Hosted mode: the lock names the patched tarball on the patch host, and +/// the record comes from the API. +#[test] +fn a_hosted_pin_beside_a_java_bazel_build_attests_as_without_bazel() { + let files = [("package/index.js", &*git_sha256(PATCHED.as_bytes()))]; + let api = PatchApi::start(vec![(UUID.into(), patch_view(UUID, PURL, &files, VULNS))]); + let pin = format!( + "integrity: {INTEGRITY}, tarball: \ + https://patch.socket.dev/patch/npm/left-pad/1.3.0/{HOSTED_TOKEN}/{UUID}/left-pad-1.3.0.tgz" + ); + says_the_same_beside_bazel(&project(&pin), VexRun::online(&api), Marker::Redirected); +} + +/// Agent mode: the installed copy holds the patch, which the manifest +/// records with its blob, and the run is offline. +#[test] +fn an_installed_patch_beside_a_java_bazel_build_attests_as_without_bazel() { + let (ghsa, cves) = VULNS[0]; + let patched = git_sha256(PATCHED.as_bytes()); + let manifest = serde_json::json!({ "patches": { PURL: { + "uuid": UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "package/index.js": { + "beforeHash": git_sha256(UPSTREAM.as_bytes()), + "afterHash": patched, + }}, + "vulnerabilities": { ghsa: { + "cves": cves, "summary": "s", "severity": "high", "description": "d", + }}, + "description": "a patch", + "license": "MIT", + "tier": "free", + }}}); + let mut files = project(&format!("integrity: {INTEGRITY}")); + let installed = r#"{"name": "left-pad", "version": "1.3.0"}"#; + files.extend([ + ( + "node_modules/left-pad/package.json".into(), + installed.into(), + ), + ("node_modules/left-pad/index.js".into(), PATCHED.into()), + (format!(".socket/blobs/{patched}"), PATCHED.into()), + (".socket/manifest.json".into(), manifest.to_string()), + ]); + says_the_same_beside_bazel(&files, VexRun::offline(), Marker::Applied); +} diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs index 39d72efa2..20ae25a43 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/main.rs @@ -35,6 +35,7 @@ mod vex_pdm_hatch_common; #[path = "../vex_pipenv_pip_common/mod.rs"] mod vex_pipenv_pip_common; +mod bazel_beside; mod bun; mod cargo; mod common_selftest; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index b8a0fd25d..a8df338fa 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2273,6 +2273,38 @@ installed tree leaves the gem with its patched sources and no finished extension Patch runs again: `apply` puts the previous build back and completes the rebuild, and `rollback` restores the original sources and build. +## Bazel workspaces: VEX + +`vex` and `--vex` read what socket-patch wrote and what the project's own package manager +installed. They read no `MODULE.bazel`, `WORKSPACE` or BUILD file, so in a Bazel workspace a +document says what was patched, and that is what Bazel builds only where Bazel builds from +the files socket-patch rewrote. The two are tested to agree on real Bazel 9.3.2, 8.8.2 and +7.7.2 for four shapes, all under Bzlmod: Go through gazelle's +`go_deps.from_file(go_mod = "//:go.mod")` with +`go_deps.config(check_direct_dependencies = "error")` and the module required directly in +`go.mod` (hosted, vendored and agent mode), npm through +aspect_rules_js's `npm.npm_translate_lock(pnpm_lock = "//:pnpm-lock.yaml")` (hosted and +vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requirements.txt")` +(hosted), and RubyGems through rules_ruby's +`ruby.bundle_fetch(gemfile_lock = "//:Gemfile.lock")` without `gem_checksums` (hosted). There +the build prints the patched package, and the document of the run (`--vex`), of `vex` and of +`vex --no-verify` is one `not_affected` statement that names the package and the patch; the +first two are the same in a checkout with the same files that Bazel has not built in, and +after the undo `vex` writes no document. + +In every other Bazel shape nothing checks the document against the build, and in these it was +measured to be wrong (`not_affected` while Bazel builds the unpatched package, or while the +build is broken): agent mode beside rules_js, which builds from the lock and never reads the +patched `node_modules`; Go under a `go_repository` rule of a `WORKSPACE`, in hosted and +vendored mode; Go under `go_deps` when another Bazel module of the build requires a higher +version of the patched module, because gazelle then builds that version and drops the +replacement; a +`pip.parse` or `pip_parse` that takes the requirements of the build's platform from another +file than the one socket-patch rewrote; vendored mode for PyPI. Do not publish a document for +an artifact that Bazel built outside those four shapes. A project that Bazel does not build is +not concerned: beside a Bazel workspace whose files name none of its locks, `vex` says what it +says without Bazel. + ## Supported platforms Prebuilt binaries are published for: From d12790ff5c9c4457a9405f371507487686ac3d46 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 16:55:22 -0500 Subject: [PATCH 04/13] Hold the VEX documents of the Bazel flows to each other after review A code review of the VEX assertions in the real-Bazel flows found gaps in what the tests hold. This closes them. It changes tests, one docs sentence and the path lists of the four Bazel workflows; no file under `crates/*/src`. - The documents of a flow are compared with each other. Each one was checked alone, and its package through a normalising function, so the `%40` and the `@` spelling of an npm scope both passed and nothing showed that the forms write the same document. Now every document read in a checkout (of the run, of `vex`, of `vex --no-verify`) must equal the first one read there in every string but the document id, the timestamps and the `; not verified on disk` mark, and the documents of the checkout that Bazel has not built in must equal those of the one it has. The check of each document alone stays. The product spells all of it alike in all eight flows on Bazel 9.3.2, 8.8.2 and 7.7.2: no expectation had to differ per form. - `vex --output ` with no `--product`, the command a user types, runs once after the patched build in every flow. In the npm and the Go checkouts it exits 0 without a warning and writes the same document for the product of the project's own file, beside Bazel's links: `pkg:npm/socket-fixture@0.0.0` from `package.json`, `pkg:golang/example.com/consumer` from `go.mod`. The PyPI and the RubyGems fixture have no file a product is read from: there it exits 2 with `product_undetected` and writes no document. - The marker of a vendored copy is compared between the two checkouts as well, as JSON without `vendoredAt`, its one time field. The whole file was left out before, so a marker with another purl, patch id or advisory passed. - The `; not verified on disk` mark is the constant the product exports, `socket_patch_core::vex::NOT_VERIFIED_SUFFIX`. - The two hermetic tests of `e2e_vex_lockfile/bazel_beside.rs` tell each form the id of its document (`--doc-id`, and `--vex-doc-id` for `apply`) in place of rewriting the ids in what a run printed. - `docs/ecosystems.md` says that for PyPI on Bazel 8.5 and later a hosted scan leaves `MODULE.bazel.lock` stale: a build with `--lockfile_mode=error` fails until the lock is updated and committed. The PyPI flow already asserts both. - The pull request path lists of the four Bazel workflows gain `crates/socket-patch-core/src/vex/**` and `crates/socket-patch-cli/src/commands/vex*.rs`, the three files of the `vex` command. The flows hold exact VEX output, and the first commit added the core directory to the push lists only: a pull request that changed VEX code started no Bazel leg and could break all eight flows on main unseen. One hermetic test holds the two comparisons themselves: two spellings of a scope are two wordings, and a marker that names another package is another tree. The fixture checks hold the two product names to the fixtures' `package.json` and `go.mod`. Each new or changed assertion fails under one mutation, the real-Bazel ones on Bazel 9.3.2. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/bazel-go.yml | 18 +- .github/workflows/bazel-npm.yml | 28 +-- .github/workflows/bazel-pypi.yml | 21 +- .github/workflows/bazel-ruby.yml | 13 +- .../tests/e2e_bazel_build/go.rs | 21 +- .../tests/e2e_bazel_build/harness.rs | 181 ++++++++++++++++-- .../tests/e2e_bazel_build/main.rs | 10 +- .../tests/e2e_bazel_build/npm.rs | 21 +- .../tests/e2e_bazel_build/pypi.rs | 3 + .../tests/e2e_bazel_build/ruby.rs | 3 + .../tests/e2e_vex_lockfile/bazel_beside.rs | 17 +- docs/ecosystems.md | 5 +- 12 files changed, 281 insertions(+), 60 deletions(-) diff --git a/.github/workflows/bazel-go.yml b/.github/workflows/bazel-go.yml index e940d5f3e..b189b3f12 100644 --- a/.github/workflows/bazel-go.yml +++ b/.github/workflows/bazel-go.yml @@ -23,12 +23,17 @@ on: # 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, 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. + # lists them, what socket-patch does only in a Bazel workspace + # (`bazel/`), and the VEX code: `vex/` of the core and the files of the + # `vex` command. Every flow holds the exact document socket-patch writes + # about its patched build, so a change to how a document is built or + # worded starts the legs of every ecosystem. Nothing else that another + # ecosystem's flow owns is here, so any other change to one ecosystem + # starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, - # hosted/, commands/), the shared test helpers and the toolchain files. + # hosted/, the rest of commands/), the shared test helpers and the + # toolchain files. # A change there gets its run on the push to main (when the file is in # the list below) or in the nightly run, not on the pull request: that # is the price of not running every ecosystem's legs on every shared @@ -45,6 +50,8 @@ on: - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -65,11 +72,12 @@ on: - 'crates/*/src/**/*golang*/**' - 'crates/socket-patch-core/src/vendor/go*.rs' - 'crates/socket-patch-core/src/bazel/**' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' - - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-npm.yml b/.github/workflows/bazel-npm.yml index 35f945467..699a19c2d 100644 --- a/.github/workflows/bazel-npm.yml +++ b/.github/workflows/bazel-npm.yml @@ -36,18 +36,21 @@ on: # Its walk of the pnpm workspace decides what the second run of each # flow reports, and no other test runs it beside Bazel's links. That # file also holds the Composer, Cargo and Go parts of the gate, so a - # change to those starts the npm legs too. The - # globs name that one crate, so no bench fixture is here, and nothing - # another ecosystem's flow owns: a change to one ecosystem starts that - # ecosystem's legs only. + # change to those starts the npm legs too. The `*pnpm*` globs name that + # one crate, so no bench fixture is here. Last, the VEX code: `vex/` of + # the core and the files of the `vex` command. Every flow holds the + # exact document socket-patch writes about its patched build, so a + # change to how a document is built or worded starts the legs of every + # ecosystem. Nothing else that another ecosystem's flow owns is here: + # any other change to one ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, - # the rest of vendor/, hosted/, commands/), the shared test helpers and - # the toolchain files. A change there gets its run on the push to main - # (when the file is in the list below) or in the nightly run, not on the - # pull request: that is the price of not running every ecosystem's legs - # on every shared change. On demand, workflow_dispatch runs the legs on - # any branch. + # the rest of vendor/, hosted/, the rest of commands/), the shared test + # helpers and the toolchain files. A change there gets its run on the + # push to main (when the file is in the list below) or in the nightly + # run, not on the pull request: that is the price of not running every + # ecosystem's legs on every shared change. On demand, workflow_dispatch + # runs the legs on any branch. paths: - '.github/workflows/bazel-npm.yml' - '.github/workflows/bazel-compatibility.yml' @@ -66,6 +69,8 @@ on: - 'crates/socket-patch-core/src/crawlers/npm_crawler.rs' - 'crates/socket-patch-core/src/formats/package_json.rs' - 'crates/socket-patch-core/src/patch/user_patches.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -92,12 +97,13 @@ on: - 'crates/socket-patch-core/src/crawlers/npm_crawler.rs' - 'crates/socket-patch-core/src/formats/package_json.rs' - 'crates/socket-patch-core/src/patch/user_patches.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/vendor/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' - - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-pypi.yml b/.github/workflows/bazel-pypi.yml index 48ec24d21..6299fc1c3 100644 --- a/.github/workflows/bazel-pypi.yml +++ b/.github/workflows/bazel-pypi.yml @@ -32,12 +32,16 @@ on: # `*python*` pattern would also match the benchmark fixtures, the rest # of vendored mode and the files of the lock-file package managers # (pdm, pipenv, poetry, uv), where this flow does no more than find - # that the project is not theirs. Nothing another ecosystem's flow owns - # is here, so a change to one ecosystem starts that ecosystem's legs - # only. Three PyPI helpers that those files call, and that are no other - # project manager's own, are listed with them: the finder of a - # project's Python lock files, the spelling of a version in a wheel's - # file name, and the hosted scan's check of an installed wheel. + # that the project is not theirs. Three PyPI helpers that those files + # call, and that are no other project manager's own, are listed with + # them: the finder of a project's Python lock files, the spelling of a + # version in a wheel's file name, and the hosted scan's check of an + # installed wheel. Last, the VEX code: `vex/` of the core and the files + # of the `vex` command. Every flow holds the exact document socket-patch + # writes about its patched build, so a change to how a document is built + # or worded starts the legs of every ecosystem. Nothing else that + # another ecosystem's flow owns is here, so any other change to one + # ecosystem starts that ecosystem's legs only. # # What it does not cover: shared engine code (patch/redirect/mod.rs, # the rest of hosted/ and of commands/), the shared test helpers and the @@ -69,6 +73,8 @@ on: - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -100,11 +106,12 @@ on: - 'crates/socket-patch-core/src/vendor/pypi_requirements.rs' - 'crates/socket-patch-core/src/vendor/pypi_wheel.rs' - 'crates/socket-patch-core/src/vex/discover/pypi_other.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' - - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' diff --git a/.github/workflows/bazel-ruby.yml b/.github/workflows/bazel-ruby.yml index 0686db0e1..07183b368 100644 --- a/.github/workflows/bazel-ruby.yml +++ b/.github/workflows/bazel-ruby.yml @@ -30,8 +30,12 @@ on: # (formats/gem), lock discovery, the lock inventory, the Ruby crawler # (it says which lock Bundler loads), the upstream restore of # `rollback`, and the stale-install guard that both commands end with. - # Nothing another ecosystem's flow owns is here, so a change to one - # ecosystem starts that ecosystem's legs only. + # Last, the VEX code: `vex/` of the core and the files of the `vex` + # command. Every flow holds the exact document socket-patch writes about + # its patched build, so a change to how a document is built or worded + # starts the legs of every ecosystem. Nothing else that another + # ecosystem's flow owns is here, so any other change to one ecosystem + # starts that ecosystem's legs only. # # What it does not cover: shared engine code. The other half of the # hosted rewrite is there (`rewrite_gem` and its planner in @@ -60,6 +64,8 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' push: branches: [main] # The pull request paths, and what only a push to main covers: the @@ -82,12 +88,13 @@ on: - 'crates/socket-patch-core/src/crawlers/ruby_crawler.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/gem.rs' - 'crates/*/src/**/gem_refresh.rs' + - 'crates/socket-patch-core/src/vex/**' + - 'crates/socket-patch-cli/src/commands/vex*.rs' - 'crates/socket-patch-cli/tests/e2e_bazel_build/main.rs' - 'crates/socket-patch-core/src/vendor/gem.rs' - 'crates/socket-patch-core/src/patch/redirect/**' - 'crates/socket-patch-core/src/hosted/**' - 'crates/socket-patch-cli/src/commands/**' - - 'crates/socket-patch-core/src/vex/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' - 'Cargo.lock' 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 3a0589fbc..5901b009f 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/go.rs @@ -83,6 +83,9 @@ const FIXTURE: Fixture = Fixture { const MODULE: &str = "example.com/upstream"; const VERSION: &str = "v1.0.0"; const PURL: &str = "pkg:golang/example.com/upstream@v1.0.0"; +/// The product `vex` reads from the fixture's own `go.mod`, which records +/// a module and no version. +const PRODUCT: &str = "pkg:golang/example.com/consumer"; /// Its two files. The fixture's `go.sum` holds the `h1:` of these bytes. const GO_MOD: &[u8] = b"module example.com/upstream\n\ngo 1.21\n"; const UPSTREAM_LIB: &[u8] = b"package upstream\n\nfunc Greeting() string { return \"PRISTINE\" }\n"; @@ -344,6 +347,9 @@ fn hosted_go_deps() { // and with `--no-verify` that it checked no file. cell.stands_alone(socket_patch, &claim, true); cell.stands_alone(socket_patch, &claim, false); + // Without a product, as a user types it: the same document for the + // module of the checkout's own `go.mod`. + cell.detects_product(socket_patch, Some(PRODUCT)); // (d) The undo: every file is the one of before, and so is the build, // and `vex` has no document for it. @@ -702,10 +708,12 @@ fn kept_copy_flow(test: &str, mode: Kept, ships_build: bool) { cell.stands_alone(run, &claim, true); // (c) The next build is patched, from the copy, and `vex` says so; with - // `--no-verify` it says that it checked no file. + // `--no-verify` it says that it checked no file, and without a product + // it says the same for the module of the checkout's own `go.mod`. cell.builds_patched(&pinned, &patched); cell.stands_alone(run, &claim, true); cell.stands_alone(run, &claim, false); + cell.detects_product(run, Some(PRODUCT)); // (d) The user's next step: gazelle writes nothing into the copy, the // build stays patched, and no package of the checkout is under @@ -1575,9 +1583,10 @@ fn a_manifest_in_another_project_brings_the_file_of_both_projects_in_line() { } } -/// 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. +/// Without a Bazel: the fixture's directories are those of its table, its +/// `go.sum` pins the module the test serves, which holds the `h1:` +/// arithmetic here to sums that `go` computed, and its `go.mod` names the +/// module of [`PRODUCT`]. #[test] fn the_fixture_pins_the_upstream_module_the_test_serves() { FIXTURE.check(); @@ -1585,4 +1594,8 @@ fn the_fixture_pins_the_upstream_module_the_test_serves() { let go_sum = std::fs::read_to_string(&path).expect("the fixture's go.sum"); let lines: Vec<&str> = go_sum.lines().collect(); assert_eq!(lines, upstream().go_sum(), "{}", path.display()); + let go_mod = std::fs::read_to_string(path.with_file_name("go.mod")).expect("go.mod"); + let module = PRODUCT.strip_prefix("pkg:golang/").expect("a Go module"); + let line = format!("module {module}"); + assert!(go_mod.lines().any(|named| named == line), "{go_mod}"); } 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 dbe30b3d3..17c55bf5d 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -10,12 +10,14 @@ use std::ffi::{OsStr, OsString}; use std::ops::Range; use std::path::{Path, PathBuf}; use std::process::{Command, Output}; +use std::sync::OnceLock; use serde_json::{json, Value}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; use socket_patch_core::utils::purl::normalize_purl; +use socket_patch_core::vex::NOT_VERIFIED_SUFFIX; use crate::envelope::{codes_in, event_for, events}; use crate::fs_tree; @@ -113,9 +115,10 @@ pub type Tree = BTreeMap>; /// What [`changed`] gives for two equal trees. pub const NOTHING: [&str; 0] = []; -/// The product every form of `vex` is told: no flow depends on what its -/// fixture lets `socket-patch` detect one from, and the PyPI and the -/// RubyGems fixture have no project file. +/// The product the forms of `vex` are told, so that the documents of every +/// flow name one, whatever its fixture lets `socket-patch` detect: the PyPI +/// and the RubyGems fixture have no project file. One run per flow goes +/// without it ([`Cell::detects_product`]). const PRODUCT: &str = "pkg:generic/socket-fixture@0.0.0"; /// The advisory of every patch record a flow is served: the one of the @@ -166,6 +169,43 @@ fn vex(path: &Path) -> [&str; 5] { ["vex", "--output", argument(path), "--product", PRODUCT] } +/// What the document at `path` holds. +fn document_at(test: &str, path: &Path) -> (String, Value) { + let text = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("{test}: no document {}: {e}", path.display())); + let document = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{test}: no JSON ({e}):\n{text}")); + (text, document) +} + +/// `document` without what each run and each form writes for itself: the +/// id of the document, its times and those of its statements, and the mark +/// of `vex --no-verify` at the end of an impact statement. What is left is +/// what a document says and the strings it says it with: the product, the +/// package, the advisory and its aliases, the status, the justification +/// and the patch. +fn wording(mut document: Value) -> Value { + fn without(of: &mut Value, fields: &[&str]) { + let Some(object) = of.as_object_mut() else { + return; + }; + for field in fields { + object.remove(*field); + } + } + without(&mut document, &["@id", "timestamp", "last_updated"]); + let statements = document["statements"].as_array_mut(); + for statement in statements.into_iter().flatten() { + without(statement, &["timestamp", "last_updated"]); + let Some(impact) = statement["impact_statement"].as_str() else { + continue; + }; + let unmarked = impact.strip_suffix(NOT_VERIFIED_SUFFIX).unwrap_or(impact); + statement["impact_statement"] = unmarked.to_string().into(); + } + document +} + /// What a `scan` or an `apply` is given to write the document of its own /// run to `path`. pub fn with_vex(path: &Path) -> [&str; 4] { @@ -291,6 +331,28 @@ pub fn fixture_path(rel: &str) -> PathBuf { .join(rel) } +/// The marker file of a vendored copy, in the directory of its patch. +const MARKER: &str = "/socket-patch.vendor.json"; + +/// `tree` with every [`MARKER`] as its JSON value without `vendoredAt`, +/// the one field that holds a time: two runs that vendor the same patch +/// of the same package write markers that are equal in this, and a marker +/// that names another package, patch or advisory is not. A marker that is +/// no JSON object stays as it is. +fn undated(tree: &Tree) -> Tree { + let mut tree = tree.clone(); + for (file, bytes) in &mut tree { + if !file.ends_with(MARKER) { + continue; + } + if let Ok(Value::Object(mut fields)) = serde_json::from_slice(bytes) { + fields.remove("vendoredAt"); + *bytes = Value::Object(fields).to_string().into_bytes(); + } + } + tree +} + /// The names under which `before` and `after` differ. pub fn changed(before: &Tree, after: &Tree) -> Vec { let names = before.keys().chain(after.keys()); @@ -681,6 +743,9 @@ pub struct Cell { socket_bin: Option, /// The rules of the downloader config, once a flow has asked for one. downloads: Option>, + /// The [`wording`] of the first document [`Cell::attests`] read in + /// this checkout, which every later one is held to. + wording: OnceLock, // Dropped after `Cell::drop` has stopped the server. scratch: Scratch, } @@ -737,6 +802,7 @@ impl Cell { numbers, socket_bin, downloads: None, + wording: OnceLock::new(), scratch, }) } @@ -778,6 +844,7 @@ impl Cell { numbers: self.numbers, socket_bin: self.socket_bin.clone(), downloads: None, + wording: OnceLock::new(), scratch: Scratch::new(Some(self.scratch.repository_cache.clone())), }; for (rel, bytes) in files { @@ -1019,13 +1086,13 @@ impl Cell { /// `not_affected` for the one advisory, with the package as the one /// subcomponent of the one product and the patch of this run in its /// impact statement, which ends with `; not verified on disk` exactly - /// when the run did not check the files (`verified` is false). + /// when the run did not check the files (`verified` is false). And it + /// says so in the words of every other document read in this checkout: + /// the forms spell the product, the package, the advisory and the + /// status alike, and differ in nothing but what [`wording`] leaves out. fn attests(&self, path: &Path, claim: &Claim, verified: bool) { let test = &self.test; - let text = std::fs::read_to_string(path) - .unwrap_or_else(|e| panic!("{test}: no document {}: {e}", path.display())); - let document: Value = serde_json::from_str(&text) - .unwrap_or_else(|e| panic!("{test}: no JSON ({e}):\n{text}")); + let (text, document) = document_at(test, path); let context = "https://openvex.dev/ns/v0.2.0"; assert_eq!(document["@context"], context, "{test}: {text}"); let statements = document["statements"].as_array(); @@ -1048,9 +1115,15 @@ impl Cell { let (uuid, how) = (claim.uuid, claim.how.words()); let mut impact = format!("Patched via Socket patch {uuid}{how}"); if !verified { - impact += "; not verified on disk"; + impact += NOT_VERIFIED_SUFFIX; } assert_eq!(statement["impact_statement"], impact, "{test}: {text}"); + let said = wording(document); + let first = self.wording.get_or_init(|| said.clone()); + assert_eq!( + said, *first, + "{test}: not the words of the first document of this checkout:\n{text}" + ); } /// The stand-alone `vex` of this checkout, through `run`, the flow's way @@ -1082,6 +1155,37 @@ impl Cell { self.attests(&path, claim, verified); } + /// `vex --output ` as a user types it, with no `--product`, + /// through `run`, in this checkout that Bazel has built in: beside the + /// project's own files are Bazel's links, and behind them those files + /// again. `product` is what `vex` reads from the project file of the + /// checkout: it writes the document every other form wrote here, for + /// that product, and warns of nothing. With `None` the checkout has no + /// file `vex` reads a product from: it exits 2 with + /// `product_undetected` and writes no document. + pub fn detects_product(&self, run: impl Fn(&Cell, &[&str]) -> Ran, product: Option<&str>) { + let path = self.document("no-product"); + let ran = run(self, &["vex", "--output", argument(&path)]); + let (test, said) = (&self.test, &ran.dump); + let Some(product) = product else { + assert_eq!(ran.code, 2, "{test}: {said}"); + let error = &ran.envelope["error"]["code"]; + assert_eq!(*error, "product_undetected", "{test}: {said}"); + assert!(!path.exists(), "{test}: a document is left: {said}"); + return; + }; + assert_eq!(ran.code, 0, "{test}: {said}"); + assert_eq!( + codes_in(&ran.envelope["warnings"]), + NOTHING, + "{test}: {said}" + ); + let (text, document) = document_at(test, &path); + let mut named = self.wording.get().cloned().expect("a document here"); + named["statements"][0]["products"][0]["@id"] = product.into(); + assert_eq!(wording(document), named, "{test}: {said}\n{text}"); + } + /// For a finished command that was given [`with_vex`] for `path`: it /// passed, and wrote the document of its own run, which attests /// `claim` and nothing else. A hosted scan says of its document that @@ -1105,10 +1209,11 @@ impl Cell { /// The same two documents from a checkout that no Bazel has built in: /// one with the files `before`, where `command`, the command of the /// mode, applies the patch and writes the document of its run, and the - /// stand-alone `vex` writes its own. The command leaves the files - /// `patched`, those the patched build started from (only the marker - /// of a vendored copy differs: it holds the time of its run), so both - /// checkouts attest the same files. + /// stand-alone `vex` writes its own, both in the words of this + /// checkout's documents. The command leaves the files `patched`, those + /// the patched build started from, so both checkouts attest the same + /// files. One field of one file is left out: `vendoredAt`, the time of + /// its run in the marker of a vendored copy. pub fn attests_unbuilt( &self, run: impl Fn(&Cell, &[&str]) -> Ran, @@ -1123,11 +1228,11 @@ impl Cell { let (test, said) = (&self.test, &ran.dump); assert_eq!(ran.envelope["summary"]["applied"], 1, "{test}: {said}"); fresh.wrote_in_run(&ran, &in_run, claim); - let mut differ = changed(patched, &fresh.tree()); - // The marker of a vendored copy holds the time of its run. - differ.retain(|file| !file.ends_with("/socket-patch.vendor.json")); + let differ = changed(&undated(patched), &undated(&fresh.tree())); assert_eq!(differ, NOTHING, "{test}: {said}"); fresh.stands_alone(run, claim, true); + let (here, there) = (self.wording.get(), fresh.wording.get()); + assert_eq!(there, here, "{test}: the two checkouts word it apart"); } /// The stand-alone `vex` of a checkout that holds no patch any more, @@ -1222,6 +1327,7 @@ pub fn cell_without_bazel(release: &str) -> Cell { numbers: numbers(release).expect("a release"), socket_bin: None, downloads: None, + wording: OnceLock::new(), scratch: Scratch::new(None), } } @@ -1287,6 +1393,49 @@ fn a_document_is_no_file_of_the_checkout() { } } +/// Without a Bazel: two documents are held to each other in every string +/// but the id, the times and the mark of `--no-verify`, so the two +/// spellings of an npm scope are two wordings; and two trees in every +/// byte but the `vendoredAt` of a marker. +#[test] +fn documents_and_markers_are_compared_but_for_their_ids_and_times() { + let (escaped, plain) = ("pkg:npm/%40scope/name@1.0.0", "pkg:npm/@scope/name@1.0.0"); + let document = |n: u32, package: &str, impact: &str| { + let time = format!("2026-01-0{n}T00:00:00Z"); + wording(json!({ + "@id": format!("urn:uuid:{n}"), + "timestamp": time, + "statements": [{ + "timestamp": time, + "products": [{ "@id": PRODUCT, "subcomponents": [{ "@id": package }] }], + "impact_statement": impact, + }], + })) + }; + let patched = "Patched via Socket patch one (vendored)"; + let first = document(1, escaped, patched); + let unchecked = format!("{patched}{NOT_VERIFIED_SUFFIX}"); + assert_eq!(document(2, escaped, &unchecked), first); + assert_ne!(document(1, plain, patched), first); + assert_ne!(document(1, escaped, "Patched via Socket patch two"), first); + + let tree = |file: &str, purl: &str, n: u32| { + let marker = json!({ "purl": purl, "vendoredAt": format!("2026-01-0{n}T00:00:00Z") }); + undated(&Tree::from([( + file.to_string(), + marker.to_string().into_bytes(), + )])) + }; + let marker = format!(".socket/vendor/npm/one{MARKER}"); + let first = tree(&marker, escaped, 1); + assert_eq!(changed(&first, &tree(&marker, escaped, 2)), NOTHING); + assert_eq!(changed(&first, &tree(&marker, plain, 1)), [marker.as_str()]); + // No other file is read for a time. + let ledger = ".socket/vendor/state.json"; + let other = changed(&tree(ledger, escaped, 1), &tree(ledger, escaped, 2)); + assert_eq!(other, [ledger]); +} + /// Set in the copy of this test binary that the next test starts, which /// then plays the shell of a developer. const PLAYS_THE_SHELL: &str = "SOCKET_PATCH_BAZEL_E2E_PLAYS_THE_SHELL"; 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 c44e4000e..f271f6998 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/main.rs @@ -39,8 +39,14 @@ //! and the command and `vex` write the same two in a checkout with the //! same files that no Bazel has built in. Each document is one statement: //! the package under test is `not_affected`, through the patch of this -//! run. Nothing in `socket-patch` reads a Bazel file for it, so these tests -//! say for which workspaces the document and the build agree. +//! run. The documents of a flow are also held to each other: they differ +//! in their id, their times and the mark of `--no-verify`, and in no other +//! string. Every form is told one product; `vex` without one, as a user +//! types it, runs once after the patched build, where it names the project +//! of the checkout's own `package.json` or `go.mod`, or writes no document +//! where the fixture has no such file. Nothing in `socket-patch` reads a +//! Bazel file for it, so these tests say for which workspaces the document +//! and the build agree. //! //! A flow is one `#[ignore]`d test in its ecosystem's module, and its //! fixture is one directory of files that every release builds beside one diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs index ffa54c242..c590d55ca 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/npm.rs @@ -113,6 +113,9 @@ const VERSION: &str = "1.0.0"; /// Socket API's purl of a scoped package. `scan` takes either spelling and /// names a patch in its events as the API did. const PURL: &str = "pkg:npm/%40socketsecurity/bazel-fixture-upstream@1.0.0"; +/// The product `vex` reads from the fixture's own `package.json`: its name +/// and its version. +const PRODUCT: &str = "pkg:npm/socket-fixture@0.0.0"; /// The file name of its tarball on the registry and on the patch host: the /// name without its scope. const TGZ: &str = "bazel-fixture-upstream-1.0.0.tgz"; @@ -411,8 +414,9 @@ fn second_machine( /// `scan --mode --yes` scans the package and reports the one event /// `seen` for it (an action and an error code), which is what it reports in /// a checkout without those links; the document of that run, and those of -/// `vex` and of `vex --no-verify`, attest `claim`; no file of the checkout -/// changes; and the build still prints `marker`. +/// `vex` and of `vex --no-verify`, attest `claim`; `vex` without a product +/// names the fixture's own; no file of the checkout changes; and the build +/// still prints `marker`. fn runs_again( cell: &Cell, standin: &StandIn, @@ -451,6 +455,10 @@ fn runs_again( let run = |cell: &Cell, args: &[&str]| socket_patch(cell, standin, args); cell.stands_alone(run, claim, true); cell.stands_alone(run, claim, false); + // Without a product, as a user types it: the same document for the + // project of the checkout's own `package.json`, which Bazel's links + // show a second time. + cell.detects_product(run, Some(PRODUCT)); assert_eq!(changed(patched, &cell.tree()), NOTHING, "{test}"); cell.builds_patched(patched, marker); @@ -696,9 +704,10 @@ fn vendored_npm_translate_lock() { /// fixture's directories and the legs of its workflow are those of its /// table; the fixture's lock holds the one entry a test pins, with the /// placeholder and no URL, and pinning changes nothing else; the fixture -/// depends on the package at the version of that entry; two runs serve two -/// upstream tarballs; and the names written out above are those of the one -/// package, under the organisation's scope. +/// depends on the package at the version of that entry and has the name +/// and the version of [`PRODUCT`]; two runs serve two upstream tarballs; and +/// the names written out above are those of the one package, under the +/// organisation's scope. #[test] fn a_test_pins_the_one_entry_of_the_fixture_lock() { FIXTURE.check(); @@ -715,6 +724,8 @@ fn a_test_pins_the_one_entry_of_the_fixture_lock() { let fixture: Value = serde_json::from_str(&read("package.json")).expect("package.json"); assert_eq!(fixture["dependencies"][NAME], VERSION); + let named = [&fixture["name"], &fixture["version"]].map(|field| field.as_str().expect("text")); + assert_eq!(PRODUCT, format!("pkg:npm/{}@{}", named[0], named[1])); let manifest: Value = serde_json::from_str(MANIFEST).expect("the package's package.json"); assert_eq!(manifest["name"], NAME); assert_eq!(manifest["version"], VERSION); diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs index 3f17432b6..5d48ad304 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/pypi.rs @@ -449,6 +449,9 @@ fn hosted_pip_parse() { // and with `--no-verify` that it checked no file. cell.stands_alone(run, &claim, true); cell.stands_alone(run, &claim, false); + // Without a product, as a user types it, `vex` writes none: the + // checkout has no file it reads a product from. + cell.detects_product(run, None); // (d) The undo: `requirements.txt` is the one of before at once, and // the lock is still the one of the patched build, so a frozen lock diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs index b000b0dd4..1e1eb046a 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/ruby.rs @@ -336,6 +336,9 @@ fn hosted_bundle_fetch() { // and with `--no-verify` that it checked no file. cell.stands_alone(socket_patch, &claim, true); cell.stands_alone(socket_patch, &claim, false); + // Without a product, as a user types it, `vex` writes none: the + // checkout has no file it reads a product from. + cell.detects_product(socket_patch, None); // (d) The undo: every file is the one of before, and so is the build, // and `vex` has no document for it. diff --git a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs index 5b1034a91..69072290b 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_lockfile/bazel_beside.rs @@ -9,7 +9,7 @@ //! package manager installs, as in a checkout without Bazel, and `vex` must //! say what it says there: the exit code, both streams and the document of //! each form are those of that checkout, byte for byte (but for the path of -//! the checkout, the id of a document and the time). +//! the checkout and the time; each form is told the id of its document). //! //! These two tests are the fixed point for every change to what `vex` says //! in a Bazel workspace. A change that makes one of them fail, or that @@ -30,6 +30,9 @@ const UPSTREAM: &str = "module.exports = (s) => s;\n"; const PATCHED: &str = "/* patched */\nmodule.exports = (s) => s;\n"; /// The sum of a tarball, as a lock spells it. const INTEGRITY: &str = "sha512-UEFUQ0hFRHBhdGNoZWRQQVRDSEVEcGF0Y2hlZA=="; +/// The id every form is told to give its document (`--doc-id`, and +/// `--vex-doc-id` for `apply`), where `vex` would make a new one per run. +const DOCUMENT: &str = "urn:uuid:0b6c7d2e-5a41-4f38-8e9d-1c2b3a4f5e6d"; /// A root `MODULE.bazel` whose one hub is Maven's, and the package of the /// root that it builds. @@ -90,8 +93,7 @@ fn project(resolution: &str) -> Vec<(String, String)> { /// What a run said: its exit code, its stdout, its stderr and its /// document, with what differs from one checkout and one run to the next -/// in fixed words: the path of the checkout, the id `vex` makes for a -/// document, and the time. +/// in fixed words: the path of the checkout and the time. fn settled(out: &VexOutcome, checkout: &Path) -> (Option, String, String, String) { let document = std::fs::read_to_string(&out.output).unwrap_or_default(); // The path as the test names it and as the system resolves it, each as @@ -103,13 +105,11 @@ fn settled(out: &VexOutcome, checkout: &Path) -> (Option, String, String, S let quoted = serde_json::to_string(&plain).expect("a JSON string"); paths.extend([quoted[1..quoted.len() - 1].to_string(), plain]); } - let id = regex::Regex::new("urn:uuid:[0-9a-f-]{36}").expect("an id"); let time = regex::Regex::new(r#""timestamp": "[^"]*""#).expect("a time"); let fixed = |text: &str| { let text = paths.iter().fold(text.to_string(), |text, path| { text.replace(path.as_str(), "") }); - let text = id.replace_all(&text, "urn:uuid:"); time.replace_all(&text, r#""timestamp": """#) .into_owned() }; @@ -124,11 +124,16 @@ fn settled(out: &VexOutcome, checkout: &Path) -> (Option, String, String, S /// through the patch, as `marker` says; beside each workspace it says what /// it said there. fn says_the_same_beside_bazel(files: &[(String, String)], run: VexRun, marker: Marker) { + let told = |run: VexRun, option: &str| run.arg(option).arg(DOCUMENT); let person = VexRun { human: true, ..run.clone() }; - let forms = [run.clone(), person, run.via(VexVia::Apply)]; + let forms = [ + told(run.clone(), "--doc-id"), + told(person, "--doc-id"), + told(run.via(VexVia::Apply), "--vex-doc-id"), + ]; let mut without_bazel = Vec::new(); for (around, bazel) in AROUND { let root = tempfile::tempdir().expect("a temp root"); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a8df338fa..4fcca1f03 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2290,7 +2290,10 @@ vendored), PyPI through rules_python's `pip.parse(requirements_lock = "//:requir the build prints the patched package, and the document of the run (`--vex`), of `vex` and of `vex --no-verify` is one `not_affected` statement that names the package and the patch; the first two are the same in a checkout with the same files that Bazel has not built in, and -after the undo `vex` writes no document. +after the undo `vex` writes no document. For PyPI on Bazel 8.5 and later a hosted scan leaves +`MODULE.bazel.lock` stale, so the document is there before a frozen build passes: a build with +`--lockfile_mode=error` fails until a build that may update the lock has run, and the updated +lock has to be committed. In every other Bazel shape nothing checks the document against the build, and in these it was measured to be wrong (`not_affected` while Bazel builds the unpatched package, or while the From fbe5db73714a21faf9f40df1d07cba39b75cb805 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 18 Nov 2026 14:02:34 -0500 Subject: [PATCH 05/13] Read the calls of a Bazel workspace's files Whether a patch reaches a Bazel build depends on which file the workspace's rules read: `npm.npm_translate_lock(pnpm_lock = ...)`, `pip.parse(requirements_lock = ..., requirements_by_platform = {...})`, `ruby.bundle_fetch(gemfile_lock = ..., gem_checksums = {...})`, `go_deps.from_file(go_mod = ...)`. socket-patch has no reader of Bazel files. This adds one, as library code in `crates/socket-patch-core/src/bazel/` beside `bazel_root`. Nothing calls it yet and no command changes: its first caller is the VEX step that withholds a statement for a copy Bazel does not build. What it reads `starlark.rs` lists every call `name(...)` and `a.b(...)` of a file, at any depth: the callee as written, its line and bytes, and each argument, positional, by keyword, `*` or `**`. An argument is a string literal (either quote, tripled or raw, decoded as Bazel's lexer decodes it), a list of strings, a dict from strings to strings or lists of strings, a bare name, or "other". A call says whether it is a whole statement, an argument of another call, in a comprehension; only the first says that it runs, and once. Beside the calls it lists what each statement binds (`x = f(...)`, `x = y`, the symbols of a `load` with their aliases) and every other place a name stands, marked where the name may be given a value there: a tuple target, the variable of a comprehension. A name means what the last statement before it bound it to. That is how these files run: Bazel allows no `if`, `for` or `def` statement and no `lambda` in them (`DotBazelFileSyntaxChecker`, the same at 7.7.2, 8.8.2 and 9.3.2). Tokens end where Bazel's lexer ends them: a name that ends a line and a parenthesis that starts the next are two statements, and the `for` of `0for` is a word of its own. `workspace.rs` reads MODULE.bazel and the files it includes, through a view: a function from a path below the Bazel root to text, absent or unreadable, so the same code serves a checkout on disk and files held in memory. `disk()` is the view of a checkout and opens nothing outside the Bazel root. `Workspace::tags(extension, tag)` returns the calls of one tag of one module extension, with the file and line of each. An extension is known by the module and the `.bzl` file that define it (through the name a `bazel_dep(repo_name = ...)` gives the module, or the root module itself), never by the name of its proxy: rules_go's `go_sdk.from_file` and gazelle's `go_deps.from_file` take the same `go_mod`. `Workspace::label` reads a label of a tag as Bazel does: from the root package, whichever file the tag is written in (`StarlarkBazelModule.create`), with the root module's own repository name as the main repository. `include` is read by Bazel's rules (`CompiledModuleFile.checkModuleFileSyntax`, `ModuleFileFunction.advanceHorizon`; it exists from 7.2.0): a statement of its own with one string that starts with `//` and ends in `.MODULE.bazel`. Why nothing is evaluated, and what is reported instead To evaluate Starlark is to run the workspace's code and its rulesets'. The reader states what the text says outright and says where it cannot, as doubts: those of the workspace (`Workspace::doubts`), which are about every answer, and those of one answer (`Tags::doubts`). With neither, the calls listed are the calls of that tag which the files of a workspace Bazel accepts can make. That is held by tests, one for each way found so far to write a call that would not be listed, and not proven; what Bazel is told outside the files (a flag, an override on the command line) is not known to the reader. A doubt is: - a file that is missing, cannot be read, is not UTF-8, is over 1 MiB, is reached through a path or a link that leaves the Bazel root, or includes itself; a 257th file, or text past 8 MiB in all; - a string or a bracket that is never closed, which Bazel refuses too; - an `include`, `use_extension`, `module` or `bazel_dep` whose label or name is not written as a plain string, or that may not run: one that gives a name or a file and is not a whole statement (behind `and`, in a conditional, in a comprehension); - an `include` with a second argument (9.3.2 takes `dev_dependency`); - one of those four names, `use_repo` or `inject_repo` used other than to call it: under such a name, `getattr` calls a tag; - `True`, `False` or `None` where the file may give it another value: Bazel then reads `repo_name = None` otherwise; - for the extension asked about, a proxy used for anything but calling a tag on it or as the whole first argument of `use_repo` or `inject_repo`. `override_repo` is such a use: it puts another repository in the place of one the extension makes. A computed argument is no doubt: the call is listed and the argument is "other", never a guess. A label can name a target of a BUILD file instead of a file; the reader gives its path, and whether the file exists is for the caller to ask. WORKSPACE files and the `.bzl` files they load are not read yet; `load` bindings and labels relative to a package are there for them, and what a name is bound to inside a function of a `.bzl` file is not told yet. The reader takes any bytes and panics on none. It makes one pass over the bytes and one over the tokens, with no recursion, a name bound again shares what it stands for, and a query looks at each call, binding and use once, so the work grows with the size of the files. The tests hold that with the largest file that is read in each shape that nests or repeats, with one long symbol, call or label that many names stand for, and with a sample file cut and altered at every byte. Measured, outside the tree, on the 17,842 MODULE.bazel, *.MODULE.bazel, WORKSPACE, WORKSPACE.bazel, WORKSPACE.bzlmod and .bzl files of 35 repositories (rulesets with their examples, Bazel itself, the Bazel Central Registry): 17,841 are read and one is refused, a fixture with an unclosed string. Of 13,664 directories with a MODULE.bazel, 13,653 are read without a doubt. The four lookups find 941 `go_deps.from_file`, 389 `npm_translate_lock`, 984 `pip.parse` and 42 `bundle_fetch` calls; a second reading of the same files with regular expressions finds the same calls with the same string arguments in every directory, and 66 of them were compared by eye. What a person can read there and the reader reports as a doubt: an include through a directory link that leaves the Bazel root (8 directories), and a `repo_name` given as a constant (1). What it lists without a value: 18 lock arguments that are computed, each in a comprehension. The largest of those workspaces is 55 KiB in 70 files. A workspace made to be costly, 8 MiB of nothing but names, takes about 1 GiB for under a second. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/bazel/mod.rs | 2 + .../socket-patch-core/src/bazel/starlark.rs | 1498 +++++++++++++ .../socket-patch-core/src/bazel/workspace.rs | 1863 +++++++++++++++++ scripts/loc-budget.json | 2 +- 4 files changed, 3364 insertions(+), 1 deletion(-) create mode 100644 crates/socket-patch-core/src/bazel/starlark.rs create mode 100644 crates/socket-patch-core/src/bazel/workspace.rs diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index 7147e02a2..704f70ac9 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -9,6 +9,8 @@ pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; pub mod ignore; +pub mod starlark; +pub mod workspace; use std::path::{Path, PathBuf}; diff --git a/crates/socket-patch-core/src/bazel/starlark.rs b/crates/socket-patch-core/src/bazel/starlark.rs new file mode 100644 index 000000000..95b15f9b9 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/starlark.rs @@ -0,0 +1,1498 @@ +//! A reader of the Starlark in Bazel workspace files: `MODULE.bazel` and +//! the files it includes today, `WORKSPACE` and the `.bzl` files it loads +//! next. +//! +//! [`index`] lists every call of a file with its arguments, every name a +//! statement binds, and every other place a name stands for its value. +//! Nothing is evaluated. An argument is a literal that can be stated +//! outright (a string, a list or a dict of strings, a bare name) or it is +//! [`Value::Other`], and a name means what the last statement before it +//! bound it to. That is how a `MODULE.bazel` and a `WORKSPACE` file run: +//! Bazel allows no `if`, `for` or `def` statement and no `lambda` in them +//! (`DotBazelFileSyntaxChecker`, the same at 7.7.2, 8.8.2 and 9.3.2). +//! +//! A `.bzl` file has all of them. Its calls, bindings and uses are listed +//! the same way, but [`Call::bind`], [`Use::bind`] and [`Call::whole`] do +//! not hold there: an assignment inside one function rebinds the name +//! for the rest of the file, and a call in an `if` or a `for` block is +//! whole. A reader of such a file has to tell the functions apart first. +//! +//! It takes bytes and panics on none. Every step consumes a byte or a +//! token, nothing recurses, the literal of an argument is given up at its +//! first token that is not part of one, and a name that is bound again +//! shares what it stands for, so time and memory grow with the size of the +//! file, which [`MAX_BYTES`] bounds. The tests hold that for the shapes +//! they name. Bytes that are not UTF-8 are content in a comment or a +//! string, as they are for Bazel; a string that holds them has no value. +//! +//! A file is refused ([`Unreadable`]) for what Bazel refuses it for too: a +//! string or a bracket that is never closed, a bracket closed by another +//! kind. Other text Bazel rejects (`$`, a tab as indentation) becomes +//! tokens: Bazel builds nothing from such a file, so no reading of it is +//! acted on. + +use std::collections::HashMap; +use std::ops::Range; +use std::sync::Arc; + +/// The largest file that is read. The largest of 17,842 workspace and +/// `.bzl` files of the rulesets and the Bazel Central Registry is 0.6 MiB. +pub const MAX_BYTES: usize = 1 << 20; + +/// Why a file is not read, and the line the reason is on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Unreadable { + pub line: usize, + pub why: &'static str, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// An identifier or a keyword. + Name, + /// A string literal in any form: either quote, tripled or not, with an + /// `r` before it or not. [`value`] decodes it. + Str, + Number, + /// `(`, `[` or `{`. + Open, + /// `)`, `]` or `}`. + Close, + /// An operator or punctuation, the longest one that matches. + Op, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Token { + kind: Kind, + /// The bytes `start..end` of the file. + start: usize, + end: usize, + /// The line it starts on, from 1. + line: usize, + /// The first token of a line, outside every bracket: where a statement + /// starts. A line joined to the one before by a backslash is no line. + first: bool, + /// For a bracket, the index of the token that closes or opens it. + mate: usize, +} + +/// The operators longer than a byte, longest first. +const LONG_OPS: [&[u8]; 20] = [ + b"//=", b"<<=", b">>=", b"**", b"==", b"!=", b"<=", b">=", b"+=", b"-=", b"*=", b"/=", b"%=", + b"&=", b"|=", b"^=", b"//", b"<<", b">>", b"->", +]; + +/// A byte of a name. +fn word(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} + +/// The tokens of a file. Blanks, comments, line ends and the backslash +/// that joins two lines are not tokens. +fn tokens(src: &[u8]) -> Result, Unreadable> { + let fail = |line, why| Err(Unreadable { line, why }); + if src.len() > MAX_BYTES { + return fail(1, "it is larger than 1 MiB"); + } + let mut out: Vec = Vec::new(); + // The brackets that are open: the index of each in `out`, and the byte + // that closes it. + let mut open: Vec<(usize, u8)> = Vec::new(); + let (mut start, mut line, mut first) = (0, 1, true); + while let Some(&c) = src.get(start) { + let rest = &src[start..]; + let run = |part: fn(u8) -> bool| rest.iter().take_while(|b| part(**b)).count(); + let (kind, len) = match c { + b' ' | b'\t' | b'\r' | b'\n' => (None, Some(1)), + b'\\' if rest.starts_with(b"\\\n") => (None, Some(2)), + b'\\' if rest.starts_with(b"\\\r\n") => (None, Some(3)), + b'#' => (None, Some(run(|b| b != b'\n'))), + b'"' | b'\'' => (Some(Kind::Str), string(rest)), + b'r' if matches!(rest.get(1), Some(b'"' | b'\'')) => { + (Some(Kind::Str), string(&rest[1..]).map(|len| len + 1)) + } + b'0'..=b'9' => (Some(Kind::Number), Some(number(rest))), + b'A'..=b'Z' | b'a'..=b'z' | b'_' => (Some(Kind::Name), Some(run(word))), + b'(' | b'[' | b'{' => (Some(Kind::Open), Some(1)), + b')' | b']' | b'}' => (Some(Kind::Close), Some(1)), + _ => { + let long = LONG_OPS.iter().find(|op| rest.starts_with(op)); + (Some(Kind::Op), Some(long.map_or(1, |op| op.len()))) + } + }; + let Some(end) = len.map(|len| start + len) else { + return fail(line, "a string is never closed"); + }; + if let Some(kind) = kind { + let (mut mate, outside) = (0, open.is_empty()); + if kind == Kind::Open { + // `)` follows `(` in ASCII; `]` and `}` are two after theirs. + open.push((out.len(), c + 1 + u8::from(c != b'('))); + } else if kind == Kind::Close { + let Some((opener, _)) = open.pop().filter(|(_, closer)| *closer == c) else { + return fail(line, "a bracket closes one that is not open"); + }; + (mate, out[opener].mate) = (opener, out.len()); + } + let first = std::mem::take(&mut first) && outside; + out.push(Token { + kind, + start, + end, + line, + first, + mate, + }); + } + // A line end, alone or after a backslash, and those in a string. + line += src[start..end].iter().filter(|b| **b == b'\n').count(); + (start, first) = (end, first || c == b'\n'); + } + match open.last() { + Some(&(opener, _)) => fail(out[opener].line, "a bracket is never closed"), + None => Ok(out), + } +} + +/// The length of the number that `s` starts with, as Bazel's lexer scans +/// it (`Lexer.scanNumberOrDot`, the same rule at 7.7.2, 8.8.2 and 9.3.2): +/// `0x`, `0o` or `0b` and their digits, or digits, a fraction and an +/// exponent. A word right after it is a token of its own: the `for` of +/// `0for`. +fn number(s: &[u8]) -> usize { + let run = + |at: usize, part: fn(&u8) -> bool| at + s[at..].iter().take_while(|b| part(b)).count(); + let digits = |at| run(at, u8::is_ascii_digit); + match s.get(1).filter(|_| s[0] == b'0') { + Some(b'x' | b'X') => return run(2, u8::is_ascii_hexdigit), + Some(b'b' | b'B') => return run(2, |b| matches!(b, b'0' | b'1')), + Some(b'o' | b'O') => return digits(2), + _ => {} + } + let mut at = digits(0); + if s.get(at) == Some(&b'.') { + at = digits(at + 1); + } + if matches!(s.get(at), Some(b'e' | b'E')) { + at = digits(at + 1 + usize::from(matches!(s.get(at + 1), Some(b'+' | b'-')))); + } + at +} + +/// The length of the string literal whose opening quote is `s[0]`, or +/// `None` when it is never closed. A backslash keeps the byte after it (a +/// whole CRLF) out of the search for the end, in a raw string too, as in +/// Bazel's lexer. +fn string(s: &[u8]) -> Option { + let quote = s[0]; + let triple = s[1..].starts_with(&[quote, quote]); + let mut at = if triple { 3 } else { 1 }; + loop { + match *s.get(at)? { + b'\\' => at += 2 + usize::from(s[at + 1..].starts_with(b"\r\n")), + b'\n' if !triple => return None, + c if c == quote && (!triple || s[at + 1..].starts_with(&[quote, quote])) => { + return Some(at + if triple { 3 } else { 1 }); + } + _ => at += 1, + } + } +} + +/// The value of a string token, decoded as Bazel's lexer decodes it +/// (`Lexer.escapedStringLiteral`, the same at 7.7.2, 8.8.2 and 9.3.2). +/// `None` for an escape Bazel rejects (`\x41`, `\N{DASH}`, `\q`, an octal +/// one above `\377`), for bytes that are not UTF-8, and for a token that +/// is no string. +fn value(src: &[u8], token: &Token) -> Option { + let text = src.get(token.start..token.end)?; + let raw = text.first() == Some(&b'r'); + let text = text.get(usize::from(raw)..)?; + let quotes = 1 + 2 * usize::from(text.len() >= 6 && text[1..3] == [text[0], text[0]]); + let inside = quotes..text.len().checked_sub(quotes)?; + let body = text.get(inside).filter(|_| token.kind == Kind::Str)?; + let mut out = Vec::with_capacity(body.len()); + let mut at = 0; + while let Some(&c) = body.get(at) { + at += 1; + if c != b'\\' { + out.push(c); + continue; + } + let next = *body.get(at)?; + at += 1; + let octal = body[at..] + .iter() + .take(2) + .take_while(|b| (b'0'..=b'7').contains(b)); + match next { + // A line end after a backslash: a line feed in a raw string, + // nothing in any other. + b'\r' | b'\n' => { + at += usize::from(next == b'\r' && body.get(at) == Some(&b'\n')); + out.extend(&b"\\\n"[..2 * usize::from(raw)]); + } + _ if raw => out.extend([b'\\', next]), + b'0'..=b'7' => { + let digits = octal.count(); + let digits = &body[at - 1..at + digits]; + at += digits.len() - 1; + let byte = digits + .iter() + .fold(0, |byte, digit| byte * 8 + u32::from(digit - b'0')); + out.push(u8::try_from(byte).ok()?); + } + _ => { + let mut escapes = b"n\nr\rt\ta\x07b\x08f\x0cv\x0b\\\\''\"\"".chunks(2); + out.push(escapes.find(|escape| escape[0] == next)?[1]); + } + } + } + String::from_utf8(out).ok() +} + +/// What an argument is, when it can be stated without running anything. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Value { + /// One string literal, decoded. + Str(String), + /// A list display of string literals. + List(Vec), + /// A dict display from string literals to [`Value::Str`] or + /// [`Value::List`], in the order written. + Dict(Vec<(String, Value)>), + /// One bare name: `True`, `None`, a constant, a loop variable. There + /// is no class for a Bool: `True` is the name, and means Bazel's `True` + /// only in a file that gives the name no other value. + Name(String), + /// Any other expression: a concatenation, a call, `select()`, a + /// comprehension, a number, a string Bazel does not take. + Other, +} + +/// How an argument is passed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum How { + Positional, + /// `name = value`. + Keyword(String), + /// `*value`. + Star, + /// `**value`. + StarStar, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Arg { + pub how: How, + pub value: Value, + /// The bytes of the argument, with its keyword or stars. + pub span: Range, +} + +/// A call `name(...)` or `a.b(...)`. A call on a computed value +/// (`f(x).g()`, `"{}".format(x)`) is not one. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Call { + /// The callee as written, its parts joined by dots: `pip.parse`. + pub callee: String, + /// What the first name of the callee is bound to here: an index into + /// [`File::binds`]. `None` for a name no statement before it has bound, + /// which is what a name Bazel predeclares is. + pub bind: Option, + /// The line of the callee, from 1. + pub line: usize, + /// The bytes from the callee to the closing parenthesis. + pub span: Range, + pub args: Vec, + /// The call is a statement of its own, or the whole right side of an + /// assignment. Only this says that the call runs, and runs once: any + /// other call may stand behind an `and`, in a conditional or in a + /// comprehension that has no item. + pub whole: bool, + /// It is inside the parentheses of another call. + pub in_call: bool, + /// It is inside the brackets of a comprehension: it may run once per + /// item, or not at all. + pub in_comprehension: bool, +} + +impl Call { + /// The value passed for the keyword `name`. `None` also when the call + /// passes it in a `**` dict: ask [`Self::unpacks`] before taking the + /// keyword for absent. + pub fn arg(&self, name: &str) -> Option<&Value> { + let named = |arg: &&Arg| matches!(&arg.how, How::Keyword(key) if key == name); + self.args.iter().find(named).map(|arg| &arg.value) + } + + /// The value of the positional argument `at`, from 0. + pub fn positional(&self, at: usize) -> Option<&Value> { + let arg = self.args.get(at).filter(|arg| arg.how == How::Positional); + arg.map(|arg| &arg.value) + } + + /// The call passes `*` or `**`: it has arguments that are not listed. + pub fn unpacks(&self) -> bool { + let stars = |arg: &Arg| matches!(arg.how, How::Star | How::StarStar); + self.args.iter().any(stars) + } +} + +/// What a name is bound to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Bound { + /// The result of a call, an index into [`File::calls`]: `x = f(...)`. + /// `y = x` binds `y` to the same. + Call(usize), + /// A symbol of another file: the `load` call, an index into + /// [`File::calls`], and the symbol's name there. `load(file, "f")` + /// binds `f` to `f`, `load(file, g = "f")` binds `g` to `f`. + Loaded(usize, Arc), + /// Anything else. + Other, +} + +/// A statement `name = ...`, or one symbol of a `load`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bind { + pub name: String, + pub line: usize, + pub to: Bound, +} + +/// A name where it is neither called nor bound by a statement `name = +/// ...`: an argument, an operand, an item of a list, an attribute read +/// without a call (`f = pip.parse`). The `y` of a statement `x = y` is +/// none when the file has bound `y`: `x` is then bound to the same. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Use { + pub name: String, + /// As [`Call::bind`]. + pub bind: Option, + pub line: usize, + /// The byte the name starts at. + pub at: usize, + /// The name may be given a value here instead of standing for one: it + /// is between a `for` and its `in` (the variable of a comprehension), + /// or before the `=` of its statement (`a, b = ...`). So are the `d` + /// and the `k` of `d[k] = ...`, which are read: the mark is one too + /// many there, never one too few. + pub assigned: bool, +} + +/// What a file says, as far as it can be read without running it. Each +/// list is in the order of the file. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct File { + pub calls: Vec, + pub binds: Vec, + pub uses: Vec, +} + +/// Words of the language: never a callee, never a use. +const KEYWORDS: &[u8] = b"and break continue def elif else for if in lambda not or pass return"; + +/// An open bracket; the first one of the stack stands for the statement. +#[derive(Default)] +struct Frame { + /// The call whose parenthesis this is. + call: Option, + /// The token the argument being read starts at. + arg: usize, + /// How many calls the file had when the bracket opened. + before: usize, + /// A `for` at this level: the bracket is a comprehension. + comprehension: bool, + /// A `for` at this level whose `in` has not come yet. + looping: bool, +} + +#[derive(Default)] +struct Reader<'a> { + src: &'a [u8], + tokens: Vec, + file: File, + /// The binding each name has at the token being read. + env: HashMap, usize>, + frames: Vec, + /// The first token of the statement being read. + statement: usize, + /// The call that starts the statement, or the right side of its + /// assignment, and the token that closes it (0 while it is open). + leading: Option<(usize, usize)>, + /// The parenthesis the newest call of the file opens with. + awaited: Option, + /// How many brackets are between a `for` and its `in`: above none, + /// the names being read may be variables of that `for`. + looping: usize, + /// How many uses the file had when the statement began, or at its + /// last `=`: the ones since then stand before the next `=`. + targets: usize, + /// The ranges of [`File::calls`] that lie in a call and in a + /// comprehension. + inside: [Vec>; 2], +} + +/// The calls, bindings and uses of a file. +pub fn index(src: &[u8]) -> Result { + let (tokens, frames) = (tokens(src)?, vec![Frame::default()]); + let mut reader = Reader { + src, + tokens, + frames, + ..Reader::default() + }; + for at in 0..reader.tokens.len() { + reader.token(at); + } + reader.end_statement(reader.tokens.len()); + // A call is inside when it lies in at least one of the ranges. + for (flag, ranges) in reader.inside.iter().enumerate() { + let mut depth = vec![0_i64; reader.file.calls.len() + 1]; + for range in ranges { + depth[range.start] += 1; + depth[range.end] -= 1; + } + let mut inside = 0; + for (call, change) in reader.file.calls.iter_mut().zip(depth) { + inside += change; + let flags = [&mut call.in_call, &mut call.in_comprehension]; + *flags[flag] = inside > 0; + } + } + Ok(reader.file) +} + +impl<'a> Reader<'a> { + fn text(&self, at: usize) -> &'a [u8] { + let src = self.src; + let token = self.tokens.get(at); + token.map_or(&src[..0], |token| &src[token.start..token.end]) + } + + fn is(&self, at: usize, kind: Kind, text: &[u8]) -> bool { + self.kind(at) == Some(kind) && self.text(at) == text + } + + fn kind(&self, at: usize) -> Option { + self.tokens.get(at).map(|token| token.kind) + } + + fn name(&self, at: usize) -> String { + String::from_utf8_lossy(self.text(at)).into_owned() + } + + fn token(&mut self, at: usize) { + let (token, text) = (self.tokens[at], self.text(at)); + let (top, calls) = (self.frames.len() == 1, self.file.calls.len()); + if top && token.first { + self.end_statement(at); + } + let Some(frame) = self.frames.last_mut() else { + return; + }; + match (token.kind, text) { + (Kind::Name, _) => self.name_at(at), + (Kind::Open, _) => { + let call = (self.awaited.take() == Some(at)).then(|| calls - 1); + self.frames.push(Frame { + call, + arg: at + 1, + before: calls, + ..Frame::default() + }); + } + (Kind::Close, _) if !top => self.close(at), + // A comma ends an argument. + (Kind::Op, b",") => { + let from = std::mem::replace(&mut frame.arg, at + 1); + let call = frame.call; + self.argument(call, from, at); + } + // The names of a statement before its `=` may be given values. + (Kind::Op, b"=") if top => { + let targets = std::mem::replace(&mut self.targets, self.file.uses.len()); + for used in self.file.uses.iter_mut().skip(targets) { + used.assigned = true; + } + } + (Kind::Op, b";") if top => { + self.end_statement(at); + self.statement = at + 1; + } + _ => {} + } + } + + /// The bracket that the token `at` closes: the calls since it opened + /// are inside it. + fn close(&mut self, at: usize) { + let Some(frame) = self.frames.pop() else { + return; + }; + let within = frame.before..self.file.calls.len(); + self.inside[0].extend(frame.call.map(|_| within.clone())); + self.inside[1].extend(frame.comprehension.then_some(within)); + self.argument(frame.call, frame.arg, at); + if let Some(call) = frame.call { + self.file.calls[call].span.end = self.tokens[at].end; + let closed = |(leading, close)| (leading, if leading == call { at } else { close }); + self.leading = self.leading.map(closed); + } + } + + /// A name: an attribute, a word of the language, the head of a call, + /// the name of a keyword argument, the target of an assignment, or a + /// use. + fn name_at(&mut self, at: usize) { + let (token, text) = (self.tokens[at], self.text(at)); + let (top, calls) = (self.frames.len() == 1, self.file.calls.len()); + let after = |kind, text: &[u8]| at > 0 && self.is(at - 1, kind, text); + let skipped = after(Kind::Op, b".") || after(Kind::Name, b"def"); + let Some(frame) = self.frames.last_mut().filter(|_| !skipped) else { + return; + }; + match text { + b"for" => { + frame.comprehension = !top; + self.looping += usize::from(!std::mem::replace(&mut frame.looping, true)); + } + b"in" => self.looping -= usize::from(std::mem::take(&mut frame.looping)), + _ => {} + } + if KEYWORDS.split(|b| *b == b' ').any(|word| word == text) { + return; + } + let target = if top { + at == self.statement + } else { + frame.call.is_some() && frame.arg == at + }; + let mut last = at; + while self.is(last + 1, Kind::Op, b".") && self.kind(last + 2) == Some(Kind::Name) { + last += 2; + } + let (bind, line) = (self.env.get(text).copied(), token.line); + // A parenthesis that starts a line outside every bracket starts a + // statement, as it does for Bazel: `f` and then `(x)` is no call. + let opens = self.tokens.get(last + 1).is_some_and(|open| !open.first); + if opens && self.is(last + 1, Kind::Open, b"(") { + let parts: Vec = (at..=last).step_by(2).map(|part| self.name(part)).collect(); + if top && at == self.statement + 2 * usize::from(self.assigns(self.statement)) { + self.leading = Some((calls, 0)); + } + self.awaited = Some(last + 1); + self.file.calls.push(Call { + callee: parts.join("."), + bind, + line, + span: token.start..token.end, + ..Call::default() + }); + } else if !(target && self.is(at + 1, Kind::Op, b"=")) { + self.file.uses.push(Use { + name: self.name(at), + bind, + line, + at: token.start, + assigned: self.looping > 0, + }); + } + } + + /// The tokens from `at` on start with `name =`. + fn assigns(&self, at: usize) -> bool { + self.kind(at) == Some(Kind::Name) && self.is(at + 1, Kind::Op, b"=") + } + + /// The argument `from..to` of `call`, when there is one. + fn argument(&mut self, call: Option, from: usize, to: usize) { + let Some(call) = call.filter(|_| from < to) else { + return; + }; + let span = self.tokens[from].start..self.tokens[to - 1].end; + let (how, skip) = if self.is(from, Kind::Op, b"*") { + (How::Star, 1) + } else if self.is(from, Kind::Op, b"**") { + (How::StarStar, 1) + } else if self.assigns(from) { + (How::Keyword(self.name(from)), 2) + } else { + (How::Positional, 0) + }; + let value = self.value(from + skip, to); + self.file.calls[call].args.push(Arg { how, value, span }); + } + + /// The literal the tokens `from..to` are, when they are one. + fn value(&self, from: usize, to: usize) -> Value { + let Some(first) = self.tokens.get(from).filter(|_| from < to) else { + return Value::Other; + }; + let display = first.kind == Kind::Open && first.mate + 1 == to; + let literal = match first.kind { + Kind::Str if from + 1 == to => value(self.src, first).map(Value::Str), + Kind::Name if from + 1 == to => Some(Value::Name(self.name(from))), + Kind::Open if display && self.text(from) == b"[" => self.list(from).map(Value::List), + Kind::Open if display && self.text(from) == b"{" => self.dict(from).map(Value::Dict), + _ => None, + }; + literal.unwrap_or(Value::Other) + } + + /// The token after `at` and after the comma that may stand there, in + /// a display that closes at `close`: `None` when `at` is neither. + fn next(&self, at: usize, close: usize) -> Option { + let comma = self.is(at, Kind::Op, b","); + (comma || at == close).then_some(at + usize::from(comma)) + } + + /// The strings of the list display that opens at the token `open`. + fn list(&self, open: usize) -> Option> { + let close = self.tokens[open].mate; + let (mut items, mut at) = (Vec::new(), open + 1); + while at < close { + items.push(value(self.src, self.tokens.get(at)?)?); + at = self.next(at + 1, close)?; + } + Some(items) + } + + /// The entries of the dict display that opens at the token `open`: a + /// string, a colon, and a string or a list of strings. + fn dict(&self, open: usize) -> Option> { + let close = self.tokens[open].mate; + let (mut items, mut at) = (Vec::new(), open + 1); + while at < close { + let key = value(self.src, self.tokens.get(at)?)?; + let item = self.tokens.get(at + 2)?; + let (value, end) = match self.text(at + 2) { + _ if !self.is(at + 1, Kind::Op, b":") => return None, + b"[" => (Value::List(self.list(at + 2)?), item.mate), + _ => (Value::Str(value(self.src, item)?), at + 2), + }; + items.push((key, value)); + at = self.next(end + 1, close)?; + } + Some(items) + } + + /// The statement that started at `self.statement` ends before the + /// token `end`: note what it binds, and start the next one there. + fn end_statement(&mut self, end: usize) { + let start = std::mem::replace(&mut self.statement, end); + let whole = self.leading.take().filter(|(_, close)| close + 1 == end); + let call = whole.map(|(call, _)| call); + if let Some(call) = call { + self.file.calls[call].whole = true; + } + let line = self.tokens.get(start).map_or(0, |token| token.line); + if start + 2 < end && self.assigns(start) { + // `x = y` binds `x` to what `y` is bound to, and is no use of `y`. + let alias = self.tokens[start + 2]; + let aliased = self.env.get(self.text(start + 2)).copied(); + let aliased = aliased.filter(|_| start + 3 == end && alias.kind == Kind::Name); + let to = match (call, aliased) { + (Some(call), _) => Bound::Call(call), + (None, Some(aliased)) => { + self.file.uses.pop_if(|used| used.at == alias.start); + self.file.binds[aliased].to.clone() + } + (None, None) => Bound::Other, + }; + self.bind(self.name(start), line, to); + } + // `load(file, "name", other = "name")` binds its symbols. + let load = call.filter(|call| { + let call = &self.file.calls[*call]; + call.callee == "load" && call.bind.is_none() + }); + let symbols = load.map_or(Vec::new(), |load| self.file.calls[load].args.clone()); + for arg in symbols.into_iter().skip(1) { + let (Some(load), Value::Str(symbol)) = (load, arg.value) else { + continue; + }; + let name = match arg.how { + How::Positional => symbol.clone(), + How::Keyword(name) => name, + How::Star | How::StarStar => continue, + }; + self.bind(name, line, Bound::Loaded(load, symbol.into())); + } + self.targets = self.file.uses.len(); + } + + fn bind(&mut self, name: String, line: usize, to: Bound) { + let bind = self.file.binds.len(); + self.env.insert(name.clone().into_bytes(), bind); + self.file.binds.push(Bind { name, line, to }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_rng::Rng; + + /// The tokens of `src`, each as its kind and its text; `^` marks the + /// first token of a statement. + fn spell(src: &str) -> String { + let spell = |token: &Token| { + let kind = match token.kind { + Kind::Name => "n", + Kind::Str => "s", + Kind::Number => "d", + Kind::Open | Kind::Close => "b", + Kind::Op => "o", + }; + let first = if token.first { "^" } else { "" }; + format!("{first}{kind}:{}", &src[token.start..token.end]) + }; + let tokens = tokens(src.as_bytes()).unwrap(); + tokens.iter().map(spell).collect::>().join(" ") + } + + fn read(src: &str) -> File { + index(src.as_bytes()).unwrap() + } + + /// The calls of `callee` in `file`. + fn calls<'a>(file: &'a File, callee: &str) -> Vec<&'a Call> { + let named = |call: &&Call| call.callee == callee; + file.calls.iter().filter(named).collect() + } + + fn string(value: &str) -> Value { + Value::Str(value.to_string()) + } + + fn list(items: &[&str]) -> Value { + Value::List(items.iter().map(|item| item.to_string()).collect()) + } + + #[test] + fn every_token_form() { + for (src, want) in [ + ("x = 1", "^n:x o:= d:1"), + ("_a1 B_2 for", "^n:_a1 n:B_2 n:for"), + ( + "0 12 0x1F 0XfF 0o17 0O7 0b101 0B1 08 1.5 0.5 1e3 1E-2 1e+5 1.5e-3", + "^d:0 d:12 d:0x1F d:0XfF d:0o17 d:0O7 d:0b101 d:0B1 d:08 d:1.5 d:0.5 d:1e3 d:1E-2 \ + d:1e+5 d:1.5e-3", + ), + // A number ends where Bazel's lexer ends it: a word right after + // it is a word, but for an `e`, which is its exponent, and a + // number that starts with a dot is a dot and a number. + ( + "0for 1if 2else 3in 4or 5and 1_0 1.real", + "^d:0 n:for d:1 n:if d:2e n:lse d:3 n:in d:4 n:or d:5 n:and d:1 n:_0 d:1. n:real", + ), + ( + "0xg 0b12 0x 1e 1.e3 0. .5 1..2", + "^d:0x n:g d:0b1 d:2 d:0x d:1e d:1.e3 d:0. o:. d:5 d:1. o:. d:2", + ), + // Strings: both quotes, tripled, raw, empty, with the other + // quote, an escaped quote or a `#` inside. + ( + r#""a" 'b' """c""" '''d'''"#, + r#"^s:"a" s:'b' s:"""c""" s:'''d'''"#, + ), + ( + r#"r"e\n" r'f' r"""g""" r'''h'''"#, + r#"^s:r"e\n" s:r'f' s:r"""g""" s:r'''h'''"#, + ), + (r#""" '' """""" ''''''"#, r#"^s:"" s:'' s:"""""" s:''''''"#), + ( + r#""it's" 'say "hi"' "a\"b" 'a\'b' "\\""#, + r#"^s:"it's" s:'say "hi"' s:"a\"b" s:'a\'b' s:"\\""#, + ), + ( + r##""""a"b""c""" "#no comment""##, + r##"^s:"""a"b""c""" s:"#no comment""##, + ), + ("\"\"\"a\nb\"\"\" c", "^s:\"\"\"a\nb\"\"\" n:c"), + ("\"a\\\nb\" c", "^s:\"a\\\nb\" n:c"), + ("r\"a\\\r\nb\" c", "^s:r\"a\\\r\nb\" n:c"), + // Only a lower-case `r` right before the quote makes a prefix. + ( + r#"R"x" br"y" rb"z" r "w""#, + r#"^n:R s:"x" n:br s:"y" n:rb s:"z" n:r s:"w""#, + ), + // A comment ends with its line, whatever it holds. + ("a # b ( \" '''\nc#d", "^n:a ^n:c"), + ( + "f(a[1], {2: (3)})", + "^n:f b:( n:a b:[ d:1 b:] o:, b:{ d:2 o:: b:( d:3 b:) b:} b:)", + ), + ( + "a == b != c <= d >= e += f -= g *= h /= i //= j %= k &= l |= m ^= n <<= o >>= p", + "^n:a o:== n:b o:!= n:c o:<= n:d o:>= n:e o:+= n:f o:-= n:g o:*= n:h o:/= n:i \ + o://= n:j o:%= n:k o:&= n:l o:|= n:m o:^= n:n o:<<= n:o o:>>= n:p", + ), + ( + "a ** b // c << d >> e -> f", + "^n:a o:** n:b o:// n:c o:<< n:d o:>> n:e o:-> n:f", + ), + ( + "a=-1 b=*c d==e", + "^n:a o:= o:- d:1 n:b o:= o:* n:c n:d o:== n:e", + ), + ( + "+ - * / % < > = , : ; . | & ^ ~", + "^o:+ o:- o:* o:/ o:% o:< o:> o:= o:, o:: o:; o:. o:| o:& o:^ o:~", + ), + // A statement starts on a new line outside every bracket, and + // not on a line that a backslash joins to the one before. + ( + "f(\n a,\n)\ng = \\\n 1\n\n# c\n h", + "^n:f b:( n:a o:, b:) ^n:g o:= d:1 ^n:h", + ), + ("a = \\\r\n 1\r\nb\rc", "^n:a o:= d:1 ^n:b n:c"), + ] { + assert_eq!(spell(src), want, "{src:?}"); + } + // What Bazel rejects outside a string is a token a byte. + let odd = tokens("$ ? ! @ ` \\ \u{e9}".as_bytes()).unwrap(); + assert_eq!(odd.len(), 8); + assert!(odd.iter().all(|token| token.kind == Kind::Op)); + } + + #[test] + fn tokens_know_their_line_and_brackets_their_mate() { + let src = "a(\n [b],\n '''x\ny''', {\n})\nc \\\n d"; + let tokens = tokens(src.as_bytes()).unwrap(); + let lines: Vec = tokens.iter().map(|token| token.line).collect(); + assert_eq!(lines, [1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5, 6, 7]); + let mates: Vec<(usize, usize)> = (tokens.iter().enumerate()) + .filter(|(_, token)| token.kind == Kind::Open) + .map(|(at, token)| (at, token.mate)) + .collect(); + assert_eq!(mates, [(1, 10), (2, 4), (8, 9)]); + for (open, close) in mates { + assert_eq!(tokens[close].mate, open); + } + } + + #[test] + fn a_string_has_the_value_bazel_gives_it() { + for (src, want) in [ + (&br#""abc""#[..], Some("abc")), + (br#"'abc'"#, Some("abc")), + (br#""""a"b""""#, Some("a\"b")), + (br#"'''it's'''"#, Some("it's")), + (br#""""#, Some("")), + (br#""""""""#, Some("")), + (b"\"\"\"a\nb\"\"\"", Some("a\nb")), + ( + br#""a\nb\t\\\'\"\a\b\f\v\r""#, + Some("a\nb\t\\'\"\x07\x08\x0c\x0b\r"), + ), + // Octal: one to three digits, at most \377; above 0o177 it is a + // byte, and bytes must be UTF-8 to be a value. + (br#""\101\60\0\1012""#, Some("A0\0A2")), + (br#""\303\251""#, Some("\u{e9}")), + (br#""\377""#, None), + (br#""\400""#, None), + // The escapes Bazel rejects. + (br#""\x41""#, None), + (br#""\u00e9""#, None), + (br#""\N{DASH}""#, None), + (br#""a\qb""#, None), + // A backslash before a line end joins the lines. + (b"\"a\\\nb\"", Some("ab")), + (b"\"a\\\r\nb\"", Some("ab")), + // A raw string keeps the backslash and what follows it. + (br#"r"a\nb\"c\\""#, Some(r#"a\nb\"c\\"#)), + (br#"r'''\d+'''"#, Some(r"\d+")), + (b"r\"a\\\r\nb\"", Some("a\\\nb")), + ("\"caf\u{e9}\"".as_bytes(), Some("caf\u{e9}")), + (b"\"\xff\"", None), + (b"name", None), + (b"12", None), + ] { + let tokens = tokens(src).unwrap(); + assert_eq!(tokens.len(), 1, "{src:?}"); + assert_eq!(value(src, &tokens[0]).as_deref(), want, "{src:?}"); + } + // A token that is not one of the file's is no string either. + let stray = Token { + kind: Kind::Str, + start: 3, + end: 2, + line: 1, + first: false, + mate: 0, + }; + assert_eq!(value(b"\"abc\"", &stray), None); + assert_eq!( + value( + b"\"", + &Token { + start: 0, + end: 1, + ..stray + } + ), + None + ); + } + + #[test] + fn what_bazel_refuses_is_refused_with_its_line() { + let large = vec![b' '; MAX_BYTES + 1]; + for (src, line, why) in [ + (&b"\n\"abc"[..], 2, "a string is never closed"), + (b"x = \"a\nb\"", 1, "a string is never closed"), + (b"'''abc''", 1, "a string is never closed"), + (b"\"a\\", 1, "a string is never closed"), + (b"r\"a\\\"", 1, "a string is never closed"), + (b"\n\n)", 3, "a bracket closes one that is not open"), + (b"f(]", 1, "a bracket closes one that is not open"), + (b"{)}", 1, "a bracket closes one that is not open"), + (b"a\nf(\n[1]\n", 2, "a bracket is never closed"), + (&large[..], 1, "it is larger than 1 MiB"), + ] { + let want = Err(Unreadable { line, why }); + assert_eq!(tokens(src), want, "{:?}", &src[..src.len().min(20)]); + assert_eq!(index(src).map(|_| ()), want.map(|_| ())); + } + // At the limit, and with a line of 5 MB above it. + assert!(tokens(&large[1..]).is_ok()); + assert!(index(&vec![b'a'; 5 << 20]).is_err()); + } + + #[test] + fn every_argument_class() { + let file = read( + r#"f( + "s", ["a", "b",], [], name, True, + one = "//:x", + raw = r"a\b", + many = ["a", "b"], + table = {"k": "v", "l": ["x", "y"], "m": [],}, + none = {}, + flag = False, + # Everything below is an expression: never a guess. + joined = "p" + "q", + adjacent = "p" "q", + call = g("x"), + label = Label("//:x"), + chosen = select({"k": "v"}), + made = "{}".format(v), + old = "%s.txt" % v, + comp = [x for x in y], + keyed = {"//:" + os: "v" for os in ["a"]}, + number = 3, + minus = -1, + tuple = ("a", "b"), + wrapped = ("a"), + mixed = ["a", 1], + nested = [["a"]], + named = ["a", b], + values = {"k": 1}, + keys = {k: "v"}, + deep = {"k": {"l": "v"}}, + listed = {"k": ["a", ["b"]]}, + unset = {"k": "v" "w"}, + bad = "\x41", + if_else = "a" if c else "b", + *rest, + **more, + **{"k": "v"} +)"#, + ); + let call = &file.calls[0]; + let keyword = |name: &str| call.arg(name).unwrap_or_else(|| panic!("{name}")); + assert_eq!(call.positional(0), Some(&string("s"))); + assert_eq!(call.positional(1), Some(&list(&["a", "b"]))); + assert_eq!(call.positional(2), Some(&list(&[]))); + assert_eq!(call.positional(3), Some(&Value::Name("name".into()))); + assert_eq!(call.positional(4), Some(&Value::Name("True".into()))); + assert_eq!(call.positional(5), None, "a keyword is no position"); + assert_eq!(keyword("one"), &string("//:x")); + assert_eq!(keyword("raw"), &string(r"a\b")); + assert_eq!(keyword("many"), &list(&["a", "b"])); + let table = [ + ("k", string("v")), + ("l", list(&["x", "y"])), + ("m", list(&[])), + ]; + let table = table.map(|(key, value)| (key.to_string(), value)); + assert_eq!(keyword("table"), &Value::Dict(table.to_vec())); + assert_eq!(keyword("none"), &Value::Dict(Vec::new())); + assert_eq!(keyword("flag"), &Value::Name("False".into())); + for other in [ + "joined", "adjacent", "call", "label", "chosen", "made", "old", "comp", "keyed", + "number", "minus", "tuple", "wrapped", "mixed", "nested", "named", "values", "keys", + "deep", "listed", "unset", "bad", "if_else", + ] { + assert_eq!(keyword(other), &Value::Other, "{other}"); + } + let stars: Vec<(&How, &Value)> = (call.args.iter()) + .filter(|arg| matches!(arg.how, How::Star | How::StarStar)) + .map(|arg| (&arg.how, &arg.value)) + .collect(); + let dict = Value::Dict(vec![("k".into(), string("v"))]); + assert_eq!( + stars, + [ + (&How::Star, &Value::Name("rest".into())), + (&How::StarStar, &Value::Name("more".into())), + (&How::StarStar, &dict), + ] + ); + assert!(call.unpacks()); + assert!(!read("f(a, b = 1)").calls[0].unpacks()); + assert_eq!(call.args.len(), 5 + 29 + 3, "every argument is listed"); + assert_eq!(read("f()").calls[0].args, []); + assert_eq!(read("f(a,)").calls[0].args.len(), 1); + } + + #[test] + fn a_call_has_its_line_and_its_bytes() { + let src = "# one\nx = [\n pip.parse(\n a = 'b', # c\n ),\n]\n"; + let file = read(src); + let call = &file.calls[0]; + assert_eq!((call.callee.as_str(), call.line), ("pip.parse", 3)); + assert_eq!( + &src[call.span.clone()], + "pip.parse(\n a = 'b', # c\n )" + ); + assert_eq!(&src[call.args[0].span.clone()], "a = 'b'"); + } + + #[test] + fn the_callee_is_the_dotted_name_as_written() { + let callees = |src: &str| -> Vec { + let file = read(src); + file.calls.into_iter().map(|call| call.callee).collect() + }; + assert_eq!( + callees("a(1)\nb.c(2)\nd . e\\\n . f (3)"), + ["a", "b.c", "d.e.f"] + ); + // A call on a value that is computed is not one. + assert_eq!( + callees("f(x).g(y)\n'{}'.format(z)\nh[0].i()\nj()()"), + ["f", "j"] + ); + // Neither is a definition, nor a word of the language before `(`. + let words = "def f(a, b = g()):\n return (a)\nif (a) and (b) or not (c) in (d): pass\n\ + for (x) in (y): pass\nz = lambda (w): w\nprint(1)\n"; + assert_eq!(callees(words), ["g", "print"]); + assert_eq!(callees("load('//:a.bzl', 'b')"), ["load"]); + } + + /// Bazel reads a name that ends a line and a parenthesis that starts + /// the next one as two statements: any expression is a statement + /// (`Parser.parseSmallStatement` at 7.7.2, 8.8.2 and 9.3.2). + #[test] + fn a_parenthesis_that_starts_a_line_starts_a_statement() { + for src in [ + "f\n(1)\n", + "f # c\n(1)\n", + "x = f\n(1)\n", + "a.b\n(1)\n", + "f;(1)\n", + ] { + assert_eq!(read(src).calls, [], "{src:?}"); + } + // In a bracket and after a backslash the line goes on. + for src in ["[f\n(1)]\n", "f \\\n(1)\n", "g(f\n(1))\n"] { + assert_eq!(calls(&read(src), "f").len(), 1, "{src:?}"); + } + } + + #[test] + fn where_a_call_stands() { + let file = read( + "a(b(c()), [d()])\n\ + x = [e(v) for v in f(1)]\n\ + {g(): h() for k in l}\n\ + s(t = [m() for u in n()], w = aa())\n\ + bb()\n\ + [cc() and 0for dd in ee()]\n", + ); + let stands = |callee: &str| { + let call = calls(&file, callee)[0]; + (call.in_call, call.in_comprehension) + }; + for (callee, want) in [ + ("a", (false, false)), + ("b", (true, false)), + ("c", (true, false)), + ("d", (true, false)), + ("e", (false, true)), + ("f", (false, true)), + ("g", (false, true)), + ("h", (false, true)), + ("s", (false, false)), + ("m", (true, true)), + ("n", (true, true)), + ("aa", (true, false)), + ("bb", (false, false)), + // A `for` right after a number is the `for` of a comprehension. + ("cc", (false, true)), + ("ee", (false, true)), + ] { + assert_eq!(stands(callee), want, "{callee}"); + } + } + + #[test] + fn a_call_that_is_a_whole_statement_or_a_whole_right_side() { + let file = read( + "a()\nx = b()\nc() + 1\ny = d() if e else None\nf(); g()\nz = h(1)(2)\nw = i.j()\n\ + [k()]\nu, v = l()\nm(\n n(),\n)\nt = \\\n o()\n", + ); + let whole: Vec<&str> = (file.calls.iter()) + .filter(|call| call.whole) + .map(|call| call.callee.as_str()) + .collect(); + assert_eq!(whole, ["a", "b", "f", "g", "i.j", "m", "o"]); + } + + #[test] + fn a_name_means_what_the_last_statement_bound_it_to() { + let file = read( + "pip = use_extension('@rules_python//python/extensions:pip.bzl', 'pip')\n\ + alias = pip\n\ + other = 1\n\ + same = True\n\ + pip.parse(hub_name = 'a')\n\ + alias.parse(hub_name = 'b')\n\ + unbound.parse(hub_name = 'c')\n\ + pip = 'rebound'\n\ + pip.parse(hub_name = 'd')\n\ + again = pip\n", + ); + let binds: Vec<(&str, usize, &Bound)> = (file.binds.iter()) + .map(|bind| (bind.name.as_str(), bind.line, &bind.to)) + .collect(); + assert_eq!( + binds, + [ + ("pip", 1, &Bound::Call(0)), + // `alias = pip` binds `alias` to what `pip` is. + ("alias", 2, &Bound::Call(0)), + ("other", 3, &Bound::Other), + // A name the file has not bound is no alias. + ("same", 4, &Bound::Other), + ("pip", 8, &Bound::Other), + ("again", 10, &Bound::Other), + ] + ); + let bound: Vec<(&str, Option)> = (file.calls.iter()) + .map(|call| (call.callee.as_str(), call.bind)) + .collect(); + assert_eq!( + bound, + [ + ("use_extension", None), + ("pip.parse", Some(0)), + ("alias.parse", Some(1)), + ("unbound.parse", None), + ("pip.parse", Some(4)), + ] + ); + // The right side of an alias is not a use of the name; `True` is. + let uses: Vec<&str> = file.uses.iter().map(|used| used.name.as_str()).collect(); + assert_eq!(uses, ["True"]); + } + + #[test] + fn load_binds_its_symbols() { + let file = read( + "load('@rules_python//python:pip.bzl', 'pip_parse', parse = 'pip_parse', bad = 1)\n\ + pip_parse(name = 'a')\n\ + parse(name = 'b')\n\ + f(load('//:x.bzl', 'inner'))\n\ + inner()\n\ + load = g\n\ + load('//:y.bzl', 'late')\n\ + late()\n", + ); + let loaded = |symbol: &str| Bound::Loaded(0, symbol.into()); + let binds: Vec<(&str, &Bound)> = (file.binds.iter()) + .map(|bind| (bind.name.as_str(), &bind.to)) + .collect(); + assert_eq!( + binds, + [ + ("pip_parse", &loaded("pip_parse")), + ("parse", &loaded("pip_parse")), + // A `load` inside a call, and one after `load` was bound + // to something else, bind nothing. + ("load", &Bound::Other), + ] + ); + assert_eq!( + file.calls[0].positional(0), + Some(&string("@rules_python//python:pip.bzl")) + ); + assert_eq!(calls(&file, "pip_parse")[0].bind, Some(0)); + assert_eq!(calls(&file, "parse")[0].bind, Some(1)); + assert_eq!(calls(&file, "inner")[0].bind, None); + assert_eq!(calls(&file, "late")[0].bind, None); + } + + /// The names bound to one loaded symbol hold its name once: a copy + /// each would be the square of the file. + #[test] + fn the_names_of_one_loaded_symbol_share_it() { + let (symbol, aliases) = ("s".repeat(32 << 10), "a=s\n".repeat(8 << 10)); + let src = format!("load('//:f.bzl', s = '{symbol}')\n{aliases}"); + let file = read(&src); + assert_eq!(file.binds.len(), (8 << 10) + 1); + let mut held = std::collections::BTreeMap::new(); + for bind in &file.binds { + let Bound::Loaded(_, symbol) = &bind.to else { + panic!("{:?}", bind.name); + }; + held.insert(symbol.as_ptr(), symbol.len()); + } + assert!(held.values().sum::() <= src.len()); + } + + #[test] + fn every_use_of_a_name_but_calling_it_is_listed() { + let file = read( + "pip = use_extension('//:e.bzl', 'pip')\n\ + pip.parse()\n\ + use_repo(pip, 'hub')\n\ + use_repo(npm, pip = 'hub')\n\ + f(x = pip)\n\ + g = pip.parse\n\ + h = [pip]\n\ + pip += 1\n\ + a, pip = 1, 2\n\ + [pip.tag() for pip in x]\n\ + i(*pip)\n\ + j = pip if k else None\n", + ); + let lines: Vec = (file.uses.iter()) + .filter(|used| used.name == "pip") + .map(|used| { + assert_eq!(used.bind, Some(0), "line {}", used.line); + used.line + }) + .collect(); + // Line 2 calls a tag on it, line 4 names a keyword argument. + assert_eq!(lines, [3, 5, 6, 7, 8, 9, 10, 11, 12]); + // The use on line 3 is where the first argument of the call is. + let handed = &calls(&file, "use_repo")[0].args[0]; + assert_eq!(handed.value, Value::Name("pip".into())); + assert_eq!(file.uses[0].at, handed.span.start); + } + + #[test] + fn a_name_that_may_be_given_a_value_is_marked() { + let file = read( + "a, b = c, d\n\ + (e) = f\n\ + [g, [h]] = i\n\ + x = [j(k) for l, (m, n) in o if p for q in r]\n\ + s = t\n\ + u(v = w)\n\ + y.z = aa; bb[cc] = dd\n\ + [ee and 0for ff in gg]\n\ + hh == ii\n\ + [jj for kk[ll in mm], nn in oo]\n\ + [pp for qq[[rr for ss in tt][0]], uu in vv if ww in xx]\n", + ); + let assigned: Vec<&str> = (file.uses.iter()) + .filter(|used| used.assigned) + .map(|used| used.name.as_str()) + .collect(); + // The targets of an assignment that is not `name = ...` and the + // variables of a comprehension, also after an `in` or a whole + // comprehension inside an item they index; `y`, `bb`, `cc` and + // what stands in such an index are read, and marked all the same. + assert_eq!( + assigned, + [ + "a", "b", "e", "g", "h", "l", "m", "n", "q", "y", "bb", "cc", "ff", "kk", "ll", + "mm", "nn", "qq", "rr", "ss", "tt", "uu" + ] + ); + let read: Vec<&str> = (file.uses.iter()) + .filter(|used| !used.assigned) + .map(|used| used.name.as_str()) + .collect(); + assert_eq!( + read, + [ + "c", "d", "f", "i", "k", "o", "p", "r", "t", "w", "aa", "dd", "ee", "gg", "hh", + "ii", "jj", "oo", "pp", "vv", "ww", "xx" + ] + ); + } + + #[test] + fn a_rule_named_in_a_comment_or_a_string_is_no_call() { + let file = read( + "# pip.parse(requirements_lock = '//:a.txt')\n\ + \"\"\"pip.parse(requirements_lock = '//:b.txt')\"\"\"\n\ + x = \"pip.parse(requirements_lock = '//:c.txt')\" # pip.parse()\n\ + y = 'use_extension(\"//:e.bzl\", \"pip\")'\n", + ); + assert_eq!(file.calls, []); + assert_eq!(file.binds.len(), 2); + } + + /// What must hold of whatever a file is read as. + fn sound(src: &[u8]) { + let Ok(tokens) = tokens(src) else { + assert!(index(src).is_err()); + return; + }; + let mut end = 0; + for (at, token) in tokens.iter().enumerate() { + assert!(end <= token.start && token.start < token.end && token.end <= src.len()); + end = token.end; + let _ = value(src, token); + if matches!(token.kind, Kind::Open | Kind::Close) { + assert_eq!(tokens[token.mate].mate, at); + } + } + let file = index(src).unwrap(); + for call in &file.calls { + assert!(call.span.start < call.span.end && call.span.end <= src.len()); + assert_eq!(src[call.span.end - 1], b')'); + assert!(call.bind.is_none_or(|bind| bind < file.binds.len())); + for arg in &call.args { + assert!(call.span.start < arg.span.start && arg.span.end < call.span.end); + } + } + for bind in &file.binds { + assert!( + !matches!(bind.to, Bound::Call(call) | Bound::Loaded(call, _) if call >= file.calls.len()) + ); + } + } + + #[test] + fn no_bytes_make_it_panic() { + let sample = "module(name = 'm') # c\n\ + pip = use_extension(\"@rules_python//python/extensions:pip.bzl\", \"pip\")\n\ + [pip.parse(a = r'\\x', b = {\"k\": [\"v\"]}, **{'c': '''d\ne'''}) for v in w]\n\ + load('//:a.bzl', 'b', c = \"d\")\nx = y; z = lambda q: q(1.5e3)\n"; + let table: [&[u8]; 24] = [ + b"", + b"\0", + b"\0\0\0(", + b"\xff\xfe\xfd", + b"\xef\xbb\xbfx = 1", + b"\"", + b"'", + b"'''", + b"\"\"\"\"", + b"r\"", + b"\\", + b"\\\n", + b"\\\r", + b"a.", + b".a(", + b"a.b.", + b"f(=)", + b"f(**)", + b"f(a=)", + b"= =", + b"x = ", + b"f(,,,)", + b"[for]", + b"lambda: lambda:,", + ]; + for src in table { + sound(src); + } + // The sample cut at every byte, with every byte replaced by each + // of a few that open, close or end something, and random bytes. + let bytes = sample.as_bytes(); + for at in 0..=bytes.len() { + sound(&bytes[..at]); + sound(&bytes[at..]); + for swap in *b"\0\n\\\"'()[]{},=.#:*\xff" { + let mut changed = bytes.to_vec(); + if let Some(byte) = changed.get_mut(at) { + *byte = swap; + } + sound(&changed); + } + } + let mut rng = Rng::new(7); + let alphabet = b"ab.=,:*()[]{}\"'\\\n #r\0\xff\xc3\xa9"; + for _ in 0..4000 { + let len = rng.below(60); + let random: Vec = (0..len) + .map(|_| alphabet[rng.below(alphabet.len())]) + .collect(); + sound(&random); + } + } + + /// The largest file that is read, in each shape that nests or repeats + /// without end, and with one long thing that many names stand for. One + /// pass over 1 MiB takes well under a second; a pass that walked the + /// nesting again at each level, or copied the long thing for each + /// name, would take 10^12 steps. + #[test] + fn the_work_grows_with_the_size_of_the_file() { + let fill = |unit: &str, tail: &str| -> Vec { + let times = MAX_BYTES / (unit.len() + tail.len()); + let mut src = unit.repeat(times); + src.push_str(&tail.repeat(times)); + src.into_bytes() + }; + let started = std::time::Instant::now(); + for (unit, tail) in [ + ("(", ""), + ("(", ")"), + ("[", "]"), + ("f(", ")"), + ("f(x=[", "])"), + ("f([\"a\",", "])"), + ("f({\"k\":[\"a\"],", "})"), + ("[f() for x in ", "]"), + ("f(lambda:", ")"), + ("lambda:[", "]"), + ("[x for x in ", "]"), + ("a,", "=b"), + ("a=", "1for b in c\n"), + ("1.", "e"), + ("0x", "0b"), + ("a.", "b()"), + ("a=b\n", ""), + ("a=a\n", ""), + ("x=f()\n", ""), + ("f(a,b,c,d)\n", ""), + ("\"\\", ""), + ("\"a\" ", ""), + ("'''", ""), + ("a ", ""), + ("\n", ""), + ("# \\\n", ""), + ("\0", ""), + ("\u{e9}", ""), + ] { + let src = fill(unit, tail); + assert!( + src.len() <= MAX_BYTES && src.len() > MAX_BYTES - 64, + "{unit:?}" + ); + sound(&src); + } + let (long, args) = ("s".repeat(MAX_BYTES / 2), "x,".repeat(MAX_BYTES / 4)); + for head in [ + format!("load('//:f.bzl', s = '{long}')\n"), + format!("s = f({args})\n"), + ] { + let names = "a=s\n".repeat((MAX_BYTES - head.len()) / 4); + sound(format!("{head}{names}").as_bytes()); + } + let took = started.elapsed(); + assert!(took < std::time::Duration::from_secs(120), "{took:?}"); + } +} diff --git a/crates/socket-patch-core/src/bazel/workspace.rs b/crates/socket-patch-core/src/bazel/workspace.rs new file mode 100644 index 000000000..b4e9a3f5c --- /dev/null +++ b/crates/socket-patch-core/src/bazel/workspace.rs @@ -0,0 +1,1863 @@ +//! The files of a Bazel workspace that say which locks its rules read, and +//! the calls in them: `MODULE.bazel` and the files it includes. +//! +//! [`Workspace::read`] reads those files through a view, so the same code +//! serves a checkout on disk ([`disk`]) and files held in memory, and +//! [`Workspace::tags`] answers "which calls of this tag of this module +//! extension does the workspace make". An extension is known by the module +//! and the `.bzl` file that define it, never by the name a file gives its +//! proxy: `go_sdk.from_file` and `go_deps.from_file` take the same `go_mod`. +//! +//! Nothing is evaluated ([`super::starlark`]), so an answer comes with +//! [`Doubt`]s: what could not be read, and so may hide a call or change +//! one. They are the workspace's ([`Workspace::doubts`]) and the answer's +//! own ([`Tags::doubts`]). With neither, the calls listed are the calls +//! of that tag which the files of a workspace Bazel accepts can make; the +//! tests name every way found so far to write one that would not be +//! listed. Whether a listed call runs is told by [`Call::whole`] alone, +//! and what Bazel is told outside these files (`--ignore_dev_dependency`, +//! an override on the command line) is not known here. +//! +//! Reading and each query look at every byte, call, binding and use a +//! bounded number of times, so their work grows with the size of the +//! files, which is bounded too. +//! +//! `WORKSPACE` files and the `.bzl` files they load are not read yet. + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{ErrorKind, Read as _}; +use std::path::Path; + +use super::starlark::{self, Bound, Call, File, How, Value, MAX_BYTES}; +use crate::utils::fs::open_regular_file_sync; + +/// How many files of one workspace are asked for, and how many bytes are +/// read in all. +const MAX_FILES: usize = 256; +const MAX_TOTAL: usize = 8 << 20; + +/// What a view of the workspace has at a path. The path is from the Bazel +/// root, with `/` between its parts. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + Text(String), + Absent, + /// There is something, and this is why it is not text to read. + Unreadable(String), +} + +/// The view of the checkout at `root`, the Bazel root. It opens nothing +/// outside it: a path or a link that leads out is unreadable, like a +/// directory, a file that is not UTF-8 and one over [`MAX_BYTES`]. +pub fn disk(root: &Path) -> impl Fn(&str) -> Entry + '_ { + move |path| { + let read = || -> std::io::Result { + let real = std::fs::canonicalize(root.join(path))?; + if !real.starts_with(std::fs::canonicalize(root)?) { + return Err(std::io::Error::other("it leads out of the Bazel workspace")); + } + let (file, meta) = open_regular_file_sync(&real)?; + if meta.len() > MAX_BYTES as u64 { + return Err(std::io::Error::other("it is larger than 1 MiB")); + } + let mut text = String::new(); + file.take(MAX_BYTES as u64).read_to_string(&mut text)?; + Ok(text) + }; + let unreadable = |why: &str| Entry::Unreadable(why.to_string()); + match read() { + Ok(text) => Entry::Text(text), + Err(e) => match e.kind() { + ErrorKind::NotFound | ErrorKind::NotADirectory => Entry::Absent, + ErrorKind::InvalidData => unreadable("it is not UTF-8"), + // The opener's own words for a directory or a FIFO name + // the path on this machine. + ErrorKind::InvalidInput => unreadable("it is not a regular file"), + _ => unreadable(&e.to_string()), + }, + } + } +} + +/// The repository a label is in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Repo { + /// The main repository: no `@`, `@//` or `@@//`. + Main, + /// `@name//`: a name the workspace gives a repository. It is the main + /// repository when it is the root module's own ([`Workspace::label`]). + Apparent(String), + /// `@@name//`: another repository by its canonical name. + Canonical(String), +} + +/// A label that names a file of a repository. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Label { + pub repo: Repo, + /// Empty for the package at the root. + pub package: String, + pub name: String, +} + +impl Label { + /// `text` as a label written in `package`: `//pkg:name`, `//pkg` (the + /// name is its last part), `:name` and `name` (in `package`), each + /// after `@repo` or `@@repo` or not, and `@repo` alone. `None` when it + /// is none of them or a part of it is empty, `.` or `..`: the path of + /// a label never leaves its repository. + pub fn parse(text: &str, package: &str) -> Option