diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index e746a4755..ae2b3a8ba 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -3,7 +3,8 @@ name: Bazel patch compatibility (NuGet) # The NuGet flows of the real-Bazel tests (`nuget::` in `e2e_bazel_build`): # hosted mode for a package that rules_csharp's `nuget.from_lock` reads from # `packages.lock.json` and `nuget.config`, and for a tag that names no -# `nuget_config`, on each Bazel release below. +# `nuget_config`, and vendored mode for the same package, through the block +# it keeps in `MODULE.bazel`, on each Bazel release below. # bazel-compatibility.yml holds the legs and what every ecosystem shares; # this file says when the NuGet legs run and on which releases. # @@ -39,9 +40,14 @@ on: # `rollback`, and the hosted scan's check of that folder. Then what # reads the tag in `MODULE.bazel`: the reader of the workspace files, # which every ecosystem's flow shares (bazel/mod.rs, starlark.rs and - # workspace.rs), and what hosted mode makes of the tag (bazel/nuget.rs). - # vendor/nuget_feed.rs is the vendored backend; it is here for the - # version and folder helpers that every one of those files calls. + # workspace.rs), and what hosted and vendored mode make of the tag + # (bazel/nuget.rs). vendor/nuget_feed.rs is the vendored backend, which + # the vendored flow runs; every one of those files calls its version + # and folder helpers. The vendored flow also runs through the block of + # `MODULE.bazel` (bazel/block.rs), what bazel/maven.rs shares with it + # (the label of a `use_extension` and the release of a ruleset), what + # names the Bazel release and the rc files (bazel/rc.rs), and the + # dispatch of the refusals of vendored mode (vendor/refusals.rs). # Nothing else that another ecosystem's flow owns is here, so any other # change to one ecosystem starts that ecosystem's legs only. # @@ -70,8 +76,12 @@ on: - 'crates/socket-patch-core/src/vex/discover/nuget.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs' - 'crates/socket-patch-cli/src/commands/scan/hosted/nuget.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' + - 'crates/socket-patch-core/src/bazel/block.rs' + - 'crates/socket-patch-core/src/bazel/maven.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.rs' + - 'crates/socket-patch-core/src/bazel/rc.rs' - 'crates/socket-patch-core/src/bazel/starlark.rs' - 'crates/socket-patch-core/src/bazel/workspace.rs' push: @@ -80,8 +90,11 @@ on: # root of the test target (it changes when an ecosystem's module is # added; ci.yml builds the target and runs its hermetic tests on every # pull request), the shared engine code and test helpers the flow runs - # through, `vex`, whose verdicts the flow asserts, and the toolchain - # files. A main push outside this list waits for the nightly run below. + # through, `vex`, whose verdicts the flow asserts, the ledger and the + # artifact paths of vendored mode (vendor/state.rs and vendor/path.rs, + # which every ecosystem shares: they hold the record of the block and + # the place of a hub's package), and the toolchain files. A main push + # outside this list waits for the nightly run below. paths: - '.github/workflows/bazel-nuget.yml' - '.github/workflows/bazel-compatibility.yml' @@ -97,14 +110,20 @@ on: - 'crates/socket-patch-core/src/vex/discover/nuget.rs' - 'crates/socket-patch-core/src/patch/redirect/upstream/nuget.rs' - 'crates/socket-patch-cli/src/commands/scan/hosted/nuget.rs' + - 'crates/socket-patch-core/src/vendor/refusals.rs' + - 'crates/socket-patch-core/src/bazel/block.rs' + - 'crates/socket-patch-core/src/bazel/maven.rs' - 'crates/socket-patch-core/src/bazel/mod.rs' - 'crates/socket-patch-core/src/bazel/nuget.rs' + - 'crates/socket-patch-core/src/bazel/rc.rs' - 'crates/socket-patch-core/src/bazel/starlark.rs' - 'crates/socket-patch-core/src/bazel/workspace.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-core/src/vex/**' + - 'crates/socket-patch-core/src/vendor/path.rs' + - 'crates/socket-patch-core/src/vendor/state.rs' - 'crates/socket-patch-cli/src/commands/**' - 'crates/socket-patch-cli/tests/common/**' - 'crates/socket-patch-cli/tests/hosted_memory_common/**' diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bc390b2e6..bcea04959 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -122,7 +122,7 @@ Every subcommand accepts the same set of "global" flags via a single shared `Glo | `--no-vlt-install-cleanup` | — | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `false` | bool | Opt out of hosted mode's warm-tree heal for vlt: stale installed copies (`node_modules/.vlt-lock.json` and the stale `node_modules/.vlt/` entries) are left in place after `vlt-lock.json` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`), and the `redirect_vlt_reinstall_required` advisory tells you to run `vlt ci` instead. Stale copies of optional dependencies are always left in place (see `redirect_vlt_reinstall_required`). Other subcommands accept it silently | | `--no-gem-install-refresh` | — | `SOCKET_NO_GEM_INSTALL_REFRESH` | `false` | bool | Opt out of hosted mode's gem stale-install refresh: the gems Bundler already holds for the project (an installed gem under the project and its cached `.gem`, an archive in `vendor/cache`) are left as they are after `Gemfile.lock` is repointed (`scan`/`get --mode hosted`) or restored (`rollback`/`remove`, of a hosted pin or of a vendored gem; `vendor --revert`), and the `redirect_gem_stale_install` / `upstream_gem_stale_install` warning names the files to remove by hand instead (see the "Gem stale-install guard" section). Other subcommands accept it silently | | `--gem-refresh-shared` | — | `SOCKET_GEM_REFRESH_SHARED` | `false` | bool | Extend the gem stale-install refresh to gem homes OUTSIDE the project (the system gems, `~/.gem`, an rbenv or asdf home) and to project bundle or cache paths that resolve outside the project directory. Off by default: another project on the machine may pin the other build of the same gem version, and its `bundle pristine` then fails on the replaced archive's checksum (see the "Gem stale-install guard" section). Other subcommands accept it silently | -| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default; the one refusal it lifts today is `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. The switch is not specific to Composer: any refusal of vendored mode that rests on the Bazel workspace reads this one. For a project whose build does find the copy. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | Let vendored mode write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. Vendored mode declines such a package by default; it lifts two refusals today. `vendor_composer_bazel_workspace`: the lock then names the patched copy by a path relative to the directory Composer runs in, and a Bazel rule that runs `composer install` anywhere else fails on it. `vendor_nuget_bazel_workspace`: the package is then vendored as in a project without Bazel, which a rules_csharp hub does not take, and its build fails. Any refusal of vendored mode that rests on the Bazel workspace reads this one switch. For a project whose build does find the copy, or which Bazel does not build. Read by `vendor`, `scan --mode vendored` and `get --mode vendored`; other subcommands accept it silently. See docs/ecosystems.md "Bazel workspaces: Composer" and "Bazel workspaces: NuGet" | **`--download-mode` removed (v5.0, MAJOR).** The global `--download-mode` flag and its `SOCKET_DOWNLOAD_MODE` binding are gone, with no alias: passing the flag is a usage error (exit 2) and the env var is ignored. Patch content is always fetched as per-file blobs (`.socket/blobs/`); `.socket/diffs/` archives are obsolete, never read, and removed by the cleanup sweeps. @@ -1734,7 +1734,7 @@ to **six flavors**. | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | | pypi / pipenv (Pipfile.lock) | (rebuilt wheel) | lock-only: the `default`/`develop` entry → `{file, hashes:[sha256-of-our-wheel]}`. Pipfile + `_meta.hash` untouched. Emits `vendor_integrity_unverified` — pipenv does not hash-check file entries; the committed wheel bytes are the protection — and, when another entry is hashed, `pypi_pipenv_hash_export_unsupported` (`pipenv requirements --hash` drops the vendored wheel's hash) | `pipenv install --deploy` (+ `pipenv verify`), cold cache | | pypi / requirements.txt (pip / `uv pip`) | (rebuilt wheel) | pin line → `./` (markers carried over; transitive deps appended), plus `--hash=sha256:` only when the requirements tree is already in pip's hash-checking mode (any `--hash` or `--require-hashes`) | `pip install -r` / `uv pip install -r` **run from the project root** (both resolve bare paths against the CWD) | -| nuget | deterministically rebuilt `.nupkg` at `..nupkg` (the uuid dir IS a NuGet folder feed; the stale embedded signature is dropped — unsigned is accepted under NuGet's default validation), plus `/.gitignore` (`!*`: re-includes the nupkg against the project's ignores, such as VisualStudio.gitignore's `*.nupkg`); refuses `vendor_artifact_gitignored` when git would still drop it | `nuget.config` source + `packageSourceMapping` for the id (creating the mapping from scratch ALSO fans a `` out to every pre-existing source, including the ones NuGet inherits from the user config and parent directories' configs (v5.0 #354), none at all when an inherited config already maps packages — mapping is exclusive, NU1100 otherwise; another source's exact pattern for the id is set aside in a comment while vendored, `vendor_nuget_mapping_set_aside`, #462) **+** `packages.lock.json` `contentHash` → `base64(sha512(nupkg))` for the entries at the patched version in every lock a project under the root restores into — the root `packages.lock.json`, member projects' locks, `packages..lock.json`, a literal `NuGetLockFilePath` (v5.0 #353/#514; an unevaluable `NuGetLockFilePath` is refused with `vendor_nuget_lock_path_unresolved`) — (`vendor_nuget_no_lockfile` warning when there is none; a lock that also resolves the id at another version is refused with `vendor_nuget_lock_other_version`, nothing written) | `dotnet restore --locked-mode`, cold cache, `--network none` (tampered nupkg fails NU1403) | +| nuget | deterministically rebuilt `.nupkg` at `..nupkg` (the uuid dir IS a NuGet folder feed; for a package of a rules_csharp hub in a Bazel workspace the file lies at `//..nupkg`, `nuget.config` names that directory and the root `MODULE.bazel` gains one managed block, or the package is declined with `vendor_nuget_bazel_workspace`, see docs/ecosystems.md "Bazel workspaces: NuGet"; the stale embedded signature is dropped — unsigned is accepted under NuGet's default validation), plus `/.gitignore` (`!*`: re-includes the nupkg against the project's ignores, such as VisualStudio.gitignore's `*.nupkg`); refuses `vendor_artifact_gitignored` when git would still drop it | `nuget.config` source + `packageSourceMapping` for the id (creating the mapping from scratch ALSO fans a `` out to every pre-existing source, including the ones NuGet inherits from the user config and parent directories' configs (v5.0 #354), none at all when an inherited config already maps packages — mapping is exclusive, NU1100 otherwise; another source's exact pattern for the id is set aside in a comment while vendored, `vendor_nuget_mapping_set_aside`, #462) **+** `packages.lock.json` `contentHash` → `base64(sha512(nupkg))` for the entries at the patched version in every lock a project under the root restores into — the root `packages.lock.json`, member projects' locks, `packages..lock.json`, a literal `NuGetLockFilePath` (v5.0 #353/#514; an unevaluable `NuGetLockFilePath` is refused with `vendor_nuget_lock_path_unresolved`) — (`vendor_nuget_no_lockfile` warning when there is none; a lock that also resolves the id at another version is refused with `vendor_nuget_lock_other_version`, nothing written) | `dotnet restore --locked-mode`, cold cache, `--network none` (tampered nupkg fails NU1403) | | maven | the patched `.jar` + the upstream pom (its `` suffixed, and what it inherits from its parents through `${project.version}` declared at the base version between `socket-patch:inherited` markers, so it resolves what the upstream pom does; transitives survive) + `.sha1` sidecars + an ownership marker under `.socket/vendor/maven2///-socket./`; every JVM tree root (`.socket/vendor/maven2`, Gradle's `.socket/vendor/gradle`, Coursier's `.socket/vendor/coursier`) owns a `.gitignore` (`!*`) that re-includes the jars against the project's ignores, such as Java.gitignore's `*.jar`, plus a `.gitattributes` (`-text`); a tree root git ignores itself refuses `vendor_artifact_gitignored` | every pom root, single-module (a reactor of one) or multi-module: the pinned `` + `` pin, `.mvn/maven.config` (`maven.repo.local.tail`) and the `socket-patch-vendor` fallback file repository (`checksumPolicy=fail`); Gradle, sbt and scala-cli roots go to the same JVM backend (ledger ecosystem `jvm`). Pre-v5 `maven_pom_repository` entries (`` to `.socket/vendor/maven/`) are revert-only: vendoring their root is refused (`vendor_jvm_shape_unsupported`, `legacy_maven_root`) | `mvn` build on a fresh checkout with a warm local repository and behind `mirrorOf external:*` (host capstone `e2e_vendor_maven_build` across the Maven matrix) | Ecosystems with no vendor backend (jsr) refuse per-purl with @@ -2227,7 +2227,7 @@ Empty string means unset at every layer: exported-but-empty flag-bound vars are | `SOCKET_NO_VLT_INSTALL_CLEANUP` | `--no-vlt-install-cleanup` | `false` | Hosted mode, `rollback`, `remove`: keep stale vlt installed copies. | | `SOCKET_NO_GEM_INSTALL_REFRESH` | `--no-gem-install-refresh` | `false` | Hosted mode, `rollback`, `remove`: leave the project's stale installed gems and cached archives alone. | | `SOCKET_GEM_REFRESH_SHARED` | `--gem-refresh-shared` | `false` | Hosted mode, `rollback`, `remove`: also refresh stale gems in gem homes outside the project. | -| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy. | +| `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `--allow-vendored-in-bazel` | `false` | Vendored mode: write for a package although the project is in a Bazel workspace, where the build may not find the vendored copy (`vendor_composer_bazel_workspace`, `vendor_nuget_bazel_workspace`). | | `SOCKET_PATCH_VERSION` | `--update ` | (latest) | Local to `--update`; the same pin `install.sh` honors. | | `SOCKET_BATCH_SIZE` | `scan --batch-size` | `500` authenticated / `100` proxy | Local to `scan`. | | `SOCKET_MAX_NEW_PATCHES` | `scan --max-new-patches` | (unlimited) | Local to `scan` (v5.0): a count or `none`; empty is unset, malformed exits 2. | @@ -2537,6 +2537,7 @@ command's integration tests check its output. | `vendor_bun_lockb_invalid` | `failed` | vendor / scan / get `--mode vendored`: the binary lock is malformed, unreadable, unsupported or cannot be rewritten safely. The detail names the parser, hash or filesystem error. Refused before patch downloads and before hosted takeover; the package's `failed` event carries `errorCode` and `error`, while `get ` also carries top-level `error.code`. Dry-run predicts the same refusal. | | `vendor_bun_workspace_unsupported` | `failed` | vendor / scan / get `--mode vendored` (bun): the text lock holds `workspace:` packages and its `lockfileVersion` is below 2 — Bun 1.2–1.3 resolve a workspace member's local-tarball path relative to the member; a committed version-2 lock is the proof every consumer runs Bun ≥ 1.4 (deliberate over-approximation: root-only declared packages would install on version 1 too). Detail names the version integer and a version-specific remedy: delete `bun.lock` and re-lock with Bun ≥ 1.4 (an in-place `bun install` keeps the existing version) — then, for a version-1 lock, "or use `--mode hosted`, which accepts version-1 workspace locks"; for a version-0 lock, "or delete `bun.lock`, re-lock with Bun ≥ 1.2 (which writes lockfileVersion 1) and use `--mode hosted`" (hosted refuses version-0 workspace locks, so a bare hosted pointer would send the user into a second refusal). Refused before any write — in the pre-download preflight on `get`/`scan` (see `vendor_bun_lockb_invalid` for the placements); in the shared preflight that `vendor` and the vendor step run BEFORE a hosted → vendored takeover's revert (a hosted-redirected purl stays hosted-wired, ledger and lock untouched; `vendor --dry-run` previews the same `failed` code); and in the engine when the run would write a NEW local tuple. Exempt: purls the vendor ledger wires at the selected uuid, purls whose every `bun.lock` instance is already a `.socket/vendor/npm/` tuple (any uuid), in-sync re-runs and `repair` redownloads. | | `vendor_composer_bazel_workspace` | `failed` | vendor / scan / get `--mode vendored` (composer): the project is in a Bazel workspace (its directory, or one above it up to the root of its git checkout, holds `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`). Vendored mode makes `composer.lock` name the patched copy by a path relative to the directory Composer runs in; a Bazel repository rule or build action that runs `composer install` from the lock anywhere else fails with Composer's `Source path "…" is not found for package …`, and the build with it (Bazel 9.3.2, 8.8.2, 7.7.2). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1, as it does every refusal. The detail names the Bazel root and the mode that writes no such path, `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel`, `vendor --revert`, and a package whose `composer.lock` entry already names the copy of the same patch (the run leaves the lock as it is, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included; a new patch for it is refused). A project that commits its `vendor/` tree is refused like any other: the tree shows that Composer has run in the project's directory, not that no rule of the workspace runs it elsewhere as well. See docs/ecosystems.md "Bazel workspaces: Composer". | +| `vendor_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | vendor / scan / get `--mode vendored` (nuget): a rules_csharp `nuget.from_lock` tag of the project's Bazel workspace reads a lock of the project, and the block that makes the hub take the committed package cannot be shown to work from the checkout. Vendored mode keeps such a package at `.socket/vendor/nuget////..nupkg`, names that directory in `nuget.config`, and appends one managed block to the root `MODULE.bazel`: a `nuget.from_lock` of its own whose `feeds` are `file:.socket/vendor/nuget/` for each vendored patch and then the sources the hub had without it (rules_csharp 0.5.0 on Bazel 9.3.2, 8.8.2, 7.7.2). It declines when: the project is not the root of its Bazel workspace, or another workspace lies above it in the checkout; the workspace has more than one `nuget.from_lock`, or its tags cannot be read with certainty; the tag is not a call of its own with every argument written out, is called on an isolated or dev-dependency `use_extension`, or has `local_package_dirs`, `netrc` or `auth_patterns`; its `nuget_config` cannot be read, or a package source cannot stand in a string; it has `feeds` and a `nuget_config` without a package source (the run names its folder there, and rules_csharp takes the sources of that file in place of `feeds`); `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0; the checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 (`.bazelversion` / `.bazeliskrc`); an rc file names `--repository_disable_download`, `--vendor_dir` or a remote downloader (`--experimental_remote_downloader`), or a directory at the root holds `VENDOR.bazel`; `MODULE.bazel` is a symbolic link, or its block was changed by hand; a lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`: the hub asks its feeds for the lock's spelling). Refused before any download and before a hosted → vendored takeover or eject (the hosted pin stays; the eject reports it under `eject_refused`, detail `kept hosted: …`); nothing is written; exit 1 / `partialFailure`; `scan` and `get` with `--dry-run` list the package as would-refuse (`skipped` with this code, exit 0), and `vendor --dry-run` reports it `failed` with exit 1. The detail names the reason, with the file and line where there is one, and `--mode hosted`. Not refused: a run with `--allow-vendored-in-bazel` (the package is vendored as without Bazel), `vendor --revert`, a package whose folder `nuget.config` already names (the run leaves the config as it is), and a project whose locks no `nuget.from_lock` reads, which is vendored as without Bazel. As an advisory event: a package that is vendored for the hub, whose block can no longer be shown to work or was changed by hand; the block is left as it is. The undo of such a package beside a block that was changed by hand fails and changes nothing (`revert_failed` from `vendor --revert`, `vendor_revert_failed` from `rollback` and `remove`; exit 1): the detail names the line of the block, and the lock restored beside it would fail the Bazel build. An undo that leaves `nuget.config` wired (`vendor_lock_entry_drifted`: the file was written anew and still names the folder) keeps the block with the lock pin and the package. See docs/ecosystems.md "Bazel workspaces: NuGet". | | `vendor_lockfile_missing` / `vendor_lockfile_version_unsupported` (bun preflight placement) | `failed` | scan / get `--mode vendored` (bun): the pre-download preflight found `bun.lock` unreadable / at a `lockfileVersion` other than 0 to 3 (a newer version: update socket-patch; no integer: re-lock with Bun ≥ 1.2 — the same text as hosted's `redirect_bun_lock_unsupported`) or outside bun's single-line `packages` grammar. Same placements as `vendor_bun_lockb_invalid`; nothing fetched, no patch record. An unreadable `.socket/vendor/state.json` met by the same preflight is `vendor_state_unreadable` (see that row), never one of these. | | `bun_lockb_invalid` | scan `warnings[]` (run-level) | scan (every mode): the native binary inventory could not parse or read `bun.lockb`; detail names the format or filesystem error. Also printed as `Warning: …` on stderr. Exit and status remain unchanged. The warning is retained on empty and non-empty scans; valid binary locks are inventoried normally without a runtime or install. | | `bun_lock_unsupported` | scan `warnings[]` (run-level) | scan (every mode): the text `bun.lock` is there but the lock reader refuses it — a `lockfileVersion` newer than 3, no integer version, or a `packages` section outside bun's single-line grammar (a comment line, a re-indent) — so the packages it lists were not read from the lockfile. Detail is the shared version gate's text or `bun.lock: line : …`, followed by `, so the packages it lists were NOT read from the lockfile: a package that is locked but not installed was not scanned`. Also printed as `Warning: …` on stderr, and a scan that then finds no package at all ends `No packages found (see the warning).` instead of advising an install. Status and exit are unchanged (0): before, a checkout without `node_modules` scanned as an empty project and the lock was not mentioned. Installed packages are still crawled, and hosted / vendored runs keep their own refusal (`redirect_bun_lock_unsupported` / `vendor_lockfile_version_unsupported`). The hosted in-memory engine reports the same code among its warnings. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2184c23ef..14956a741 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -427,11 +427,14 @@ pub struct GlobalArgs { /// Vendored mode (`vendor`, `scan`/`get --mode vendored`): write for a /// package although the project is in a Bazel workspace, where the /// build may not find the vendored copy. Vendored mode declines such - /// a package by default; today that is a Composer package + /// a package by default: a Composer package /// (`vendor_composer_bazel_workspace`), whose lock names the copy by a /// path that a Bazel rule running `composer install` in another - /// directory does not find. Pass it when the build does find the - /// copy. Other subcommands accept it silently. + /// directory does not find, and a NuGet package of a rules_csharp hub + /// where the `MODULE.bazel` block that makes the hub take the copy + /// cannot be shown to work (`vendor_nuget_bazel_workspace`). Pass it + /// when the build does find the copy, or does not build the project. + /// Other subcommands accept it silently. #[arg( help_heading = GLOBAL_OPTIONS, long = "allow-vendored-in-bazel", 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 dea1f4b94..116a41761 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -948,6 +948,21 @@ impl Cell { self.downloads = Some(rules.to_vec()); } + /// Take the file whose sha256 is `sha256` out of the repository cache, + /// which the tests of a leg and every twin share: whether it was + /// there. Bazel then has to fetch that file again from where its URLs + /// lead, as on a machine that never had it. + pub fn uncache(&self, sha256: &str) -> bool { + let cache = &self.scratch.repository_cache; + let entry = cache.join("content_addressable/sha256").join(sha256); + let held = entry.join("file").is_file(); + if held { + std::fs::remove_dir_all(&entry) + .unwrap_or_else(|e| panic!("remove {}: {e}", entry.display())); + } + held + } + /// Whether the repository cache of this cell, which its twins share, /// holds a download with the sha256 `sha256`: what Bazel's downloader /// keeps of a file it fetched under a checksum. diff --git a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs index a51c1b7e8..000686788 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -128,9 +128,25 @@ //! tag: the last tag with sources decides which config the hub reads, and //! the first lock that names a package gives its `contentHash`. //! +//! A third flow, [`vendored_from_lock`], runs vendored mode in the +//! fixture's workspace. `scan --mode vendored --yes` downloads the patched +//! package from the patch service once and keeps it under `.socket/vendor`, +//! at the path a feed of the hub has a package. It names that folder as a +//! package source in `nuget.config`, which NuGet takes, re-pins the lock, +//! and appends a block to `MODULE.bazel`: a `nuget.from_lock` of its own, +//! whose feeds are the folder of the patch, as a `file:` URL that Bazel +//! reads from the root of the workspace, and then the sources of the +//! config. The build then takes the committed package and asks no host for +//! it, also on a machine with no host to ask; a changed copy fails the +//! build; and `vendor --revert` puts every file back. Where the checkout +//! does not show that the block works (it names no Bazel release), the +//! command declines the package and writes nothing. +//! [`vendored_mode_keeps_the_block_or_declines`] holds the commands to the +//! same without a Bazel, with the other ways in and out. +//! //! # Known gaps //! -//! Three outcomes the flow asserts are gaps of the product, not its +//! Three outcomes the flows assert are gaps of the product, not its //! contract. Each is asserted as the release has it, and marked //! `KNOWN GAP` there with what a fix would change in this test: //! @@ -152,7 +168,7 @@ use serde_json::{json, Value}; use sha2::{Digest, Sha256, Sha512}; use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes; -use crate::envelope::{codes_in, event_triples}; +use crate::envelope::{all_codes as codes_of, codes_in, event_triples}; use crate::harness::{ cell_without_bazel, changed, fixture_path, rewrite, Cell, Fixture, Ran, StandIn, Tree, CONSUMER, NOTHING, @@ -205,6 +221,9 @@ const PATCH_HOST: &str = "patch.socket.dev"; const FLAT_CONTAINER: &str = "api.nuget.org/v3-flatcontainer"; /// The one command of hosted mode. const SCAN: [&str; 4] = ["scan", "--mode", "hosted", "--yes"]; +/// The one command of vendored mode, before the option that names the +/// patch service ([`vendored_scan`]). +const VENDORED: [&str; 4] = ["scan", "--mode", "vendored", "--yes"]; /// The sha256 of `bytes` in lowercase hex, as `MODULE.bazel.lock` and /// Bazel's downloader spell one. @@ -970,6 +989,621 @@ fn hosted_no_config() { ); } +/// `scan --mode vendored --yes ` in `cell`, on the machine whose .NET +/// home is `home`. The grant names the patched package by its URL on the +/// patch host, and vendored mode downloads it itself: `--patch-server-url` +/// sends that one download to `standin`, which serves the package there +/// under the path of that URL (`service` of [`service_route`]). +fn vendored_scan(cell: &Cell, standin: &StandIn, home: &Path, more: &[&str]) -> Ran { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin], more].concat(); + socket_patch(cell, standin, home, &args) +} + +/// Has `standin` serve the package of `patch` to vendored mode, and gives +/// the route: the path of the URL the grant names, without the prefix of +/// the patch host that a download of Bazel's carries on the stand-in. +fn service_route(standin: &StandIn, patch: &Patched) -> String { + let route = patch.file(&patch.package); + let service = route + .strip_prefix(&format!("/{PATCH_HOST}")) + .expect("a route of the patch host"); + standin.serve(5, service, &patch.package.nupkg); + service.to_string() +} + +/// Where vendored mode keeps what it wrote for `patch`: the folder of the +/// patch under the checkout's `.socket/vendor`. +fn vendor_dir(patch: &Patched) -> String { + format!(".socket/vendor/nuget/{}", patch.uuid) +} + +/// Where vendored mode keeps the package of `patch` for a hub, below +/// [`vendor_dir`]: the path at which a feed of rules_csharp has a package. +fn hub_copy(patch: &Patched) -> String { + let lower = patch.package.lower(); + format!( + "{}/{lower}/{VERSION}/{lower}.{VERSION}.nupkg", + vendor_dir(patch) + ) +} + +/// The block vendored mode keeps at the end of the fixture's `MODULE.bazel` +/// for the folder `dir` of a patch: the hub's own extension and lock, and +/// as feeds that folder, which Bazel reads from the root of the workspace, +/// and then the one source of the fixture's `nuget.config`. +fn block(dir: &str) -> String { + format!( + "# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and \ + removes it) >>>\n\ + socket_patch_nuget = use_extension(\"@rules_csharp//csharp:extensions.bzl\", \"nuget\")\n\ + socket_patch_nuget.from_lock(\n feeds = [\n \"file:{dir}\",\n \ + \"{SOURCE}\",\n ],\n packages_lock_json = \"//:{LOCK}\",\n)\n\ + # <<< socket-patch <<<\n" + ) +} + +/// The code with which vendored mode declines a package of a hub, where it +/// cannot show that its block works, and the file that names the Bazel +/// release of a checkout. +const DECLINED: &str = "vendor_nuget_bazel_workspace"; +const BAZEL_VERSION: &str = ".bazelversion"; + +/// For a finished vendored command that declined the package `purl`: it +/// failed with exit 1, its one event is the refusal, and the detail says +/// `why`, names hosted mode and the switch. +fn declined(test: &str, ran: &Ran, purl: &str, why: &str) { + let said = &ran.dump; + assert_eq!(ran.code, 1, "{test}: {said}"); + assert_eq!(ran.envelope["status"], "partialFailure", "{test}: {said}"); + let refusal = [(purl.to_string(), "failed".to_string(), DECLINED.to_string())]; + assert_eq!(event_triples(&ran.envelope), refusal, "{test}: {said}"); + let event = &ran.envelope["events"][0]; + let detail = event["error"].as_str().or(event["reason"].as_str()); + let detail = detail.unwrap_or_default(); + for part in [why, "`--mode hosted`", "`--allow-vendored-in-bazel`"] { + assert!(detail.contains(part), "{test}: no {part:?} in {detail:?}"); + } +} + +/// Vendored mode in the fixture's workspace, on the machine that restored +/// the project. +/// +/// - (a) The unpatched build. The checkout names no Bazel release, so +/// `scan --mode vendored --yes` declines the package: nothing is +/// downloaded or written, and the build stays the one of before. +/// - (b) With the release in `.bazelversion`, the same command downloads +/// the patched package from the patch service once and keeps it where a +/// feed of the hub has a package, names that folder in `nuget.config`, +/// re-pins the lock, and appends its block to `MODULE.bazel`. `vendor +/// --check` passes, `vex` attests the package, and `bazel query //...` +/// lists what it listed. Bazel's own lock is stale, as after a hosted +/// scan: a frozen lock fails until a build has updated it. +/// - (c) The build of (a) prints the patched marker, from the committed +/// copy: Bazel asks no host for the package. Then on a second machine, +/// with the stand-in stopped, a new output base and the package in no +/// repository cache, the build prints it again. +/// - (d) On a third machine, one byte of the committed package is another: +/// `vendor --check` fails, and so does the build, over the sha256 that +/// Bazel's lock pins. +/// - (e) `vendor --revert` puts every file back but Bazel's own lock, and +/// the next build prints the unpatched marker and writes the lock of +/// before. +#[test] +#[ignore = "real Bazel; run with --ignored"] +fn vendored_from_lock() { + let test = "nuget::vendored_from_lock"; + let started = Instant::now(); + let Some(mut cell) = Cell::open(test, &FIXTURE) else { + return; + }; + let release = cell.release().to_string(); + + let run = format!("R{}", uuid::Uuid::new_v4().simple()); + let upstream = Package::new(NAME, &run, &format!("PRISTINE {run}")); + let neighbour = Package::new(NEIGHBOUR, &run, "NEIGHBOUR"); + let patch = Patched::new(&run); + let (purl, unpatched, patched) = (upstream.purl(), upstream.marker(), patch.package.marker()); + let standin = registry(&[&neighbour, &upstream]); + grant(&standin, &upstream, &patch, &patch.package.nupkg); + let service = service_route(&standin, &patch); + cell.route_downloads(&downloads(&standin.origin())); + check_out(&cell, &run, &[&neighbour, &upstream]); + let home = tempfile::Builder::new() + .prefix("sp-bazel-nuget-") + .tempdir() + .expect("create the .NET home"); + for package in [&neighbour, &upstream] { + package.restore_into(home.path()); + } + let listing = |cell: &Cell| { + let query = cell.bazel("query", &["//..."]); + assert!(query.ok(), "{test}: {}", query.dump()); + query.stdout() + }; + + // (a) The unpatched build. No file of the checkout names the Bazel + // release that builds it, and the block is written for the releases it + // was built on alone: the command declines, with nothing downloaded + // and nothing written, and the build passes on the upstream package. + let unnamed = cell.builds_unpatched(&unpatched); + let scan = vendored_scan(&cell, &standin, home.path(), &[]); + let no_release = "no file of the checkout names the Bazel release that builds it"; + declined(test, &scan, &purl, no_release); + assert_eq!(standin.asked(&service), 0, "{test}: {}", scan.dump); + assert_eq!(changed(&unnamed, &cell.tree()), NOTHING, "{test}"); + cell.builds_patched(&unnamed, &unpatched); + + // (b) The checkout names its release, as a launcher reads it. + cell.write(BAZEL_VERSION, format!("{release}\n")); + let before = cell.tree(); + let targets = listing(&cell); + let scan = vendored_scan(&cell, &standin, home.path(), &[]); + let said = &scan.dump; + assert_eq!(scan.code, 0, "{test}: {said}"); + assert_eq!(scan.envelope["status"], "success", "{test}: {said}"); + assert_eq!(scan.envelope["summary"]["applied"], 1, "{test}: {said}"); + let event = |action: &str, code: &str| (purl.clone(), action.to_string(), code.to_string()); + let events = [ + event("downloaded", ""), + event("applied", ""), + event("skipped", "vendor_prebuilt_downloaded"), + // NuGet's folder holds the unpatched copy, which no build here reads. + event("skipped", "vendor_nuget_stale_global_package"), + ]; + assert_eq!(event_triples(&scan.envelope), events, "{test}: {said}"); + assert_eq!(standin.asked(&service), 1, "{test}: {said}"); + let vendored = cell.tree(); + let (dir, copy) = (vendor_dir(&patch), hub_copy(&patch)); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + copy.clone(), + ".socket/vendor/state.json".to_string(), + MODULE.to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(changed(&before, &vendored), written, "{test}: {said}"); + assert_eq!(vendored[©], patch.package.nupkg, "{test}: {copy}"); + // The config names the folder of the package, where NuGet finds it; + // the block names the folder of the patch, below which the hub does. + let folder = copy.rsplit_once('/').expect("a path").0; + let source = format!( + " \n", + patch.uuid + ); + let config = text(&vendored, CONFIG); + assert!(config.contains(&source), "{test}: {CONFIG}:\n{config}"); + assert_eq!( + text(&vendored, LOCK), + lock_pinning(&run, &[&neighbour, &patch.package]), + "{test}: {LOCK}" + ); + let appended = format!("{}\n{}", text(&before, MODULE), block(&dir)); + assert_eq!(text(&vendored, MODULE), appended, "{test}: {MODULE}"); + // `vendor --check` and `vex` see the package as any vendored one, and + // Bazel sees no package in the folder. + let check = socket_patch(&cell, &standin, home.path(), &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + let verified = [event("verified", "vendor_check_ok")]; + assert_eq!(event_triples(&check.envelope), verified, "{}", check.dump); + let document = cell.document("vendored"); + let output = document.to_string_lossy(); + let vex = socket_patch(&cell, &standin, home.path(), &["vex", "--output", &output]); + assert_eq!(vex.code, 0, "{test}: {}", vex.dump); + let attested = [event("verified", "")]; + assert_eq!(event_triples(&vex.envelope), attested, "{}", vex.dump); + // With its closing quote, as the document writes `"@id": ""`. + let written = std::fs::read_to_string(&document).unwrap_or_default(); + let names = written.contains(&format!("\"{purl}\"")); + assert!(names, "{test}: {}\n{written}", vex.dump); + assert_eq!(listing(&cell), targets, "{test}: `bazel query //...`"); + assert_eq!(changed(&vendored, &cell.tree()), NOTHING, "{test}"); + frozen_build_fails(&cell, "scan --mode vendored"); + + // (c) The build of (a) and no other step: patched, from the committed + // copy. Bazel asked the folder for the other package of the lock as + // well, warned that it is not there, and took it from nuget.org as + // before. It rewrote its own lock and no other file. + let build = cell.bazel("build", &[CONSUMER]); + assert!(build.ok(), "{test}: {}", build.dump()); + // A line of Bazel's is compared without white space, here and below: + // nothing says where a tool breaks a long line. + let squeezed = |text: &str| text.split_whitespace().collect::(); + let missed = format!("WARNING: Download from file:{dir}/{}/", neighbour.lower()); + assert!( + squeezed(&build.stderr()).contains(&squeezed(&missed)), + "{test}: no {missed:?}:\n{}", + build.dump() + ); + let built = cell.tree(); + assert_eq!(changed(&vendored, &built), [BAZEL_LOCK], "{test}"); + cell.builds_patched(&built, &patched); + let patched_route = patch.file(&patch.package); + let asked = (standin.asked(&service), standin.asked(&patched_route)); + assert_eq!(asked, (1, 0), "{test}: Bazel asked a host for the package"); + + // A second machine, with no host to ask: the stand-in is stopped, the + // output base is new, and the repository cache, which held the package + // since the build above, holds it no more. + let sum = sha256_hex(&patch.package.nupkg); + assert!(cell.uncache(&sum), "{test}: the cache did not hold {sum}"); + drop(standin); + let offline = cell.twin(); + offline.builds(&patched); + assert_eq!(changed(&built, &offline.tree()), NOTHING, "{test}"); + + // (d) A third machine, where one byte of the committed package is + // another: `vendor --check` fails, and the build fails over the sha256 + // that Bazel's lock pins. The changed bytes are never built. + assert!( + offline.uncache(&sum), + "{test}: the cache did not hold {sum}" + ); + let tampered = offline.twin(); + let mut bytes = patch.package.nupkg.clone(); + let middle = bytes.len() / 2; + bytes[middle] ^= 0x01; + tampered.write(©, &bytes); + let check = tampered.socket_patch("http://127.0.0.1:9", &["vendor", "--check"], &[]); + assert_eq!(check.code, 1, "{test}: {}", check.dump); + let failed = [event("failed", "vendor_check_failed")]; + assert_eq!(event_triples(&check.envelope), failed, "{}", check.dump); + let build = tampered.bazel("build", &[CONSUMER]); + let refusal = format!("Checksum was {} but wanted {sum}", sha256_hex(&bytes)); + assert!( + !build.ok() && squeezed(&build.stderr()).contains(&squeezed(&refusal)), + "{test}: the changed package did not fail the build with {refusal:?}:\n{}", + build.dump() + ); + drop(tampered); + drop(offline); + + // (e) The undo, with a registry to ask again: every file of the + // checkout is the one of before but Bazel's own lock, which the next + // build puts back with the unpatched marker. + let standin = registry(&[&neighbour, &upstream]); + cell.route_downloads(&downloads(&standin.origin())); + let undo = socket_patch(&cell, &standin, home.path(), &["vendor", "--revert"]); + let said = &undo.dump; + assert_eq!(undo.code, 0, "{test}: {said}"); + assert_eq!(undo.envelope["summary"]["removed"], 1, "{test}: {said}"); + assert_eq!( + changed(&before, &cell.tree()), + [BAZEL_LOCK], + "{test}: {said}" + ); + cell.builds(&unpatched); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}"); + + println!( + "{test}: on Bazel {release}, `scan --mode vendored` declined the package while no file \ + named the release ({DECLINED}) and the build stayed {unpatched:?}; with {BAZEL_VERSION} \ + it kept the patched package at {copy} and its block in {MODULE}; `vendor --check` passed \ + and `vex` attested the package; the build printed {patched:?} with no request for the \ + package, and again with the stand-in stopped, a new output base and the package in no \ + repository cache; one changed byte failed `vendor --check` and the build ({refusal}); \ + `vendor --revert` restored all {} files but {BAZEL_LOCK}, and the next build printed \ + {unpatched:?} and wrote the lock of before; {:?}", + before.len(), + started.elapsed() + ); +} + +/// Bazel's lock of a checkout that a build has selected rules_csharp 0.5.0 +/// for: the one line of it that vendored mode reads. +const SELECTED: &str = "{\"lockFileVersion\": 28, \"registryFileHashes\": {\ + \"https://bcr.bazel.build/modules/rules_csharp/0.5.0/source.json\": \"sum\"}}\n"; + +/// Without a Bazel: vendored mode through the binary, in checkouts of the +/// fixture's project on the machine that restored it. +/// +/// Where no Bazel workspace is, and where the tag of one reads the lock of +/// another project, the command gives a person and a script what it gives +/// without Bazel, and writes the same files: the package in the folder of +/// the patch, that folder in `nuget.config`, and no line of `MODULE.bazel`. +/// +/// In the fixture's workspace it keeps the package where a feed of the hub +/// has it and its block in `MODULE.bazel`; a second run changes nothing; +/// `vendor --check` passes and `list` says what it says without Bazel; and +/// `vendor --revert`, `rollback` and `remove` each put every file back +/// byte for byte, the block with its one folder. Beside a block that was +/// changed by hand no undo changes a file, and each says where the block +/// is; with the block deleted by hand, the undo puts the rest back. +/// +/// Where the block cannot be shown to work, `scan` and `get` decline the +/// package with exit 1 and write nothing, a dry run lists it and exits 0, +/// and a person reads the reason. A pin of hosted mode stays: the scan +/// that would take it over and the `vendor` that would eject it are +/// declined too, and where the block does work `vendor` ejects the pin +/// into it. With `--allow-vendored-in-bazel`, or its variable, the package +/// is vendored as without Bazel. +#[test] +fn vendored_mode_keeps_the_block_or_declines() { + let test = "nuget::vendored_mode_keeps_the_block_or_declines"; + let (upstream, neighbour) = ( + Package::new(NAME, "R1", "PRISTINE"), + Package::new(NEIGHBOUR, "R1", "NEIGHBOUR"), + ); + let (patch, purl) = (Patched::new("R1"), upstream.purl()); + let standin = registry(&[&neighbour, &upstream]); + grant(&standin, &upstream, &patch, &patch.package.nupkg); + let service = service_route(&standin, &patch); + let home = tempfile::tempdir().expect("create the .NET home"); + for package in [&neighbour, &upstream] { + package.restore_into(home.path()); + } + let era = fixture_path(FIXTURE.dir).join(FIXTURE.eras[0].1); + let module = std::fs::read_to_string(era.join(MODULE)).expect(MODULE); + // A checkout of the fixture's project and config: with `module` as its + // MODULE.bazel, beside Bazel's lock, and the release it names. + let checkout = |module: Option<&str>, release: Option<&str>| { + let cell = cell_without_bazel("9.3.2"); + check_out(&cell, "R1", &[&neighbour, &upstream]); + cell.write(CONFIG, fixture_file_as_is(CONFIG)); + cell.write(".git/HEAD", "ref: refs/heads/main\n"); + if let Some(module) = module { + cell.write(MODULE, module); + cell.write(BAZEL_LOCK, SELECTED); + } + if let Some(release) = release { + cell.write(BAZEL_VERSION, format!("{release}\n")); + } + cell + }; + let scan = |cell: &Cell, more: &[&str]| vendored_scan(cell, &standin, home.path(), more); + let (dir, flat) = ( + vendor_dir(&patch), + format!("{}.{VERSION}.nupkg", upstream.lower()), + ); + let flat = format!("{dir}/{flat}"); + // What a vendored run wrote of the three files it shares with a hub, + // and the names of everything it wrote. + let wrote = |cell: &Cell, before: &Tree| { + let after = cell.tree(); + let files = [CONFIG, LOCK].map(|file| after[file].clone()); + (changed(before, &after), files) + }; + + // Without Bazel, and beside a tag that reads the lock of another + // project: the package in the folder of the patch. + let plain = checkout(None, None); + let before = plain.tree(); + let without = scan(&plain, &[]); + assert_eq!(without.code, 0, "{test}: {}", without.dump); + let as_before = wrote(&plain, &before); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + flat.clone(), + ".socket/vendor/state.json".to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(as_before.0, written, "{test}: {}", without.dump); + let elsewhere = module.replace("//:packages", "//api:packages"); + for (module, release) in [(&elsewhere, None), (&elsewhere, Some("9.3.2"))] { + let cell = checkout(Some(module), release); + let before = cell.tree(); + let ran = scan(&cell, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!(ran.envelope, without.envelope, "{test}: {}", ran.dump); + assert_eq!(wrote(&cell, &before), as_before, "{test}: {}", ran.dump); + } + + // The fixture's workspace: the block, and every way to take it out. + let hub = checkout(Some(&module), Some("9.3.2")); + let before = hub.tree(); + let undo: [&[&str]; 3] = [ + &["vendor", "--revert"], + &["rollback", "--yes"], + &["remove", &purl, "--yes"], + ]; + for undo in undo { + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let vendored = hub.tree(); + let mut written = vec![ + format!("{dir}/.gitignore"), + format!("{dir}/socket-patch.vendor.json"), + hub_copy(&patch), + ".socket/vendor/state.json".to_string(), + MODULE.to_string(), + CONFIG.to_string(), + LOCK.to_string(), + ]; + written.sort(); + assert_eq!(changed(&before, &vendored), written, "{test}: {}", ran.dump); + let appended = format!("{module}\n{}", block(&dir)); + assert_eq!(text(&vendored, MODULE), appended, "{test}"); + // Once more, and the check: nothing is written. + let again = scan(&hub, &[]); + assert_eq!(again.code, 0, "{test}: {}", again.dump); + let check = socket_patch(&hub, &standin, home.path(), &["vendor", "--check"]); + assert_eq!(check.code, 0, "{test}: {}", check.dump); + // `list` says of it what it says of the package without Bazel. + let list = |cell: &Cell| socket_patch(cell, &standin, home.path(), &["list"]); + let (listed, as_without) = (list(&hub), list(&plain)); + assert_eq!(listed.envelope["events"][0]["details"]["mode"], "vendored"); + assert_eq!(listed.envelope, as_without.envelope, "{}", listed.dump); + assert_eq!(changed(&vendored, &hub.tree()), NOTHING, "{test}: {undo:?}"); + let ran = socket_patch(&hub, &standin, home.path(), undo); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!( + changed(&before, &hub.tree()), + NOTHING, + "{test}: {}", + ran.dump + ); + } + + // A block that was changed by hand keeps the folder of the patch, and + // with the lock restored beside it the Bazel build would fail on the + // committed package: no undo changes a file, and each names the line + // of the block. With the block deleted by hand, the undo puts every + // other file back. + let squeezed = |text: &str| text.split_whitespace().collect::(); + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let wired = text(&hub.tree(), MODULE); + hub.write( + MODULE, + wired.replace(" feeds = [", " # mine\n feeds = ["), + ); + let edited = hub.tree(); + assert_ne!(text(&edited, MODULE), wired, "{test}"); + let by_hand = format!( + "{MODULE}:{}: the block that socket-patch keeps there was changed by hand", + module.lines().count() + 2 + ); + for undo in undo { + let ran = socket_patch(&hub, &standin, home.path(), undo); + assert_eq!(ran.code, 1, "{test}: {}", ran.dump); + assert!( + squeezed(&ran.dump).contains(&squeezed(&by_hand)), + "{test}: no {by_hand:?}: {}", + ran.dump + ); + assert_eq!(changed(&edited, &hub.tree()), NOTHING, "{test}: {undo:?}"); + } + hub.write(MODULE, &module); + let ran = socket_patch(&hub, &standin, home.path(), undo[0]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!( + changed(&before, &hub.tree()), + NOTHING, + "{test}: {}", + ran.dump + ); + + // Where the block cannot be shown to work: declined by every command + // that would vendor, with nothing asked of the patch service. The + // last row is a tag with `feeds` beside a config without a source: the + // run would name its folder there, and the next one would take the + // sources of that file for the hub's in place of those feeds. + let asked = standin.asked(&service); + let dirs = module.replace(NAMES_CONFIG, " local_package_dirs = [\"/opt/nuget\"],\n"); + let fed = + format!(" feeds = [\"https://nuget.private.example/v3/index.json\"],\n{NAMES_CONFIG}"); + let fed = module.replace(NAMES_CONFIG, &fed); + let sourceless = "\n \n \n\n"; + let rows: [(&str, Option<&str>, Option<&str>, &str); 4] = [ + ( + &module, + None, + None, + "no file of the checkout names the Bazel release", + ), + ( + &module, + Some("8.8.1"), + None, + "the checkout names Bazel 8.8.1", + ), + ( + &dirs, + Some("9.3.2"), + None, + "MODULE.bazel:9: this `nuget.from_lock` has `local_package_dirs`", + ), + ( + &fed, + Some("9.3.2"), + Some(sourceless), + "MODULE.bazel:9: this `nuget.from_lock` has `feeds`, and its `nuget_config` \ + `//:nuget.config` names no package source", + ), + ]; + for (module, release, config, why) in rows { + let cell = checkout(Some(module), release); + if let Some(config) = config { + cell.write(CONFIG, config); + } + let before = cell.tree(); + declined(test, &scan(&cell, &[]), &purl, why); + let get = ["get", &purl, "--mode", "vendored", "--yes"]; + let get = socket_patch(&cell, &standin, home.path(), &get); + assert_eq!(get.code, 1, "{test}: {}", get.dump); + assert!( + codes_of(&get.envelope).contains(&DECLINED.to_string()), + "{}", + get.dump + ); + // A dry run lists it and passes. + let dry = scan(&cell, &["--dry-run"]); + assert_eq!(dry.code, 0, "{test}: {}", dry.dump); + let listed = [(purl.clone(), "skipped".to_string(), DECLINED.to_string())]; + assert_eq!(event_triples(&dry.envelope), listed, "{test}: {}", dry.dump); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}: {why}"); + // A person reads the reason after the package, once. The output is + // compared without white space: nothing says where a long line is + // broken. + let run = |api: &str, env: &[(&str, &str)]| { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + cell.socket_patch_person(api, &args, env) + }; + let person = on_machine(&standin, home.path(), run); + let told = squeezed(&person.concat()); + let line = squeezed(&format!("{purl} ({DECLINED}): ")); + assert!( + told.matches(&line).count() == 1 && told.contains(&squeezed(why)), + "{test}: {person:?}" + ); + assert_eq!(changed(&before, &cell.tree()), NOTHING, "{test}: {why}"); + assert_eq!(standin.asked(&service), asked, "{test}: {why}"); + } + // A package that hosted mode pinned: the scan that would take the pin + // over and the `vendor` that would eject it are declined, and the pin + // stays. Once the checkout names its release, `vendor` ejects the pin + // into the block. + let cell = checkout(Some(&module), None); + let hosted = socket_patch(&cell, &standin, home.path(), &SCAN); + assert_eq!(hosted.code, 0, "{test}: {}", hosted.dump); + let pinned = cell.tree(); + declined(test, &scan(&cell, &[]), &purl, rows[0].3); + let eject = socket_patch(&cell, &standin, home.path(), &["vendor", "--yes"]); + assert_eq!(eject.code, 1, "{test}: {}", eject.dump); + let refused = &eject.envelope["error"]["code"]; + assert_eq!(*refused, "eject_refused", "{test}: {}", eject.dump); + let kept = eject.envelope["events"][0]["error"].as_str(); + let kept = kept.is_some_and(|why| why.starts_with("kept hosted: ") && why.contains(rows[0].3)); + assert!(kept, "{test}: {}", eject.dump); + assert_eq!(changed(&pinned, &cell.tree()), NOTHING, "{test}"); + assert_eq!(standin.asked(&service), asked, "{test}"); + cell.write(BAZEL_VERSION, "9.3.2\n"); + let origin = standin.origin(); + let eject = ["vendor", "--yes", "--patch-server-url", &origin]; + let eject = socket_patch(&cell, &standin, home.path(), &eject); + assert_eq!(eject.code, 0, "{test}: {}", eject.dump); + let ejected = cell.tree(); + assert_eq!(ejected[&hub_copy(&patch)], patch.package.nupkg, "{test}"); + let appended = format!("{module}\n{}", block(&dir)); + assert_eq!(text(&ejected, MODULE), appended, "{test}: {}", eject.dump); + assert!(!text(&ejected, CONFIG).contains(PATCH_HOST), "{test}"); + + // The user's word, as a flag and as its variable: as without Bazel. + for flag in [true, false] { + let cell = checkout(Some(&module), None); + let before = cell.tree(); + let ran = match flag { + true => scan(&cell, &["--allow-vendored-in-bazel"]), + false => on_machine(&standin, home.path(), |api, env| { + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + let env = [env, &[("SOCKET_ALLOW_VENDORED_IN_BAZEL", "1")]].concat(); + cell.socket_patch(api, &args, &env) + }), + }; + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + assert_eq!(ran.envelope, without.envelope, "{test}: {}", ran.dump); + assert_eq!(wrote(&cell, &before), as_before, "{test}: {}", ran.dump); + } +} + /// Without a Bazel: `scan --mode hosted --yes` through the binary, in /// checkouts of the fixture's project that hold no `nuget.config`. What it /// gives a person, then a script, and the files it leaves are the same in diff --git a/crates/socket-patch-core/src/bazel/block.rs b/crates/socket-patch-core/src/bazel/block.rs new file mode 100644 index 000000000..f5ae5b9b6 --- /dev/null +++ b/crates/socket-patch-core/src/bazel/block.rs @@ -0,0 +1,113 @@ +//! The text of a block that socket-patch keeps in the root `MODULE.bazel`. +//! +//! A block is the lines from a first line of its kind (`# >>> socket-patch: +//! Maven patches for Bazel (...) >>>`) to [`END`]. It is appended to the +//! file and taken out byte for byte, and it is known by its text alone: +//! [`super::maven`] and [`super::nuget`] each render what they keep there, +//! and a block that is not, byte for byte, what its owner renders for what +//! it names was changed by hand. This module holds what the two share: +//! where a block is, how one is put into a file and taken out of it, and +//! the file as it reads without one. + +use std::ops::Range; + +use crate::utils::line_endings::terminator; + +/// The last line of a block. +pub(super) const END: &str = "# <<< socket-patch <<<"; + +/// What a `MODULE.bazel` holds of the block whose first line is `begin`. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Found { + None, + /// From the first byte of its first line to the last of [`END`], and + /// the number of its first line. + At(Range, usize), + /// A second first line, one that is not as it is written, or no + /// [`END`]: the line of the first one. + Edited(usize), +} + +/// Whether `line` is the first line of the block of `begin`, as it is +/// written or touched (a blank after it, another end): `begin` up to its +/// bracket. A file without such a line holds no such block. +pub(super) fn begins(line: &str, begin: &str) -> bool { + let mark = begin.split(" (").next().unwrap_or(begin); + line.trim_start().starts_with(mark) +} + +pub(super) fn find(text: &str, begin: &str) -> Found { + let (mut at, mut first, mut end) = (0, None, None); + for (line, whole) in text.split_inclusive('\n').enumerate() { + let bare = whole.strip_suffix('\n').unwrap_or(whole); + let bare = bare.strip_suffix('\r').unwrap_or(bare); + match (first, end) { + (None, _) if bare == begin => first = Some((at, line + 1)), + // A second first line, or one that is not as it is written. + _ if begins(bare, begin) => { + return Found::Edited(first.map_or(line + 1, |(_, first)| first)); + } + (Some(_), None) if bare == END => end = Some(at + bare.len()), + _ => {} + } + at += whole.len(); + } + match (first, end) { + (None, _) => Found::None, + (Some((start, line)), Some(end)) => Found::At(start..end, line), + (Some((_, line)), None) => Found::Edited(line), + } +} + +/// Whether the block at `at` is `rendered`, whose lines a line feed ends, +/// in the line break of its own lines, whatever the rest of a file with +/// both has. +pub(super) fn is(text: &str, at: &Range, rendered: &str) -> bool { + let block = &text[at.clone()]; + rendered.replace('\n', terminator(block)) == block +} + +/// `module` with the block `rendered` in the place of the one at `at`, in +/// the line break of that one's lines, or as a new one at the end of the +/// file, after one blank line, in the line break of the file +/// ([`terminator`]: the more frequent one of a file with both). A file +/// whose last line has no line break gets a block without one, so that +/// [`cut`] can tell. +pub(super) fn put(module: &str, at: Option>, rendered: &str) -> String { + let ended = module.is_empty() || module.ends_with('\n'); + let eol = terminator(at.as_ref().map_or(module, |at| &module[at.clone()])); + let block = rendered.replace('\n', eol); + match at { + Some(at) => format!("{}{block}{}", &module[..at.start], &module[at.end..]), + None if ended => format!("{module}{eol}{block}{eol}"), + None => format!("{module}{eol}{eol}{block}"), + } +} + +/// `module` without the block at `at` and what [`put`] put before it: the +/// file is then byte for byte what it was before the block. +pub(super) fn cut(module: &str, at: Range) -> String { + let (head, tail) = (&module[..at.start], &module[at.end..]); + // The line break before the block and, when it ends a blank line, that + // line; then the block's own line break or, for a block that ends the + // file without one, the one that was added to the last line. A line + // break is one of either kind: a file can have both. + let cut = + |text: &str| text.len() - text.ends_with('\n') as usize - text.ends_with("\r\n") as usize; + let blank = |head: &str| cut(head) == 0 || head[..cut(head)].ends_with('\n'); + let after = tail.strip_prefix('\r').unwrap_or(tail).strip_prefix('\n'); + let (head, tail) = match after { + Some(tail) if blank(head) => (&head[..cut(head)], tail), + None if tail.is_empty() && blank(head) => (&head[..cut(&head[..cut(head)])], tail), + Some(tail) => (head, tail), + None => (head, tail), + }; + format!("{head}{tail}") +} + +/// `module` as the user wrote it: without the block at `at`, and with +/// every line where it was. +pub(super) fn hidden(module: &str, at: Range) -> String { + let lines = "\n".repeat(module[at.clone()].matches('\n').count()); + format!("{}{lines}{}", &module[..at.start], &module[at.end..]) +} diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 73eb1d69d..f11a18ae3 100644 --- a/crates/socket-patch-core/src/bazel/maven.rs +++ b/crates/socket-patch-core/src/bazel/maven.rs @@ -54,6 +54,7 @@ use std::ops::Range; use std::path::Path; use std::rc::Rc; +use super::block::{self, Found, END}; use super::rc::{declared_release, mentions, ModuleLock}; use super::starlark::{Bound, Call, How, Value}; use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Workspace}; @@ -63,7 +64,6 @@ use crate::patch::redirect::{ }; use crate::utils::digest::is_hex64_lower; use crate::utils::fs::run_blocking; -use crate::utils::line_endings::terminator; use crate::utils::purl::{build_maven_purl, parse_maven_purl, purl_qualifier}; use crate::vendor::jvm::layout::artifact_path; @@ -110,10 +110,9 @@ pub const DOWNLOAD: &str = "maven_bazel_download"; pub const FILE: &str = "MODULE.bazel"; pub const SITE_KEY: &str = ""; -/// The first and the last line of the block. +/// The first line of the block. pub const BEGIN: &str = "# >>> socket-patch: Maven patches for Bazel (managed block: socket-patch \ writes and removes it) >>>"; -const END: &str = "# <<< socket-patch <<<"; /// The releases of rules_jvm_external whose way to name the repository of /// a jar was read: `escape(coordinates)` in @@ -165,7 +164,7 @@ pub struct Hub { /// called on, when that usage is shared with every other one of the /// extension (`isolate` is not given, or is `False`) and its label holds /// nothing a string of the block would have to escape. -fn proxy(ws: &Workspace, tag: &Tag) -> Option { +pub(super) fn proxy(ws: &Workspace, tag: &Tag) -> Option { let (_, file) = ws.files.iter().find(|(path, _)| path == tag.file)?; let Bound::Call(made) = file.binds.get(tag.call.bind?)?.to else { return None; @@ -395,7 +394,7 @@ pub enum Built<'a> { /// Discovery.java lines 158 and 159 at 7.7.2, 178 and 179 at 8.8.2 and /// 9.3.2). #[derive(Debug, PartialEq, Eq)] -enum Asked { +pub(super) enum Asked { /// No version is given. Nothing, /// A `bazel_dep` asks for this release: Bazel selects it or a newer @@ -430,11 +429,33 @@ fn ordered(version: &str) -> impl Ord + '_ { (identifiers(release), pre.is_empty(), identifiers(pre)) } -/// What the root module of `ws` says of the ruleset's release: by its -/// calls that name the ruleset, a `bazel_dep` and the overrides, which are -/// the functions whose name ends in `_override`. -fn asked(ws: &Workspace) -> Asked { - let named = Some(&Value::Str(EXTENSION.module.to_string())); +impl Asked { + /// The release that is asked for or pinned, for a message. + pub(super) fn wanted(&self) -> &str { + match self { + Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted, + Asked::Nothing | Asked::Unknown(_) => "", + } + } + + /// Whether a `MODULE.bazel.lock` that holds the release `selected` is + /// one Bazel has not written since the root asked for another: older + /// than what is asked for, or any other than the one a + /// `single_version_override` pins. + pub(super) fn stale(&self, selected: &str) -> bool { + match self { + Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), + Asked::AtLeast(least) => ordered(least) > ordered(selected), + Asked::Nothing | Asked::Unknown(_) => false, + } + } +} + +/// What the root module of `ws` says of the release of the ruleset +/// `module`: by its calls that name the ruleset, a `bazel_dep` and the +/// overrides, which are the functions whose name ends in `_override`. +pub(super) fn asked(ws: &Workspace, module: &str) -> Asked { + let named = Some(&Value::Str(module.to_string())); let names = |call: &&Call| { call.bind.is_none() && [call.arg("name"), call.arg("module_name")].contains(&named) }; @@ -517,9 +538,7 @@ impl Hubs { Block::None => {} Block::Edited(line) => edited = Some(line), Block::Ours(at, _, patches) => { - let lines = "\n".repeat(module[at.clone()].matches('\n').count()); - let (head, tail) = (&module[..at.start], &module[at.end..]); - hidden = Some(format!("{head}{lines}{tail}")); + hidden = Some(block::hidden(&module, at)); block = patches; } } @@ -539,7 +558,7 @@ impl Hubs { why: "the block that socket-patch keeps there was changed by hand".to_string(), }), ); - let asked = asked(&ws); + let asked = asked(&ws, EXTENSION.module); let overrides = ws.tags(&EXTENSION, "override").calls.into_iter(); let overrides = overrides.map(|Tag { file, call, .. }| { let (replaced, why) = match call.arg("coordinates") { @@ -858,48 +877,26 @@ enum Block { /// touched (a blank after it, another end): [`BEGIN`] up to its bracket. /// A file without such a line holds no block. pub fn begins(line: &str) -> bool { - let mark = BEGIN.split(" (").next().unwrap_or(BEGIN); - line.trim_start().starts_with(mark) + block::begins(line, BEGIN) } fn find(text: &str) -> Block { - let (mut at, mut begin, mut end) = (0, None, None); - for (line, whole) in text.split_inclusive('\n').enumerate() { - let bare = whole.strip_suffix('\n').unwrap_or(whole); - let bare = bare.strip_suffix('\r').unwrap_or(bare); - match (bare, begin, end) { - (BEGIN, None, _) => begin = Some((at, line + 1)), - // A second first line, or one that is not as it is written. - _ if begins(bare) => { - return Block::Edited(begin.map_or(line + 1, |(_, first)| first)); - } - (END, Some(_), None) => end = Some(at + bare.len()), - _ => {} - } - at += whole.len(); - } - let Some((start, line)) = begin else { - return Block::None; + let (at, line) = match block::find(text, BEGIN) { + Found::None => return Block::None, + Found::Edited(line) => return Block::Edited(line), + Found::At(at, line) => (at, line), }; - // In the line break of its own lines, whatever the rest of a file - // with both has. - let ours = end.and_then(|end| { - let (label, entries) = parse(&text[start..end])?; - let written = render(&label, &entries).replace('\n', terminator(&text[start..end])); - (written == text[start..end]).then_some((start..end, label, entries)) - }); - ours.map_or(Block::Edited(line), |(at, label, patches)| { + let ours = parse(&text[at.clone()]); + let ours = ours.filter(|(label, entries)| block::is(text, &at, &render(label, entries))); + ours.map_or(Block::Edited(line), |(label, patches)| { Block::Ours(at, label, patches) }) } /// `module` with `patch` in its block, in the place of any patch for the -/// same repository: in the block that is there, in the line break of its -/// lines, or in a new one at the end of the file, after one blank line, -/// in the line break of the file ([`terminator`]: the more frequent one -/// of a file with both). A file whose last line has no line break gets a -/// block without one, so that [`without`] can tell. `None` when the block -/// that is there was changed by hand. +/// same repository: in the block that is there or in a new one at the end +/// of the file ([`block::put`]). `None` when the block that is there was +/// changed by hand. pub fn with_patch(module: &str, label: &str, patch: Patch) -> Option { let (at, mut patches) = match find(module) { Block::Edited(_) => return None, @@ -908,14 +905,7 @@ pub fn with_patch(module: &str, label: &str, patch: Patch) -> Option { }; patches.retain(|other| other.repository() != patch.repository()); patches.push(patch); - let ended = module.is_empty() || module.ends_with('\n'); - let eol = terminator(at.as_ref().map_or(module, |at| &module[at.clone()])); - let block = render(label, &patches).replace('\n', eol); - Some(match at { - Some(at) => format!("{}{block}{}", &module[..at.start], &module[at.end..]), - None if ended => format!("{module}{eol}{block}{eol}"), - None => format!("{module}{eol}{eol}{block}"), - }) + Some(block::put(module, at, &render(label, &patches))) } /// The patches of the block of `module`: none when it has no block, or one @@ -1018,26 +1008,10 @@ pub fn without(module: &str, gone: &mut dyn FnMut(&Patch) -> bool) -> Option (&head[..cut(head)], tail), - None if tail.is_empty() && blank(head) => (&head[..cut(&head[..cut(head)])], tail), - Some(tail) => (head, tail), - None => (head, tail), - }; - Some(format!("{head}{tail}")) + Some(match entries.is_empty() { + true => block::cut(module, at), + false => block::put(module, Some(at), &render(&label, &entries)), + }) } /// What a hosted run does in the root `MODULE.bazel` for one patch. @@ -1194,19 +1168,7 @@ fn settings( } _ => {} } - // A lock that holds another release than the root now takes is one - // that Bazel has not written since: older than what is asked for, or - // any other than the one a `single_version_override` pins. - let module = EXTENSION.module; - let stale = |selected: &str| match asked { - Asked::Exactly(pinned) => ordered(pinned) != ordered(selected), - Asked::AtLeast(least) => ordered(least) > ordered(selected), - Asked::Nothing | Asked::Unknown(_) => false, - }; - let wanted = match asked { - Asked::Exactly(wanted) | Asked::AtLeast(wanted) => wanted.as_str(), - Asked::Nothing | Asked::Unknown(_) => "", - }; + let (module, wanted) = (EXTENSION.module, asked.wanted()); let why = match (asked, &lock.selected(module)[..]) { (Asked::Unknown(at), _) => format!( "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel \ @@ -1216,7 +1178,7 @@ fn settings( "Bazel selected {module} {selected}, and how the ruleset names the repository of a \ jar is known for its releases 6.4 to 7.2: update socket-patch" ), - (_, [selected]) if stale(selected) => format!( + (_, [selected]) if asked.stale(selected) => format!( "{FILE} asks for {module} {wanted} and MODULE.bazel.lock holds {selected}: build once \ so that Bazel updates its lock" ), @@ -1714,6 +1676,7 @@ fn notices_blocking( #[cfg(test)] pub(crate) mod tests { use super::*; + use crate::utils::line_endings::terminator; /// For the tests of what reads the block elsewhere: the `MODULE.bazel` /// of a checkout whose pinned hub fetches netty's jar, the lock of diff --git a/crates/socket-patch-core/src/bazel/mod.rs b/crates/socket-patch-core/src/bazel/mod.rs index fe8331b95..96e2eb9a2 100644 --- a/crates/socket-patch-core/src/bazel/mod.rs +++ b/crates/socket-patch-core/src/bazel/mod.rs @@ -8,6 +8,7 @@ pub const WORKSPACE_FILES: [&str; 4] = ["MODULE.bazel", "REPO.bazel", "WORKSPACE", "WORKSPACE.bazel"]; +mod block; pub mod built; pub mod cargo; pub(crate) mod cargo_bazel; @@ -46,13 +47,30 @@ pub fn bazel_root(project: &Path) -> Option { 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 { +/// The root of a Bazel workspace above the one `project` is in, within the +/// bounds of [`bazel_root`]: the next directory up that holds one of +/// [`WORKSPACE_FILES`]. Bazel can build the inner workspace from there, as +/// a module of the outer one. +pub fn root_above(project: &Path) -> Option { + let dirs = search_dirs(project); + let above = roots_in(&dirs, repo_at_end_of(dirs.clone())).nth(1); + above.map(|at| dirs[at].clone()) +} + +/// The directories of the walk `dirs`, which ended at the checkout `repo`, +/// that hold one of [`WORKSPACE_FILES`], from the project up: each as its +/// place in `dirs`. +fn roots_in(dirs: &[PathBuf], repo: Option) -> impl Iterator + '_ { 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()); + (0..within).filter(|at| { + let marks = |name| std::fs::metadata(dirs[*at].join(name)).is_ok_and(|meta| meta.is_file()); WORKSPACE_FILES.into_iter().any(marks) - })?; + }) +} + +/// [`bazel_root`] for the walk `dirs`, which ended at the checkout `repo`. +fn root_in(dirs: &[PathBuf], repo: Option) -> Option { + let at = roots_in(dirs, repo).next()?; Some(BazelRoot { dir: dirs[at].clone(), project: dirs[0].strip_prefix(&dirs[at]).ok()?.to_path_buf(), @@ -98,11 +116,14 @@ mod tests { (below.dir, below.project), (repo.clone(), PathBuf::from("svc/app")) ); - // The nearest wins, under each name. + // The nearest wins, under each name, and the next one up is the + // workspace above it. + assert_eq!(root_above(&app), None); 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}"); + assert_eq!(root_above(&app), Some(repo.clone()), "{name}"); fs::remove_file(&file).unwrap(); } fs::remove_file(repo.join("MODULE.bazel")).unwrap(); @@ -114,6 +135,8 @@ mod tests { 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); + fs::write(base.join("repo/MODULE.bazel"), "").unwrap(); + assert_eq!(root_above(&base.join("repo/app")), None); } /// `/workspace/proj`: where the disk folds case, the directory diff --git a/crates/socket-patch-core/src/bazel/nuget.rs b/crates/socket-patch-core/src/bazel/nuget.rs index da4b8811e..6d509f978 100644 --- a/crates/socket-patch-core/src/bazel/nuget.rs +++ b/crates/socket-patch-core/src/bazel/nuget.rs @@ -1,5 +1,6 @@ //! Whether the Bazel build of a workspace takes what hosted mode writes -//! for a NuGet package. +//! for a NuGet package, and what makes it take the copy that vendored mode +//! commits. //! //! rules_csharp hands NuGet packages to Bazel through one tag of a module //! extension. `nuget.from_lock(packages_lock_json = ...)` downloads every @@ -25,17 +26,36 @@ //! [`Hub::against`] tells hosted mode when to write nothing for a package, //! and what to say instead. //! +//! Vendored mode commits the patched package and names its folder as a +//! package source in `nuget.config`, which NuGet takes. The hub reads that +//! line as the URL of a feed, and the next `bazel build` failed: Bazel +//! 9.3.2 crashed in the module extension, 8.8.2 and 7.7.2 refused the URL +//! (`Bad URL`). What the hub does take is a feed `file:`, which +//! Bazel reads from the root of the workspace, with the package at +//! `///..nupkg`. So vendored mode keeps +//! one block at the end of the root `MODULE.bazel` ([`BEGIN`]): a +//! `nuget.from_lock` of its own, after every tag of the user's, whose +//! `feeds` are the folders of the vendored packages and then the sources +//! the hub has without it. [`vendored`] says whether that block can be +//! shown to work in a checkout, [`with_folder`] writes a folder into it and +//! [`without_folder`] takes one out, the block with the last. +//! //! The answer is read from the checkout through [`super::workspace`]: //! `MODULE.bazel` and the files it includes, and the locks the tags name. //! Nothing is evaluated and no Bazel is run. The ruleset has no //! `WORKSPACE` form, so that file is not looked at. +use std::ops::Range; use std::path::Path; use serde::{Deserialize, Serialize}; -use super::starlark::Value; -use super::workspace::{disk, disk_up_to, Entry, Extension, Repo, Tag, Workspace}; +use super::block::{self, Found, END}; +use super::maven::{asked, proxy, Asked}; +use super::rc::{declared_release, mentions, ModuleLock, Release}; +use super::starlark::{How, Value}; +use super::workspace::{disk, disk_up_to, Doubt, Entry, Extension, Repo, Tag, Tags, Workspace}; +use super::BazelRoot; use crate::formats::nuget::lock::{locked_at, nuget_lock_entries, parse_lock}; use crate::formats::nuget::parse_config; use crate::patch::redirect::NUGET_CONFIG_FILE_NAMES as NAMES; @@ -228,11 +248,7 @@ pub fn withheld(project: &Path, config: &str, locks: &[String]) -> Option = listed .filter_map(|entry| entry.file_name().into_string().ok()) @@ -265,6 +281,35 @@ pub fn withheld(project: &Path, config: &str, locks: &[String]) -> Option String { + let parts = root.project.components(); + parts + .map(|part| format!("{}/", part.as_os_str().to_string_lossy())) + .collect() +} + +/// The lock that `tag` reads, for the project in `dir` whose locks are +/// `locks`. `None`: it names none. +fn reads(ws: &Workspace, tag: &Tag, dir: &str, locks: &[String]) -> Option { + let at = format!("{}:{}", tag.file, tag.call.line); + match tag.call.arg("packages_lock_json") { + Some(Value::Str(label)) => { + let label = ws.label(label).filter(|label| label.repo == Repo::Main); + let path = label?.path(); + let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); + Some(match locks.iter().find(ours) { + Some(lock) => Read::Ours(lock.clone()), + None => Read::Other(at, path, None), + }) + } + Some(_) => Some(Read::Any(at)), + None => tag.call.unpacks().then_some(Read::Any(at)), + } +} + /// [`withheld`] for the workspace `ws` and the project in its directory /// `dir` (empty, or with a `/` at its end), before the locks of the other /// tags are read. `exact`: a label names `config` only in its own case. @@ -299,18 +344,7 @@ fn judge( _ => None, }; let at = |tag: &Tag| format!("{}:{}", tag.file, tag.call.line); - let read = |tag: &Tag| match tag.call.arg("packages_lock_json") { - Some(Value::Str(_)) => { - let path = file(tag, "packages_lock_json")?.path(); - let ours = |lock: &&String| path.eq_ignore_ascii_case(&format!("{dir}{lock}")); - Some(match locks.iter().find(ours) { - Some(lock) => Read::Ours(lock.clone()), - None => Read::Other(at(tag), path, None), - }) - } - Some(_) => Some(Read::Any(at(tag))), - None => tag.call.unpacks().then(|| Read::Any(at(tag))), - }; + let read = |tag: &Tag| reads(ws, tag, dir, locks); let reads: Vec> = tags.calls.iter().map(read).collect(); let mine = |read: &Option| matches!(read, Some(Read::Ours(_) | Read::Any(_))); let reader = &tags.calls[reads.iter().position(mine)?]; @@ -390,6 +424,17 @@ fn judge( format!("Name those `feeds` in {config} and run this command again"), ) } + // The tag of the block: its feeds are the hub's, as of the last + // vendored run. + _ if tag.call.callee.split('.').next() == Some(PROXY) => ( + format!( + "is the one vendored mode keeps for the vendored NuGet packages of this project, \ + and its `feeds` stand in the place of the package sources of {config}" + ), + "Vendor this package as well (`--mode vendored`), or take the vendored ones out \ + (`socket-patch vendor --revert`), and run this command again" + .to_string(), + ), Some(Value::Str(theirs)) => { // A config of NuGet's in a directory above the project's is // one the same command writes, when it runs there. @@ -435,8 +480,476 @@ fn judge( Some(hub(Some(why), locks)) } +/// The code with which vendored mode declines a NuGet package of a project +/// whose lock the hub reads, where the block cannot be shown to work. +pub const VENDOR_DECLINED: &str = "vendor_nuget_bazel_workspace"; + +/// The file of the block of vendored mode, and the first line of the block. +pub const FILE: &str = super::maven::FILE; +pub const BEGIN: &str = "# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch \ + writes and removes it) >>>"; +/// The name the block gives its `use_extension`, and how a feed of the +/// block starts that is a folder of vendored mode. +const PROXY: &str = "socket_patch_nuget"; +const FOLDER: &str = "file:.socket/vendor/nuget/"; + +/// The release of rules_csharp and the releases of Bazel the block was +/// built on, with the patch host unreachable. It rests on Bazel reading a +/// relative `file:` URL from the root of the workspace, which no document +/// of Bazel's promises: 9.1.0 has other code for such a URL than 9.0.2 and +/// 9.1.1 (`DownloadManager.java`), so no release is taken for its +/// neighbour's sake. +const RULESET: &str = "0.5.0"; +const BAZELS: [Release; 3] = [(7, 7, 2), (8, 8, 2), (9, 3, 2)]; +const BUILT_ON: &str = "the block was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone"; + +/// The arguments of a tag beside which the block was built, or which +/// change nothing for it. +const ARGUMENTS: [&str; 6] = [ + "directory_packages_props", + "feeds", + "name", + "nuget_config", + "packages_lock_json", + "use_public_sources", +]; + +/// What the block holds besides the folders of vendored mode, read from +/// the one tag of the workspace. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Feeds { + /// The label of the tag's `use_extension`, as it is written. + label: String, + /// The name the tag gives the hub, where it gives one: a tag without + /// one would give the hub the name `nuget`. + name: Option, + /// The tag's `packages_lock_json`, as it is written. + lock: String, + /// The package sources the hub has without the block, in its order. + sources: Vec, +} + +/// What vendored mode does for the NuGet packages of a project. +#[derive(Debug, PartialEq, Eq)] +pub enum Vendored { + /// What it does without Bazel: the project is in no Bazel workspace, + /// or no `nuget.from_lock` reads a lock of it. + Plain, + /// Nothing: the hub reads a lock of the project, and this is why the + /// block cannot be shown to work. + Declined(String), + /// It keeps the package where a feed of the hub has one, and its + /// folder in the block. + Block(Feeds), +} + +/// What vendored mode does for the NuGet packages of the project at +/// `project`, whose locks are `locks` (paths from the project, with `/` +/// between their parts). +/// +/// The block is written only where the checkout shows that it works: the +/// project is the root of its Bazel workspace, and no workspace lies above +/// it in the checkout; the workspace has one `nuget.from_lock`, a call of +/// its own with every argument written out and none but [`ARGUMENTS`], on +/// a `use_extension` that the block can share, and whose `feeds` no run +/// of vendored mode replaces (a `nuget_config` without a package source +/// gets one); Bazel selected rules_csharp [`RULESET`], and the checkout +/// names one of [`BAZELS`]; no rc file names +/// `--repository_disable_download`, `--vendor_dir` or a remote downloader, +/// and no directory at the root is a vendor directory of Bazel's (it holds +/// `VENDOR.bazel`); and `MODULE.bazel` is a file whose block, if it has +/// one, is as socket-patch wrote it. +/// +/// Not seen: a tag of another Bazel module, whose sources the hub takes +/// after the block's; a module that depends on this one, where Bazel reads +/// the folder from another root; a vendor directory below the first level; +/// `--nofetch`, in an rc file as on the command line; and whatever else +/// the command line tells Bazel. +pub fn vendored(project: &Path, locks: &[String]) -> Vendored { + let Some(root) = super::bazel_root(project).filter(|_| !locks.is_empty()) else { + return Vendored::Plain; + }; + let on_disk = disk(&root.dir); + let module = match on_disk(FILE) { + Entry::Text(module) => module, + _ => String::new(), + }; + // The block is socket-patch's own: the tags are read without it. + let found = find(&module); + let view = |path: &str| match &found { + Block::Ours(at, ..) if path == FILE => Entry::Text(block::hidden(&module, at.clone())), + _ => on_disk(path), + }; + let files = disk_up_to(&root.dir, MAX_LOCK); + let feeds = match ( + gate(&Workspace::read(&view), &files, &prefix(&root), locks), + &found, + ) { + (Vendored::Plain, _) => return Vendored::Plain, + // Its tag reads as one of the user's: said as what it is. + (_, Block::Edited(line)) => { + let edited = "the block that socket-patch keeps there was changed by hand"; + return Vendored::Declined(format!("{FILE}:{line}: {edited}")); + } + (Vendored::Block(feeds), _) => feeds, + (declined, _) => return declined, + }; + let link = std::fs::symlink_metadata(root.dir.join(FILE)).is_ok_and(|meta| meta.is_symlink()); + let listed = std::fs::read_dir(&root.dir).into_iter().flatten().flatten(); + let vendor = { listed }.find(|entry| entry.path().join("VENDOR.bazel").is_file()); + let why = match (vendor, super::root_above(project)) { + _ if link => { + format!("{FILE} is a symbolic link, which socket-patch does not write through") + } + (Some(vendor), _) => format!( + "{}/VENDOR.bazel: the checkout holds a vendor directory of Bazel's, from which Bazel \ + can build the unpatched package", + vendor.file_name().to_string_lossy() + ), + (_, Some(above)) => format!( + "{} holds a Bazel workspace above this one, and a build from there reads the block's \ + folder from that root", + crate::utils::pnpm_workspace::without_verbatim_prefix(above).display() + ), + _ => return Vendored::Block(feeds), + }; + Vendored::Declined(why) +} + +/// [`vendored`] for the workspace `ws`, read without the block, and the +/// project in its directory `dir` (empty, or with a `/` at its end), by +/// what `files` holds beside it: before the checkout itself is looked at. +fn gate(ws: &Workspace, files: &dyn Fn(&str) -> Entry, dir: &str, locks: &[String]) -> Vendored { + let tags = ws.tags(&EXTENSION, "from_lock"); + let mine = |tag: &&Tag| { + let read = reads(ws, tag, dir, locks); + matches!(read, Some(Read::Ours(_) | Read::Any(_))) + }; + match tags.calls.iter().find(mine) { + None => Vendored::Plain, + Some(tag) => match feeds(ws, files, &tags, tag, dir) { + Ok(feeds) => Vendored::Block(feeds), + Err(why) => Vendored::Declined(why), + }, + } +} + +/// What the block holds for the hub of `tag`, the tag of `tags` that reads +/// a lock of the project in `dir`, or why it cannot be shown to work. +fn feeds( + ws: &Workspace, + files: &dyn Fn(&str) -> Entry, + tags: &Tags, + tag: &Tag, + dir: &str, +) -> Result { + let place = |file: &str, line: usize| match line { + 0 => file.to_string(), + line => format!("{file}:{line}"), + }; + let here = format!("{}: this `nuget.from_lock`", place(tag.file, tag.call.line)); + if !dir.is_empty() { + return Err(format!( + "{here} reads the lock of a project below the root of its Bazel workspace, and the \ + block was built for a project at the root alone" + )); + } + if let Some(Doubt { file, line, why }) = ws.doubts.iter().chain(&tags.doubts).next() { + return Err(format!( + "{}: {why}, so socket-patch cannot tell which `nuget.from_lock` tags the workspace has", + place(file, *line) + )); + } + if let Some(other) = tags.calls.iter().find(|other| *other != tag) { + return Err(format!( + "{}: the workspace has more than one `nuget.from_lock`, and the block was built \ + beside one alone", + place(other.file, other.call.line) + )); + } + let written = "is not a call of its own with every argument written out"; + let against = tag.call.args.iter().find_map(|arg| match &arg.how { + How::Keyword(name) if ARGUMENTS.contains(&name.as_str()) => None, + How::Keyword(name) if name == "local_package_dirs" => Some( + "has `local_package_dirs`, which rules_csharp asks before every feed: with the \ + upstream package in one, the Bazel build fails on the re-pinned `contentHash`" + .to_string(), + ), + How::Keyword(name) => Some(format!("has `{name}`, which the block was not built with")), + _ => Some(written.to_string()), + }); + let against = against.or((!tag.call.whole).then(|| written.to_string())); + if let Some(against) = against { + return Err(format!("{here} {against}")); + } + // What can stand in a string of the block as it is. + let plain = |text: &str| { + let quoted = |b: u8| !b.is_ascii_graphic() || b == b'"' || b == b'\\'; + !text.is_empty() && !text.bytes().any(quoted) + }; + let string = |name: &str| match tag.call.arg(name) { + None => Ok(None), + Some(Value::Str(text)) if plain(text) => Ok(Some(text.clone())), + Some(_) => Err(format!("{here} has a `{name}` that is no plain string")), + }; + let (Some(lock), name) = (string("packages_lock_json")?, string("name")?) else { + return Err(format!("{here} {written}")); + }; + let Some(label) = proxy(ws, tag).filter(|_| tag.dev_dependency == Some(false)) else { + return Err(format!( + "{here} is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly, which a block of its own does not share" + )); + }; + // The sources of the tag's config, where it has any, stand in the + // place of its feeds: without the folders vendored mode names there. + let feeds = match tag.call.arg("feeds") { + None => Vec::new(), + Some(Value::List(feeds)) => feeds.clone(), + Some(_) => { + return Err(format!( + "{here} has `feeds` that are no list of plain strings" + )) + } + }; + let named = string("nuget_config")?; + let config = match &named { + None => Vec::new(), + Some(named) => { + let file = ws.label(named).filter(|label| label.repo == Repo::Main); + match file.map(|label| files(&label.path())) { + Some(Entry::Text(config)) => sources(&config), + _ => { + let unread = "as its `nuget_config`, which cannot be read"; + return Err(format!("{here} names `{named}` {unread}")); + } + } + } + }; + let own = |source: &String| !source.starts_with(&FOLDER["file:".len()..]); + let config: Vec = config.into_iter().filter(own).collect(); + // A config without a source gets one with the folder of the patch + // (nuget.org beside it, where NuGet had that by default): read on the + // next run, the file's sources would stand in the place of the feeds. + if let Some(named) = named.filter(|_| config.is_empty() && !feeds.is_empty()) { + return Err(format!( + "{here} has `feeds`, and its `nuget_config` `{named}` names no package source, where \ + vendored mode names its folder: rules_csharp would then take the sources of that \ + file in place of those `feeds`, so name those `feeds` in that file" + )); + } + let sources = if config.is_empty() { feeds } else { config }; + if !sources.iter().all(|source| plain(source)) { + return Err(format!( + "{here} has a package source that cannot stand in a string of {FILE}" + )); + } + + let module = EXTENSION.module; + let selected = match files("MODULE.bazel.lock") { + Entry::Text(lock) => ModuleLock::parse(&lock), + _ => ModuleLock::default(), + }; + let asked = asked(ws, module); + match (&asked, &selected.selected(module)[..]) { + (Asked::Unknown(at), _) => Err(format!( + "{at} of {module} socket-patch cannot tell which release of the ruleset Bazel builds \ + with, and the block was built with {module} {RULESET} alone" + )), + (_, [selected]) if asked.stale(selected) => Err(format!( + "{FILE} asks for {module} {} and MODULE.bazel.lock holds {selected}: build once so \ + that Bazel updates its lock", + asked.wanted() + )), + (_, [selected]) if *selected != RULESET => Err(format!( + "Bazel selected {module} {selected}, and the block was built with {module} {RULESET} \ + alone" + )), + (_, [_]) => Ok(()), + _ => Err(format!( + "MODULE.bazel.lock does not say which release of {module} Bazel selected: build once \ + so that Bazel writes its lock" + )), + }?; + match declared_release(files) { + Some(release) if BAZELS.contains(&release) => Ok(()), + Some((major, minor, patch)) => Err(format!( + "the checkout names Bazel {major}.{minor}.{patch} (`.bazeliskrc` or `.bazelversion`), \ + and {BUILT_ON}" + )), + None => Err(format!( + "no file of the checkout names the Bazel release that builds it, and {BUILT_ON}: \ + name the release in `.bazelversion`" + )), + }?; + let unfetched = "under which Bazel may not take the committed package"; + let remote = "which the block was not built with: a remote downloader takes no `file:` feed"; + let words = [ + "repository_disable_download", + "vendor_dir", + "remote_downloader", + ]; + match mentions(files, &words) { + Ok(named) => named + .into_iter() + .next() + .map_or(Ok(()), |(file, line, word)| { + let why = match word.contains(words[2]) { + true => remote, + false => unfetched, + }; + Err(format!("{file}:{line} names `{word}`, {why}")) + }), + Err(file) => Err(format!( + "the rc file {file} cannot be read, and may name an option {unfetched}" + )), + }?; + Ok(Feeds { + label, + name, + lock, + sources, + }) +} + +/// The package sources of the `nuget.config` text `config` as rules_csharp +/// reads them (`_parse_nuget_config` in `csharp/extensions.bzl` at 0.5.0): +/// between the first `` and the `` after +/// it, line by line, the `value` of each line that starts with ` Vec { + let inside = config.split_once(""); + let inside = inside.and_then(|(_, rest)| rest.split_once("")); + let mut sources = Vec::new(); + for line in inside.map_or("", |(inside, _)| inside).split(['\n', '\r']) { + let line = line.trim(); + let value = |quote: char| { + let (_, value) = line.split_once(&format!("value={quote}"))?; + Some(value.split_once(quote)?.0.to_string()) + }; + if line.starts_with("") || line.contains("") { + sources.clear(); + } else if line.starts_with(" String { + let folders = folders.iter().map(|folder| format!("file:{folder}")); + let listed: String = folders + .chain(feeds.sources.iter().cloned()) + .map(|feed| format!(" \"{feed}\",\n")) + .collect(); + let name = feeds + .name + .as_ref() + .map(|name| format!(" name = \"{name}\",\n")); + format!( + "{BEGIN}\n{PROXY} = use_extension(\"{}\", \"nuget\")\n{PROXY}.from_lock(\n \ + feeds = [\n{listed} ],\n{} packages_lock_json = \"{}\",\n)\n{END}", + feeds.label, + name.unwrap_or_default(), + feeds.lock + ) +} + +/// What a `MODULE.bazel` holds of the block. +#[derive(Debug, PartialEq, Eq)] +enum Block { + None, + /// The block as socket-patch writes it: where it is, and what it + /// holds, the folders apart. + Ours(Range, Feeds, Vec), + /// A block that is not what socket-patch writes for what it names: + /// the line of its [`BEGIN`]. + Edited(usize), +} + +fn find(text: &str) -> Block { + let (at, line) = match block::find(text, BEGIN) { + Found::None => return Block::None, + Found::Edited(line) => return Block::Edited(line), + Found::At(at, line) => (at, line), + }; + let lines: Vec<&str> = text[at.clone()].lines().collect(); + let between = |open: &str, close: &str| { + let inside = |line: &&str| Some(line.strip_prefix(open)?.strip_suffix(close)?.to_string()); + lines.iter().filter_map(inside).collect::>() + }; + let one = |open: &str, close: &str| between(open, close).into_iter().next(); + let label = one(&format!("{PROXY} = use_extension(\""), "\", \"nuget\")"); + let lock = one(" packages_lock_json = \"", "\","); + let listed = between(" \"", "\",").into_iter(); + let (folders, sources): (Vec, Vec) = + listed.partition(|feed| feed.starts_with(FOLDER)); + let folders: Vec = folders + .iter() + .map(|feed| feed["file:".len()..].into()) + .collect(); + let ours = label.zip(lock).map(|(label, lock)| Feeds { + label, + name: one(" name = \"", "\","), + lock, + sources, + }); + let ours = ours.filter(|feeds| block::is(text, &at, &render(feeds, &folders))); + ours.map_or(Block::Edited(line), |feeds| Block::Ours(at, feeds, folders)) +} + +/// `module`, the text of the root `MODULE.bazel`, with the folder `folder` +/// of a vendored package (from the Bazel root) in the block for `feeds`: +/// in the block that is there, which then holds what `feeds` holds now, or +/// in a new one at the end of the file ([`block::put`]). The folders of +/// `superseded`, those of earlier patches of the same package, go out of +/// the block: the hub asks its feeds in their order, and such a folder no +/// longer holds what the lock pins. `None` when the block that is there +/// was changed by hand. +pub fn with_folder( + module: &str, + feeds: &Feeds, + folder: &str, + superseded: &[String], +) -> Option { + let (at, mut folders) = match find(module) { + Block::Edited(_) => return None, + Block::None => (None, Vec::new()), + Block::Ours(at, _, folders) => (Some(at), folders), + }; + folders.retain(|other| other != folder && !superseded.contains(other)); + folders.push(folder.to_string()); + folders.sort(); + Some(block::put(module, at, &render(feeds, &folders))) +} + +/// `module` without the folder `folder` in its block. With the last folder +/// the block goes, and what [`with_folder`] put before it: the file is then +/// byte for byte what it was before its first folder. A file without a +/// block is given as it is. `Err` when the block was changed by hand: the +/// line of the file at which it starts. +pub fn without_folder(module: &str, folder: &str) -> Result { + let (at, feeds, mut folders) = match find(module) { + Block::Edited(line) => return Err(line), + Block::None => return Ok(module.to_string()), + Block::Ours(at, feeds, folders) => (at, feeds, folders), + }; + folders.retain(|other| other != folder); + Ok(match folders.is_empty() { + true => block::cut(module, at), + false => block::put(module, Some(at), &render(&feeds, &folders)), + }) +} + #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::super::workspace::Entry; use super::*; @@ -1051,4 +1564,502 @@ mod tests { assert!(read(&root).is_some()); assert_eq!(withheld(&root, "nuget.config", &[]), None); } + + /// What a checkout holds beside its `MODULE.bazel` where the block can + /// be shown to work: Bazel's lock, which says that rules_csharp 0.5.0 + /// was selected, the release of the Bazel that builds it, and the + /// config the fixture's tag names. + const SELECTED: &str = r#"{"lockFileVersion": 28, "registryFileHashes": { + "https://bcr.bazel.build/modules/rules_csharp/0.5.0/source.json": "sum"}}"#; + const CONFIG: &str = r#" + + + + + + +"#; + const NUGET_ORG: &str = "https://api.nuget.org/v3/index.json"; + /// A config whose one source is a folder of vendored mode. + const OWN: &str = "\n\n"; + const LABEL: &str = "@rules_csharp//csharp:extensions.bzl"; + + /// For the tests of what vendors a package elsewhere: makes `dir` the + /// root of a Bazel workspace whose one tag reads the project's lock and + /// config, where the block can be shown to work. Gives its + /// `MODULE.bazel`. + pub(crate) fn checkout(dir: &Path) -> String { + let module = module(WIRED); + let files = [ + (FILE, module.as_str()), + ("MODULE.bazel.lock", SELECTED), + (".bazelversion", "9.3.2\n"), + ]; + for (name, text) in files { + std::fs::write(dir.join(name), text).unwrap(); + } + module + } + + /// What [`gate`] makes of the project at the root of the workspace + /// whose `MODULE.bazel` is [`module`] with `rest`, beside the files of + /// a checkout whose block works, with `more` in the place of those of + /// the same name (`None`: the file is not there). + fn gated(rest: &str, more: &[(&str, Option<&str>)]) -> Vendored { + let module = module(rest); + let files = [ + (FILE, module.as_str()), + ("MODULE.bazel.lock", SELECTED), + (".bazelversion", "9.3.2\n"), + ("nuget.config", CONFIG), + ]; + let view = |path: &str| { + let given = more.iter().find(|(name, _)| *name == path); + let text = match given { + Some((_, text)) => *text, + None => files.iter().find(|(name, _)| *name == path).map(|f| f.1), + }; + text.map_or(Entry::Absent, |text| Entry::Text(text.to_string())) + }; + let lock = ["packages.lock.json".to_string()]; + gate(&Workspace::read(&view), &view, "", &lock) + } + + /// The block of [`gated`], when it is one. + fn block_of(rest: &str, more: &[(&str, Option<&str>)]) -> Feeds { + match gated(rest, more) { + Vendored::Block(feeds) => feeds, + other => panic!("{rest}: {other:?}"), + } + } + + fn feeds(name: Option<&str>, sources: &[&str]) -> Feeds { + Feeds { + label: LABEL.to_string(), + name: name.map(String::from), + lock: "//:packages.lock.json".to_string(), + sources: sources.iter().map(|source| source.to_string()).collect(), + } + } + + #[test] + fn the_block_holds_what_the_hub_has_without_it() { + // The sources of the tag's config, as the fixture has them. + assert_eq!(block_of(WIRED, &[]), feeds(None, &[NUGET_ORG])); + // A tag without a config, and one with feeds: nothing, the feeds. + assert_eq!(block_of(BARE, &[]), feeds(None, &[])); + let fed = BARE.replace(")", ", feeds = [\"https://a.example/v3/index.json\"])"); + let a = ["https://a.example/v3/index.json"]; + assert_eq!(block_of(&fed, &[]), feeds(None, &a)); + // The sources of a config stand in the place of the feeds. The + // folders vendored mode names there are none of the hub's. + let both = WIRED.replace( + "nuget_config", + "feeds = [\"https://a.example\"],\n nuget_config", + ); + assert_eq!(block_of(&both, &[]), feeds(None, &[NUGET_ORG])); + let only_own = [("nuget.config", Some(OWN))]; + assert_eq!(block_of(WIRED, &only_own), feeds(None, &[])); + let none = WIRED.replace("nuget_config", "feeds = [],\n nuget_config"); + assert_eq!(block_of(&none, &only_own), feeds(None, &[])); + // The name of the hub goes with it, and what changes nothing for + // the block is passed over. + let named = WIRED.replace( + "nuget_config", + "name = \"packages\",\n use_public_sources = False,\n nuget_config", + ); + assert_eq!(block_of(&named, &[]), feeds(Some("packages"), &[NUGET_ORG])); + // The label of the extension is the one the tag is called on. + let renamed = module(WIRED) + .replace("\"0.5.0\")", "\"0.5.0\", repo_name = \"csharp\")") + .replace("@rules_csharp//", "@csharp//"); + let view = |path: &str| match path { + FILE => Entry::Text(renamed.clone()), + "MODULE.bazel.lock" => Entry::Text(SELECTED.to_string()), + ".bazelversion" => Entry::Text("7.7.2\n".to_string()), + "nuget.config" => Entry::Text(CONFIG.to_string()), + _ => Entry::Absent, + }; + let lock = ["packages.lock.json".to_string()]; + let Vendored::Block(read) = gate(&Workspace::read(&view), &view, "", &lock) else { + panic!("no block"); + }; + assert_eq!(read.label, "@csharp//csharp:extensions.bzl"); + } + + #[test] + fn a_project_whose_lock_no_tag_reads_is_vendored_as_without_bazel() { + for rest in [ + String::new(), + BARE.replace("//:", "//api:"), + BARE.replace("//:", "@other//:"), + "nuget.from_lock()".to_string(), + // Also where the block could not be shown to work. + format!("{}\nMORE = [nuget]", BARE.replace("//:", "//api:")), + ] { + assert_eq!(gated(&rest, &[]), Vendored::Plain, "{rest}"); + let unnamed = [(".bazelversion", None)]; + assert_eq!(gated(&rest, &unnamed), Vendored::Plain, "{rest}"); + } + } + + #[test] + fn the_block_is_declined_where_it_cannot_be_shown_to_work() { + let with = + |more: &str| WIRED.replace("nuget_config", &format!("{more},\n nuget_config")); + let isolated = module(WIRED).replace("\"nuget\")", "\"nuget\", isolate = True)"); + let dev = module(WIRED).replace("\"nuget\")", "\"nuget\", dev_dependency = True)"); + let quoted = "\n\n\ + "; + let pinned = "single_version_override(module_name = \"rules_csharp\", version = \"0.4.0\")"; + let archive = "archive_override(module_name = \"rules_csharp\", urls = [\"https://a\"])"; + let newer = SELECTED.replace("0.5.0", "0.6.0"); + // What the workspace holds after its module line, the files beside + // it, and what the reason says. + type Row<'a> = (String, Vec<(&'a str, Option<&'a str>)>, &'a str); + let rows: Vec = + vec![ + // The tags. + ( + format!("{WIRED}\n{}", BARE.replace("//:", "//api:")), + vec![], + "MODULE.bazel:8: the workspace has more than one `nuget.from_lock`", + ), + ( + format!("{WIRED}\nMORE = [nuget]"), + vec![], + "MODULE.bazel:8: `nuget` is used other than to call a tag, so socket-patch cannot \ + tell which `nuget.from_lock` tags the workspace has", + ), + ( + "nuget.from_lock(**TAG)".to_string(), + vec![], + "MODULE.bazel:4: this `nuget.from_lock` is not a call of its own with every \ + argument written out", + ), + ( + format!("True and {}", WIRED.replace('\n', " ")), + vec![], + "is not a call of its own with every argument written out", + ), + ( + WIRED.replace("\"//:packages.lock.json\"", "LOCK"), + vec![], + "has a `packages_lock_json` that is no plain string", + ), + ( + with("local_package_dirs = [\"/opt/packages\"]"), + vec![], + "MODULE.bazel:4: this `nuget.from_lock` has `local_package_dirs`, which \ + rules_csharp asks before every feed", + ), + ( + with("netrc = \"//:.netrc\""), + vec![], + "has `netrc`, which the block was not built with", + ), + ( + with("feeds = FEEDS"), + vec![], + "has `feeds` that are no list of plain strings", + ), + ( + WIRED.to_string(), + vec![("nuget.config", None)], + "names `//:nuget.config` as its `nuget_config`, which cannot be read", + ), + ( + WIRED.to_string(), + vec![("nuget.config", Some(quoted))], + "has a package source that cannot stand in a string of MODULE.bazel", + ), + // Feeds beside a config that vendored mode gives its first + // source: an empty one, and one that holds a folder of its own. + ( + with("feeds = [\"https://a.example\"]"), + vec![("nuget.config", Some("\n\n"))], + "MODULE.bazel:4: this `nuget.from_lock` has `feeds`, and its `nuget_config` \ + `//:nuget.config` names no package source, where vendored mode names its \ + folder", + ), + ( + with("feeds = [\"https://a.example\"]"), + vec![("nuget.config", Some(OWN))], + "so name those `feeds` in that file", + ), + ( + WIRED.to_string(), + vec![(FILE, Some(&isolated))], + "is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly", + ), + ( + WIRED.to_string(), + vec![(FILE, Some(&dev))], + "is called on a `use_extension` that is isolated, a dev dependency or not \ + written plainly", + ), + // The release of the ruleset. + ( + WIRED.to_string(), + vec![("MODULE.bazel.lock", Some(&newer))], + "Bazel selected rules_csharp 0.6.0, and the block was built with rules_csharp \ + 0.5.0 alone", + ), + ( + format!("{WIRED}\n{pinned}"), + vec![], + "MODULE.bazel asks for rules_csharp 0.4.0 and MODULE.bazel.lock holds 0.5.0", + ), + ( + WIRED.to_string(), + vec![("MODULE.bazel.lock", None)], + "MODULE.bazel.lock does not say which release of rules_csharp Bazel selected: \ + build once so that Bazel writes its lock", + ), + ( + format!("{WIRED}\n{archive}"), + vec![], + "MODULE.bazel:8: with this `archive_override` of rules_csharp socket-patch cannot \ + tell which release of the ruleset Bazel builds with", + ), + // The release of Bazel. + ( + WIRED.to_string(), + vec![(".bazelversion", Some("9.1.0\n"))], + "the checkout names Bazel 9.1.0 (`.bazeliskrc` or `.bazelversion`), and the block \ + was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone", + ), + ( + WIRED.to_string(), + vec![(".bazelversion", None)], + "no file of the checkout names the Bazel release that builds it, and the block \ + was built on Bazel 7.7.2, 8.8.2 and 9.3.2 alone: name the release in \ + `.bazelversion`", + ), + // The rc files. + ( + WIRED.to_string(), + vec![(".bazelrc", Some("build --jobs=4\ncommon --vendor_dir=third_party\n"))], + ".bazelrc:2 names `--vendor_dir=third_party`, under which Bazel may not take the \ + committed package", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("fetch --repository_disable_download\n"))], + ".bazelrc:1 names `--repository_disable_download`", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("common --experimental_remote_downloader=grpcs://a\n"))], + ".bazelrc:1 names `--experimental_remote_downloader=grpcs://a`, which the block \ + was not built with: a remote downloader takes no `file:` feed", + ), + ( + WIRED.to_string(), + vec![(".bazelrc", Some("build 'unclosed\n"))], + "the rc file .bazelrc:1 cannot be read", + ), + ]; + for (rest, more, says) in rows { + let Vendored::Declined(why) = gated(&rest, &more) else { + panic!("not declined: {rest} {more:?}"); + }; + assert!(why.contains(says), "{rest}: {why}"); + } + // A project below the root of its workspace. + let below = module(&WIRED.replace("//:", "//svc/app:")); + let view = |path: &str| match path { + FILE => Entry::Text(below.clone()), + _ => Entry::Absent, + }; + let lock = ["packages.lock.json".to_string()]; + let Vendored::Declined(why) = gate(&Workspace::read(&view), &view, "svc/app/", &lock) + else { + panic!("not declined below the root"); + }; + let says = "MODULE.bazel:4: this `nuget.from_lock` reads the lock of a project below the \ + root of its Bazel workspace"; + assert!(why.starts_with(says), "{why}"); + } + + #[test] + fn the_sources_of_a_config_are_read_as_the_ruleset_reads_them() { + let config = |inside: &str| format!("\n{inside}\n"); + for (inside, read) in [ + ("", vec!["https://a"]), + (" \r\n", vec!["https://a", "b"]), + // A `\n\n", vec!["https://b"]), + ("\n", vec![]), + // No comment is passed over and no entity decoded. + ("", vec!["https://a?x=1&y=2"]), + ] { + assert_eq!(sources(&config(inside)), read, "{inside}"); + } + assert_eq!(sources(""), [""; 0]); + assert_eq!(sources("\n"), [""; 0]); + } + + /// The block as it was built on Bazel 9.3.2, 8.8.2 and 7.7.2, for the + /// patch `7e57ce11-...`. + const FOLDER_A: &str = ".socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc"; + const FOLDER_B: &str = ".socket/vendor/nuget/9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f"; + const BLOCK: &str = r#"# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") +socket_patch_nuget.from_lock( + feeds = [ + "file:.socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc", + "https://api.nuget.org/v3/index.json", + ], + packages_lock_json = "//:packages.lock.json", +) +# <<< socket-patch <<<"#; + + #[test] + fn a_folder_is_added_once_and_taken_out_to_the_byte() { + let fixture = feeds(None, &[NUGET_ORG]); + let base = module(WIRED); + let ends = ["\n", "", "\n\n"].map(|end| format!("{}{end}", base.trim_end())); + let crlf = ends[0].replace('\n', "\r\n"); + for module in ends.iter().chain([&crlf]) { + let eol = if module.contains('\r') { "\r\n" } else { "\n" }; + let one = with_folder(module, &fixture, FOLDER_A, &[]).expect("a block"); + let block = BLOCK.replace('\n', eol); + let expected = match module.ends_with('\n') { + true => format!("{module}{eol}{block}{eol}"), + false => format!("{module}{eol}{eol}{block}"), + }; + assert_eq!(one, expected); + // Once more: the same text. + assert_eq!( + with_folder(&one, &fixture, FOLDER_A, &[]), + Some(one.clone()) + ); + // A second folder, in the order of their names, and the name + // of a hub that has one. + let named = feeds(Some("packages"), &[NUGET_ORG]); + let two = with_folder(&one, &named, FOLDER_B, &[]).expect("two folders"); + let both = + format!(" \"file:{FOLDER_A}\",{eol} \"file:{FOLDER_B}\",{eol}"); + assert!(two.contains(&both), "{two}"); + let name = format!(" ],{eol} name = \"packages\",{eol} packages_lock_json"); + assert!(two.contains(&name), "{two}"); + // The first one out: the block stays for the second, and goes + // with it. The file is then the one of before. + let left = without_folder(&two, FOLDER_A).expect("one folder"); + assert!( + !left.contains(FOLDER_A) && left.contains(FOLDER_B), + "{left}" + ); + assert_eq!(without_folder(&left, FOLDER_B).as_ref(), Ok(module)); + assert_eq!(without_folder(&one, FOLDER_A).as_ref(), Ok(module)); + // A later patch of the same package takes the place of the + // folder it supersedes, and the block goes with it alone. + let later = with_folder(&one, &fixture, FOLDER_B, &[FOLDER_A.to_string()]); + let later = later.expect("the folder of the later patch"); + assert!( + !later.contains(FOLDER_A) && later.contains(FOLDER_B), + "{later}" + ); + assert_eq!(without_folder(&later, FOLDER_B).as_ref(), Ok(module)); + // A folder that is not there, and a file without a block. + assert_eq!(without_folder(&one, FOLDER_B), Ok(one.clone())); + assert_eq!(without_folder(module, FOLDER_A).as_ref(), Ok(module)); + } + } + + #[test] + fn a_block_that_was_changed_by_hand_is_left_alone() { + let fixture = feeds(None, &[NUGET_ORG]); + let one = with_folder(&module(WIRED), &fixture, FOLDER_A, &[]).expect("a block"); + for edited in [ + one.replace("\"https://api.nuget.org/v3/index.json\",\n", ""), + one.replace(" feeds = [", " feeds = [ # ours"), + one.replace("# <<< socket-patch <<<", ""), + one.replace(") >>>", ") >>> "), + format!("{one}{BLOCK}\n"), + ] { + assert_ne!(edited, one); + assert_eq!( + with_folder(&edited, &fixture, FOLDER_B, &[]), + None, + "{edited}" + ); + assert_eq!(without_folder(&edited, FOLDER_A), Err(10), "{edited}"); + } + } + + #[test] + fn a_checkout_is_read_without_the_block_it_holds() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("repo"); + std::fs::create_dir_all(root.join("svc")).unwrap(); + std::fs::create_dir(base.join(".git")).unwrap(); + let lock = ["packages.lock.json".to_string()]; + // No Bazel workspace, and a project without a lock. + assert_eq!(vendored(&root, &lock), Vendored::Plain); + let module = checkout(&root); + assert_eq!(vendored(&root, &[]), Vendored::Plain); + // The tag names a config that is not there yet. + let unread = "as its `nuget_config`, which cannot be read"; + let declined = |why: &str| match vendored(&root, &lock) { + Vendored::Declined(said) => assert!(said.contains(why), "{said}"), + other => panic!("{why}: {other:?}"), + }; + declined(unread); + std::fs::write(root.join("nuget.config"), CONFIG).unwrap(); + let Vendored::Block(read) = vendored(&root, &lock) else { + panic!("no block"); + }; + assert_eq!(read, feeds(None, &[NUGET_ORG])); + // With its own block in the file the workspace reads as before: + // the block's tag is no second tag. + let wired = with_folder(&module, &read, FOLDER_A, &[]).expect("a block"); + std::fs::write(root.join(FILE), &wired).unwrap(); + assert_eq!(vendored(&root, &lock), Vendored::Block(read)); + // A block that was changed by hand. + std::fs::write( + root.join(FILE), + wired.replace(" feeds = [", " feeds = [ "), + ) + .unwrap(); + declined("MODULE.bazel:10: the block that socket-patch keeps there was changed by hand"); + std::fs::write(root.join(FILE), &module).unwrap(); + // A vendor directory of Bazel's, and a workspace above this one. + std::fs::write(root.join("svc/VENDOR.bazel"), "").unwrap(); + declined("svc/VENDOR.bazel: the checkout holds a vendor directory of Bazel's"); + std::fs::remove_file(root.join("svc/VENDOR.bazel")).unwrap(); + std::fs::write(base.join("MODULE.bazel"), "").unwrap(); + declined("holds a Bazel workspace above this one"); + assert_eq!(crate::bazel::root_above(&root), Some(base.clone())); + std::fs::remove_file(base.join("MODULE.bazel")).unwrap(); + assert_eq!(crate::bazel::root_above(&root), None); + // A project below the root, whose lock the tag does not read. + assert_eq!(vendored(&root.join("svc"), &lock), Vendored::Plain); + // The file is a link to a file of the workspace. + #[cfg(unix)] + { + std::fs::rename(root.join(FILE), root.join("svc/module")).unwrap(); + std::os::unix::fs::symlink(root.join("svc/module"), root.join(FILE)).unwrap(); + declined("MODULE.bazel is a symbolic link"); + } + } + + #[test] + fn a_hosted_pin_beside_the_block_of_vendored_mode_is_withheld() { + let wired = with_folder(&module(WIRED), &feeds(None, &[NUGET_ORG]), FOLDER_A, &[]); + let said = said(&[("MODULE.bazel", &wired.expect("a block"))], "").expect("withheld"); + let starts = "MODULE.bazel:12: this `nuget.from_lock` is the one vendored mode keeps for \ + the vendored NuGet packages of this project, and its `feeds` stand in the \ + place of the package sources of nuget.config"; + assert!(said.starts_with(starts), "{said}"); + let way = "So hosted mode wrote nothing for it. Vendor this package as well (`--mode \ + vendored`), or take the vendored ones out (`socket-patch vendor --revert`), and \ + run this command again"; + assert!(said.contains(way), "{said}"); + } } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 90742bbb8..7d7305faa 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -20,7 +20,7 @@ //! | gem | gem dir (+gemspec) | Gemfile `path:` + Gemfile.lock PATH pair | //! | pypi | rebuilt wheel | per manifest flavor: uv, poetry, pdm, pipenv, requirements ([`pypi`] routes) | //! | maven | patched jar | suffixed `-socket.` tree under `.socket/vendor/maven2` + pom pin, `.mvn/maven.config` (or Gradle / sbt / scala-cli wiring) ([`maven_repo`] routes to [`jvm`]) | -//! | nuget | rebuilt nupkg | folder feed + `nuget.config` + `packages.lock.json` pin ([`nuget_feed`]) | +//! | nuget | rebuilt nupkg | folder feed + `nuget.config` + `packages.lock.json` pin, and under a rules_csharp hub a block in the root `MODULE.bazel` ([`nuget_feed`]) | //! //! npm requests route through [`npm_flavor`], which content-sniffs the //! project's lockfile (not just file presence) and dispatches to the diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 621d80c33..13360466b 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -4,12 +4,16 @@ use std::sync::Arc; use crate::utils::digest::sha512_base64_of; use serde_json::Value; +use crate::bazel::nuget::{ + vendored, with_folder, without_folder, Feeds, Vendored, VENDOR_DECLINED, +}; use crate::manifest::schema::PatchRecord; use crate::patch::apply::{ApplyResult, PatchSources}; use crate::patch::copy_tree::remove_tree; use crate::patch::path_safety::{is_safe_multi_segment, is_safe_single_segment}; +use crate::utils::env_compat::env_flag; use crate::utils::fs::{ - atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_string, + atomic_write_artifact, atomic_write_bytes_preserving_mode, read_regular_to_string, run_blocking, }; use crate::utils::line_endings::{eol_eq, respell, terminator}; use crate::utils::purl::{build_nuget_purl, parse_nuget_purl}; @@ -20,6 +24,7 @@ use super::common::{ }; use super::parse_memo::ParseMemo; use super::path::vendor_uuid_dir_rel; +use super::refusals::ALLOW_IN_BAZEL_ENV; use super::revert::{self, KeepPolicy}; use super::service_fetch::service_archive_copy; use super::state::{ @@ -40,6 +45,12 @@ use crate::formats::nuget::lock::{locked_at, PACKAGES_LOCK}; const CONFIG_SOURCE_WIRING_KIND: &str = "nuget_config_source"; const CONFIG_MAPPING_WIRING_KIND: &str = "nuget_config_mapping"; const LOCK_WIRING_KIND: &str = "nuget_lock_entry"; +/// The folder of the patch in the block of the root `MODULE.bazel` +/// ([`crate::bazel::nuget`]): the revert takes that folder out of the +/// block, whatever the record says. +pub(super) const BAZEL_WIRING_KIND: &str = "nuget_bazel_feed"; +/// The file of that block. +const MODULE_FILE: &str = crate::bazel::nuget::FILE; /// `/.gitignore`, exactly: re-include the vendored nupkg against the /// user's ignore rules (VisualStudio.gitignore's `*.nupkg`), #1061. @@ -110,6 +121,40 @@ pub(crate) fn nupkg_leaf(id_lower: &str, version: &str) -> String { format!("{id_lower}.{}.nupkg", normalize_nuget_version(version)) } +/// Where a rules_csharp hub has the package `id version_norm` in the folder +/// `uuid_dir_rel` of its patch: `//`, the shape of +/// a folder feed. `nuget.config` names this folder for such a package. +fn hub_folder_rel(uuid_dir_rel: &str, id: &str, version_norm: &str) -> String { + format!("{uuid_dir_rel}/{}/{version_norm}", id.to_lowercase()) +} + +/// Why a hub would not find `id version_norm` in the folder of its patch: +/// a lock that spells the version otherwise. rules_csharp asks a feed for +/// the lock's `resolved` as it is written, in lower case, and the folder +/// holds the version as NuGet normalizes it, which is what `dotnet restore` +/// writes into a lock. +fn spelled_otherwise<'a>( + locks: impl IntoIterator, + id: &str, + version_norm: &str, +) -> Option { + locks.into_iter().find_map(|(rel, text)| { + let doc = lock_value(text).ok()?; + let spelled = crate::formats::nuget::lock::nuget_lock_entries(&doc) + .filter(|entry| entry.id.eq_ignore_ascii_case(id)) + .map(|entry| entry.resolved) + .find(|resolved| { + normalize_nuget_version(resolved) == version_norm + && resolved.to_lowercase() != version_norm + })?; + Some(format!( + "{rel} names {id} {spelled}, and a rules_csharp hub asks its feeds for the version as \ + the lock spells it, where the folder of the patch holds {version_norm}: run `dotnet \ + restore` so that the lock names {version_norm}" + )) + }) +} + /// Everything [`vendor_nuget`] decides before it can first ask the patch /// service: the coordinate guards, the no-op of an empty patch, the /// nuget.config and packages.lock.json reads, and whether the feed already @@ -120,10 +165,26 @@ struct NugetPrelude { version: String, version_norm: String, uuid_dir_rel: String, + /// The folder `nuget.config` names for the patch: [`Self::uuid_dir_rel`], + /// or below it `/` for a package of a + /// rules_csharp hub, where a feed of the hub has it. + feed_rel: String, copy_rel: String, uuid_dir: PathBuf, nupkg_path: PathBuf, source_key: String, + /// What the block of the root `MODULE.bazel` holds beside the folder + /// of the patch. `None`: the package has no folder there. + feeds: Option, + /// Why the block of a package that is wired for a hub can no longer + /// be shown to work. + hub_doubt: Option, + /// The folders of earlier patches of this package that `nuget.config` + /// still names for a hub: this patch takes their place in the block. + superseded: Vec, + /// The locks of the project as the gate of the block is asked about + /// them ([`vendored`]). + governed_rels: Vec, config_path: Option, config_text: Option, /// Every lock the projects under the root restore into (#353, #514). @@ -174,9 +235,8 @@ async fn nuget_prelude( let id_lower = name.to_lowercase(); let version_norm = normalize_nuget_version(version); let leaf = nupkg_leaf(&id_lower, version); - let copy_rel = format!("{uuid_dir_rel}/{leaf}"); let uuid_dir = project_root.join(&uuid_dir_rel); - let nupkg_path = project_root.join(©_rel); + let nupkg_path = uuid_dir.join(&leaf); let source_key = crate::patch::redirect::generation::hosted_pin_name(&record.uuid); // The nupkg must survive the commit the vendored workflow ends with: a @@ -230,6 +290,7 @@ async fn nuget_prelude( )); } let mut locks: Vec = Vec::with_capacity(governed.locks.len()); + let governed_rels = governed.locks.clone(); for rel in governed.locks { let path = project_root.join(&rel); match read_regular_to_string(&path).await { @@ -247,10 +308,63 @@ async fn nuget_prelude( // The idempotent hot path's test (see `vendor_nuget`): a live // `` source under our key. A commented-out one — or the // key merely mentioned elsewhere — is not wiring NuGet reads. - let config_wired = config_text + let sources = config_text .as_deref() .and_then(crate::formats::nuget::parse_config) - .is_some_and(|parsed| parsed.sources.iter().any(|(key, _)| *key == source_key)); + .map(|parsed| parsed.sources) + .unwrap_or_default(); + let named = sources.iter().find(|(key, _)| *key == source_key); + let config_wired = named.is_some(); + // Where the package lies. A rules_csharp hub that reads a lock of the + // project takes it from `///`, through the + // block of the root MODULE.bazel; every other project keeps it in the + // folder itself. A package that is wired stays where the config names + // it, and only one that lies where a hub has it is the hub's. + let nested = hub_folder_rel(&uuid_dir_rel, name, &version_norm); + let for_hub = named.is_some_and(|(_, value)| *value == nested); + // An earlier patch of this package keeps its source in the config (its + // pattern is set aside): where that one lies as a hub has it, its + // folder is one this patch supersedes. + let below = format!("/{id_lower}/{version_norm}"); + let earlier = sources.iter().filter(|(key, _)| *key != source_key); + let superseded: Vec = earlier + .filter_map(|(_, value)| value.strip_suffix(&below)) + .filter(|folder| { + let uuid = folder.rsplit('/').next().unwrap_or_default(); + vendor_uuid_dir_rel("nuget", uuid).as_deref() == Some(*folder) + }) + .map(str::to_string) + .collect(); + let hub = match config_wired && !for_hub { + true => Vendored::Plain, + false => { + let (root, rels) = (project_root.to_path_buf(), governed_rels.clone()); + run_blocking(move || vendored(&root, &rels)).await + } + }; + let hub = match hub { + Vendored::Block(feeds) => match spelled_otherwise(texts(&locks), name, &version_norm) { + Some(why) => Vendored::Declined(why), + None => Vendored::Block(feeds), + }, + hub => hub, + }; + let (feeds, hub_doubt) = match hub { + Vendored::Block(feeds) => (Some(feeds), None), + Vendored::Declined(why) if for_hub => (None, Some(why)), + // The caller's own refusal ([`bazel_refusals`]) comes first; this + // one holds for every way in. + Vendored::Declined(why) if !env_flag(ALLOW_IN_BAZEL_ENV) => { + return Err(refused(VENDOR_DECLINED, declined_detail(&why))); + } + _ => (None, None), + }; + let feed_rel = match for_hub || feeds.is_some() { + true => nested, + false => uuid_dir_rel.clone(), + }; + let copy_rel = format!("{feed_rel}/{leaf}"); + let nupkg_path = project_root.join(©_rel); // The mapping routes every version of the id to this feed, which serves // only the patched one: a framework that locks another version could no // longer restore (NU1102). Refused before anything is wired (#593). @@ -308,10 +422,15 @@ async fn nuget_prelude( version: version.to_string(), version_norm, uuid_dir_rel, + feed_rel, copy_rel, uuid_dir, nupkg_path, source_key, + feeds, + hub_doubt, + superseded, + governed_rels, config_path, config_text, locks, @@ -320,6 +439,143 @@ async fn nuget_prelude( }) } +/// What a declined package is told after `why`, the reason of +/// [`vendored`]: what vendored mode would have needed, and the two ways on. +fn declined_detail(why: &str) -> String { + format!( + "{why}; vendored mode makes a rules_csharp hub take the committed package through a \ + block in the root {MODULE_FILE}, which it writes only where the checkout shows that the \ + block works, so it wrote nothing for this package; use `--mode hosted`, or pass \ + `--allow-vendored-in-bazel` to vendor the package as in a project without Bazel, which \ + the hub does not take: its build then fails" + ) +} + +/// The NuGet `candidates` (`(purl, uuid)` pairs) that vendored mode +/// declines in the project at `project_root`, each with [`VENDOR_DECLINED`] +/// and the detail: those of a project whose lock a rules_csharp hub reads, +/// where the block cannot be shown to work ([`vendored`]) or a lock spells +/// the package's version otherwise ([`spelled_otherwise`]), unless the user +/// allowed it ([`ALLOW_IN_BAZEL_ENV`]). A package whose folder +/// `nuget.config` already names is let through: the run leaves the config +/// as it is. Read-only, and it starts no program. +pub(crate) async fn bazel_refusals<'a>( + project_root: &Path, + candidates: &[(&'a str, &str)], +) -> Vec<(&'a str, &'static str, String)> { + if candidates.is_empty() || env_flag(ALLOW_IN_BAZEL_ENV) { + return Vec::new(); + } + let root = project_root.to_path_buf(); + let (hub, rels) = run_blocking(move || { + // Outside a Bazel workspace nothing is declined: no lock is looked + // for there. + if crate::bazel::bazel_root(&root).is_none() { + return (Vendored::Plain, Vec::new()); + } + let governed = super::nuget_config::governed_locks_on_disk(&root); + let rels = governed.map(|governed| governed.locks).unwrap_or_default(); + (vendored(&root, &rels), rels) + }) + .await; + // A hub whose block works still finds no package whose version a lock + // spells otherwise ([`spelled_otherwise`]). + let mut locks: Vec<(String, String)> = Vec::new(); + for rel in rels + .into_iter() + .filter(|_| matches!(hub, Vendored::Block(_))) + { + if let Ok(text) = read_regular_to_string(&project_root.join(&rel)).await { + locks.push((rel, text)); + } + } + let why = |purl: &str| match &hub { + Vendored::Plain => None, + Vendored::Declined(why) => Some(why.clone()), + Vendored::Block(_) => { + let (id, version) = parse_nuget_purl(purl)?; + let texts = locks + .iter() + .map(|(rel, text)| (rel.as_str(), text.as_str())); + spelled_otherwise(texts, &id, &normalize_nuget_version(&version)) + } + }; + if matches!(hub, Vendored::Plain) { + return Vec::new(); + } + let config = match existing_config_path(project_root).await { + Some(path) => read_regular_to_string(&path).await.ok(), + None => None, + }; + let sources = config + .as_deref() + .and_then(crate::formats::nuget::parse_config); + let sources = sources.map(|config| config.sources).unwrap_or_default(); + let wired = |uuid: &str| { + let key = crate::patch::redirect::generation::hosted_pin_name(uuid); + let folder = vendor_uuid_dir_rel("nuget", uuid); + let names = |(named, value): &(String, String)| { + *named == key && folder.as_ref().is_some_and(|dir| value.starts_with(dir)) + }; + sources.iter().any(names) + }; + let declined = candidates.iter().filter(|(_, uuid)| !wired(uuid)); + declined + .filter_map(|(purl, _)| Some((*purl, VENDOR_DECLINED, declined_detail(&why(purl)?)))) + .collect() +} + +/// Keep the folder of a patch, `uuid_dir_rel`, in the block of the root +/// `MODULE.bazel`, which then holds what `feeds` holds now, without the +/// folders of `superseded`. +async fn keep_in_block( + project_root: &Path, + feeds: &Feeds, + uuid_dir_rel: &str, + superseded: &[String], +) -> Result<(), String> { + let path = project_root.join(MODULE_FILE); + let module = read_regular_to_string(&path) + .await + .map_err(|e| format!("unreadable {}: {e}", path.display()))?; + let Some(kept) = with_folder(&module, feeds, uuid_dir_rel, superseded) else { + return Err(format!( + "the block that socket-patch keeps in {MODULE_FILE} was changed by hand" + )); + }; + if kept == module { + return Ok(()); + } + atomic_write_bytes_preserving_mode(&path, kept.as_bytes()) + .await + .map_err(|e| format!("failed to write {}: {e}", path.display())) +} + +/// For a package that is wired for a hub: its folder in the block as the +/// hub's tag has it now, or the warning that the block was left as it is, +/// and why. +async fn block_refreshed( + project_root: &Path, + feeds: Option<&Feeds>, + doubt: Option, + uuid_dir_rel: &str, + superseded: &[String], +) -> Option { + let why = match feeds { + Some(feeds) => keep_in_block(project_root, feeds, uuid_dir_rel, superseded) + .await + .err(), + None => doubt, + }?; + Some(VendorWarning::new( + VENDOR_DECLINED, + format!( + "{why}; the block of {MODULE_FILE} was left as it is, and socket-patch can no longer \ + show that the Bazel build takes the committed package" + ), + )) +} + /// Whether [`vendor_nuget`] — a wet run with the service enabled — asks the /// patch service for `record`: past every refusal it raises first and not /// answered by the in-sync hot path. The vendor loop's download plan @@ -367,10 +623,15 @@ pub async fn vendor_nuget( version, version_norm, uuid_dir_rel, + feed_rel, copy_rel, uuid_dir, nupkg_path, source_key, + feeds, + hub_doubt, + superseded, + governed_rels, config_path, config_text, locks, @@ -389,10 +650,18 @@ pub async fn vendor_nuget( // first run's ledger entry holds the only copy of the verbatim pre-vendor // originals, and re-recording here would clobber them. if config_wired { + // A package of a hub: the block follows the hub's tag, wired or not. + let block = match dry_run { + true => None, + false => { + let feeds = feeds.as_ref(); + block_refreshed(project_root, feeds, hub_doubt, &uuid_dir_rel, &superseded).await + } + }; if in_sync { // The warning keeps firing on re-runs until the stale copy is // gone (#352). - let mut warnings = Vec::new(); + let mut warnings: Vec = block.into_iter().collect(); if let (Some(cached), Some(bytes)) = ( extracted_content_hash(installed_dir).await, read_zip_artifact(&nupkg_path).await, @@ -424,7 +693,7 @@ pub async fn vendor_nuget( // already correct and the full path would re-record the live vendored // fragments as `original`, breaking a later `--revert`. if !dry_run { - let mut warnings: Vec = Vec::new(); + let mut warnings: Vec = block.into_iter().collect(); let (bytes, mut result) = match materialise_patched_nupkg( purl, installed_dir, @@ -572,7 +841,7 @@ pub async fn vendor_nuget( &inherited.keys, inherited.mapped, &source_key, - &uuid_dir_rel, + &feed_rel, name, ), }; @@ -661,6 +930,33 @@ pub async fn vendor_nuget( } } } + // ── the block of a rules_csharp hub (a failure unwinds both) ───────── + if let Some(first) = feeds { + // As the hub's tag reads now: this run gave a config without a + // package source its first one, and the next run reads the block's + // sources from that file. + let root = project_root.to_path_buf(); + let feeds = match run_blocking(move || vendored(&root, &governed_rels)).await { + Vendored::Block(now) => now, + _ => first, + }; + let kept = keep_in_block(project_root, &feeds, &uuid_dir_rel, &superseded).await; + if let Err(detail) = kept { + unwind_locks(&written).await; + unwind_config(&config_target, config_text.as_deref(), &uuid_dir).await; + result.success = false; + result.error = Some(detail); + return done(result, None, warnings); + } + lock_records.push(WiringRecord { + file: MODULE_FILE.to_string(), + kind: BAZEL_WIRING_KIND.to_string(), + action: WiringAction::Added, + key: Some(uuid_dir_rel.clone()), + original: None, + new: None, + }); + } if locks.is_empty() { warnings.push(VendorWarning::new( "vendor_nuget_no_lockfile", @@ -726,8 +1022,8 @@ pub async fn vendor_nuget( original: None, new: Some(Value::String(config_edit.mapping_fragment.clone())), }; - // Application order: config source, config mapping, then the lock pin. - // Revert runs them in reverse (lock → mapping → source). + // Application order: config source, config mapping, the lock pin, then + // the block of a hub. Revert runs them in reverse. let mut wiring = vec![source_record, mapping_record]; wiring.extend(lock_records); @@ -849,6 +1145,11 @@ pub async fn revert_nuget_opts( version_norm: normalize_nuget_version(&version), source_key: crate::patch::redirect::generation::hosted_pin_name(&entry.uuid), }; + // The folder the config names: the patch's own, or the one below it + // where a hub has the package, when the artifact lies there. + let nested = hub_folder_rel(&uuid_dir_rel, &id, &package.version_norm); + let for_hub = entry.artifact.path.starts_with(&format!("{nested}/")); + let feed_rel = if for_hub { &nested } else { &uuid_dir_rel }; // SECURITY: state.json is committed and tamper-able, and the records are // replayed one write at a time: every one of them is checked before the // first write, so a refused record leaves the whole entry untouched. @@ -857,6 +1158,14 @@ pub async fn revert_nuget_opts( return RevertOutcome::failed(super::state::refused_record(entry, w, &why)); } } + // Nor beside a block that was changed by hand, which keeps the folder + // of the patch: the hub would hold the committed package to the lock + // that the revert restores, and the Bazel build would fail. + if entry.wiring.iter().any(|w| w.kind == BAZEL_WIRING_KIND) { + if let Err(why) = revert_block_record(project_root, &uuid_dir_rel, true).await { + return RevertOutcome::failed(why); + } + } let mut warnings = Vec::new(); // The lock pin may only go back to the upstream contentHash when @@ -873,7 +1182,7 @@ pub async fn revert_nuget_opts( .filter(|w| w.kind == CONFIG_SOURCE_WIRING_KIND) { if matches!( - revert_config_record(project_root, &uuid_dir_rel, &package, w, true).await, + revert_config_record(project_root, feed_rel, &package, w, true).await, Ok(false) ) && config_references(project_root, &w.file, &uuid_dir_rel).await { @@ -881,7 +1190,8 @@ pub async fn revert_nuget_opts( } } // Reverse application order: lock pin, then the (no-op) mapping audit - // record, then the authoritative config restore. + // record, then the authoritative config restore. The block of a hub + // goes after them all, below. for w in entry.wiring.iter().rev() { let restored = match w.kind.as_str() { // SECURITY: state.json is committed and tamper-able; the lock @@ -915,8 +1225,9 @@ pub async fn revert_nuget_opts( // record, so there is nothing to undo here. CONFIG_MAPPING_WIRING_KIND => Ok(true), CONFIG_SOURCE_WIRING_KIND => { - revert_config_record(project_root, &uuid_dir_rel, &package, w, dry_run).await + revert_config_record(project_root, feed_rel, &package, w, dry_run).await } + BAZEL_WIRING_KIND => continue, _ => { warnings.push(VendorWarning::new( "vendor_lock_entry_drifted", @@ -946,6 +1257,36 @@ pub async fn revert_nuget_opts( } } + // The block of a hub goes last, and only with the config's source: a + // lock that failed above leaves it, so the build stays as it was for + // the retry. A config that is left wired keeps its lock pin and its + // package, and the hub takes that package through the block alone: + // without it the hub would read the folder in `nuget.config` as the + // URL of a feed, and the Bazel build would fail. + if entry.wiring.iter().any(|w| w.kind == BAZEL_WIRING_KIND) { + if config_still_routes { + let config = entry + .wiring + .iter() + .find(|c| c.kind == CONFIG_SOURCE_WIRING_KIND) + .map_or("nuget.config", |c| c.file.as_str()); + warnings.push(VendorWarning::new( + "vendor_lock_entry_drifted", + format!( + "{config} still routes {id} to the vendored feed, so the block of \ + {MODULE_FILE} is kept" + ), + )); + } else if let Err(e) = revert_block_record(project_root, &uuid_dir_rel, dry_run).await { + return RevertOutcome { + kept_artifact: false, + success: false, + warnings, + error: Some(e), + }; + } + } + let outcome = RevertOutcome { kept_artifact: false, success: true, @@ -967,6 +1308,37 @@ pub async fn revert_nuget_opts( revert::finish(outcome, project_root, &uuid_dir_rel, opts, policy).await } +/// Take the folder of a patch, `uuid_dir_rel`, out of the block of the +/// root `MODULE.bazel`: the block goes with its last folder. `Ok(true)` = +/// taken out (or would be on a dry run) / not there; `Err` = the block was +/// changed by hand, with the ways on, or a real I/O failure. +async fn revert_block_record( + project_root: &Path, + uuid_dir_rel: &str, + dry_run: bool, +) -> Result { + let path = project_root.join(MODULE_FILE); + let module = match read_regular_to_string(&path).await { + Ok(module) => module, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(true), + Err(e) => return Err(format!("unreadable {}: {e}", path.display())), + }; + let without = without_folder(&module, uuid_dir_rel).map_err(|line| { + format!( + "{MODULE_FILE}:{line}: the block that socket-patch keeps there was changed by hand, \ + so the folder of this patch stays in it and nothing was reverted: with the lock \ + restored, the Bazel build would fail on the committed package. Put the block back \ + as socket-patch wrote it, or delete it, and run this command again" + ) + })?; + if without != module && !dry_run { + atomic_write_bytes_preserving_mode(&path, without.as_bytes()) + .await + .map_err(|e| format!("failed to restore {}: {e}", path.display()))?; + } + Ok(true) +} + // ── materialisation (service download) ───────────────────────── #[allow(clippy::too_many_arguments)] @@ -1012,9 +1384,12 @@ async fn materialise_patched_nupkg( /// Write `bytes` to `nupkg_path`, creating the uuid dir and its /// re-including `.gitignore`. Errors are strings. async fn write_nupkg(uuid_dir: &Path, nupkg_path: &Path, bytes: &[u8]) -> Result<(), String> { - tokio::fs::create_dir_all(uuid_dir) + // The folder of the patch, or the one below it where a hub has the + // package. + let folder = nupkg_path.parent().unwrap_or(uuid_dir); + tokio::fs::create_dir_all(folder) .await - .map_err(|e| format!("cannot create {}: {e}", uuid_dir.display()))?; + .map_err(|e| format!("cannot create {}: {e}", folder.display()))?; atomic_write_artifact(nupkg_path, bytes) .await .map_err(|e| format!("cannot write {}: {e}", nupkg_path.display()))?; @@ -1046,10 +1421,10 @@ async fn keep_nupkg_committable( nupkg_path: &Path, warnings: &mut Vec, ) -> Result<(), VendorOutcome> { - let leaf = nupkg_path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); + // From the uuid dir, with `/` between its parts: the file itself, or + // below `/` where a hub has the package. + let below = nupkg_path.strip_prefix(uuid_dir).unwrap_or(nupkg_path); + let leaf = below.to_string_lossy().replace('\\', "/"); let shown = nupkg_path.display().to_string(); match super::npm_dir::gitignore_probe(uuid_dir, &[leaf, ".gitignore".to_string()]).await { Ok(Some(rules)) => Err(refused( @@ -1588,6 +1963,8 @@ fn record_refusal(project_root: &Path, package: &OwnPackage, w: &WiringRecord) - ) }) } + BAZEL_WIRING_KIND => (w.file != MODULE_FILE) + .then(|| format!("names a file that is not the root {MODULE_FILE}")), LOCK_WIRING_KIND => { if !is_safe_multi_segment(&w.file) { return unsafe_path(); @@ -2017,6 +2394,13 @@ struct LockFile { text: String, } +/// The root-relative path and the text of each of `locks`. +fn texts(locks: &[LockFile]) -> impl Iterator { + locks + .iter() + .map(|lock| (lock.rel.as_str(), lock.text.as_str())) +} + /// Put back the locks a failed vendor already re-pinned. async fn unwind_locks(written: &[(&LockFile, &str)]) { for (lock, original) in written { @@ -4052,7 +4436,6 @@ mod tests { tokio::fs::metadata(p).await.unwrap().permissions().mode() & 0o7777 } - #[cfg(unix)] fn preexisting_cfg() -> &'static str { "\n\ \n\ @@ -6858,4 +7241,417 @@ mod tests { assert!(root.join(format!(".socket/vendor/nuget/{UUID}")).exists()); } } + + // ── a package of a rules_csharp hub ───────────────────────────────── + + /// The three files vendored mode edits for a package of a hub. + fn hub_files(root: &Path) -> [Vec; 3] { + [MODULE_FILE, "nuget.config", PACKAGES_LOCK] + .map(|file| std::fs::read(root.join(file)).unwrap()) + } + + /// In the root of a Bazel workspace whose one `nuget.from_lock` reads + /// the project's lock, the package lies where a feed of the hub has it, + /// `nuget.config` names that folder, and the block of `MODULE.bazel` + /// names the folder of the patch. A second run changes nothing, and + /// the revert puts the three files back byte for byte. + #[tokio::test] + #[serial_test::serial] + async fn a_package_of_a_hub_lies_where_its_feed_has_it_and_goes_to_the_byte() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + + let (result, entry, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + let folder = format!(".socket/vendor/nuget/{UUID}"); + let feed = format!("{folder}/newtonsoft.json/13.0.3"); + assert_eq!( + entry.artifact.path, + format!("{feed}/newtonsoft.json.13.0.3.nupkg") + ); + assert!(root.join(&entry.artifact.path).is_file()); + assert!( + !root.join(copy_rel()).exists(), + "no copy in the folder itself" + ); + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + let source = format!("", source_key()); + assert!(config.contains(&source), "{config}"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let feeds = format!( + " feeds = [\n \"file:{folder}\",\n \ + \"https://api.nuget.org/v3/index.json\",\n ],\n" + ); + assert!( + wired.starts_with(&module) && wired.contains(&feeds), + "{wired}" + ); + let last = entry.wiring.last().expect("records"); + assert_eq!( + (last.kind.as_str(), last.file.as_str(), last.key.as_deref()), + (BAZEL_WIRING_KIND, MODULE_FILE, Some(folder.as_str())) + ); + assert!(warnings.iter().all(|w| w.code != VENDOR_DECLINED)); + // The committed copy is what the ledger and the check hold it to. + let health = crate::vendor::check_vendored_artifact(root, &entry, &record).await; + assert_eq!(health, crate::vendor::ArtifactHealth::Healthy); + + // Once more: in sync, and no file is written again. + let vendored = hub_files(root); + let (again, rerecorded, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + assert!(warnings.iter().all(|w| w.code != VENDOR_DECLINED)); + assert_eq!(hub_files(root), vendored); + + // A record that names another file is not followed. + let mut tampered = entry.clone(); + tampered.wiring.last_mut().unwrap().file = "BUILD.bazel".to_string(); + let refused = revert_nuget(&tampered, root, false).await; + assert!(!refused.success, "{:?}", refused.warnings); + assert_eq!(hub_files(root), vendored); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!(hub_files(root), before); + assert!( + !root.join(&folder).exists(), + "the folder of the patch is gone" + ); + } + + /// Where the block cannot be shown to work, the package is declined + /// before anything is asked for or written. With the user's word it is + /// vendored as without Bazel, and a later run without that word leaves + /// it as it is. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_whose_block_cannot_be_shown_to_work_is_declined_unless_allowed() { + let unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + std::fs::remove_file(root.join(".bazelversion")).unwrap(); + let before = hub_files(root); + let candidates = [(PURL, UUID)]; + + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, VENDOR_DECLINED); + for part in [ + "no file of the checkout names the Bazel release that builds it", + "`--mode hosted`", + "`--allow-vendored-in-bazel`", + ] { + assert!(detail.contains(part), "{detail}"); + } + assert!(!root.join(".socket").exists()); + assert_eq!(hub_files(root), before); + let refused = bazel_refusals(root, &candidates).await; + assert_eq!(refused, [(PURL, VENDOR_DECLINED, detail)]); + assert!(service_preflight(PURL, root, &record).await.is_none()); + drop(unset); + + // The user's word: the package in the folder of the patch, and no + // block. + let allowed = crate::test_env::EnvGuard::set(ALLOW_IN_BAZEL_ENV, "1"); + assert!(bazel_refusals(root, &candidates).await.is_empty()); + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + assert_eq!(entry.artifact.path, copy_rel()); + assert!(entry.wiring.iter().all(|w| w.kind != BAZEL_WIRING_KIND)); + assert_eq!(hub_files(root)[0], before[0], "{MODULE_FILE} is untouched"); + drop(allowed); + + // Without it again: the package that is wired passes, in sync, and + // another patch of it is declined. + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + assert!(bazel_refusals(root, &candidates).await.is_empty()); + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + let other = [(PURL, "33333333-3333-4333-8333-333333333333")]; + assert_eq!(bazel_refusals(root, &other).await.len(), 1); + // And its revert takes it out as any vendored package. + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!(hub_files(root), before); + } + + /// A package that is wired for a hub follows the hub's tag on every + /// run: a source the user adds to `nuget.config` reaches the block. + /// Where the block can no longer be shown to work it is left as it is, + /// with a warning, and so is a block that was changed by hand. Beside + /// that one the revert changes nothing: the lock without its pin would + /// fail the Bazel build on the folder the block still names. With the + /// block deleted by hand, the revert takes out the rest. + #[tokio::test] + #[serial_test::serial] + async fn a_package_that_is_wired_for_a_hub_follows_its_tag() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + let (_, entry, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + let entry = entry.expect("a ledger entry"); + let rerun = || async { + let (result, entry, warnings) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + let warned = warnings.into_iter().filter(|w| w.code == VENDOR_DECLINED); + warned.map(|w| w.detail).collect::>() + }; + + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + let mirror = " \n"; + let with_mirror = config.replacen( + " \n\n\n"; + let (dir, blobs, installed, record) = fixture(true, Some(bare)).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let before = hub_files(root); + + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let feeds = format!( + " feeds = [\n \"file:.socket/vendor/nuget/{UUID}\",\n \ + \"https://api.nuget.org/v3/index.json\",\n ],\n" + ); + assert!(wired.contains(&feeds), "{wired}"); + let vendored = hub_files(root); + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(again.success && rerecorded.is_none()); + assert_eq!(hub_files(root), vendored); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!(hub_files(root), before); + } + + /// A later patch of a hub's package takes the place of the earlier + /// one in the block, whose source the config keeps: the block names + /// the later folder alone, and goes with it. + #[tokio::test] + #[serial_test::serial] + async fn a_later_patch_of_a_hub_package_takes_the_place_of_the_earlier_one() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + let module = crate::bazel::nuget::tests::checkout(root); + let (first, _, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(first.success, "{:?}", first.error); + let earlier = format!("file:.socket/vendor/nuget/{UUID}\""); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + assert!(wired.contains(&earlier), "{wired}"); + + let mut later = record.clone(); + later.uuid = "33333333-3333-4333-8333-333333333333".to_string(); + let (second, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &later, false).await); + assert!(second.success, "{:?}", second.error); + let entry = entry.expect("a ledger entry"); + let wired = std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(); + let folder = format!("file:.socket/vendor/nuget/{}\"", later.uuid); + assert!( + wired.contains(&folder) && !wired.contains(&earlier), + "{wired}" + ); + // And a run of it again leaves the block as it is. + let (again, rerecorded, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &later, false).await); + assert!(again.success && rerecorded.is_none()); + assert_eq!( + std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(), + wired + ); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert_eq!( + std::fs::read_to_string(root.join(MODULE_FILE)).unwrap(), + module, + "the block goes with the later folder" + ); + } + + /// A hub asks its feeds for the version as the lock spells it. A lock + /// that spells it otherwise than NuGet writes it is declined: the hub + /// would not find the package in the folder of the patch. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_lock_that_spells_the_version_otherwise_is_declined() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + crate::bazel::nuget::tests::checkout(root); + let lock = std::fs::read_to_string(root.join(PACKAGES_LOCK)).unwrap(); + let spelled = lock.replace("\"resolved\": \"13.0.3\"", "\"resolved\": \"13.0.3.0\""); + assert_ne!(spelled, lock); + std::fs::write(root.join(PACKAGES_LOCK), spelled).unwrap(); + let before = hub_files(root); + + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, VENDOR_DECLINED); + for part in [ + "packages.lock.json names Newtonsoft.Json 13.0.3.0", + "holds 13.0.3", + "`--mode hosted`", + ] { + assert!(detail.contains(part), "{detail}"); + } + assert!(!root.join(".socket").exists()); + assert_eq!(hub_files(root), before); + assert!(service_preflight(PURL, root, &record).await.is_none()); + // What every way in is told before it fetches anything. + let refused = bazel_refusals(root, &[(PURL, UUID)]).await; + assert_eq!(refused, [(PURL, VENDOR_DECLINED, detail)]); + } + + /// The package of a hub lies below `/` in the folder + /// of the patch, and that is the path git is asked about. The folder's + /// own `.gitignore` reaches over every rule above it, so only an + /// ignore file below it can drop the package: it is then refused, and + /// nothing stays written. + #[tokio::test] + #[serial_test::serial] + async fn a_package_of_a_hub_that_git_would_not_commit_is_refused() { + use crate::vendor::test_support::git_project; + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let (dir, blobs, installed, record) = fixture(true, Some(preexisting_cfg())).await; + let root = dir.path(); + if git_project(root, "newtonsoft.json/\n").is_none() { + return; + } + crate::bazel::nuget::tests::checkout(root); + let below = root.join(format!(".socket/vendor/nuget/{UUID}/newtonsoft.json")); + std::fs::create_dir_all(&below).unwrap(); + std::fs::write(below.join(".gitignore"), "*.nupkg\n").unwrap(); + let before = hub_files(root); + let (code, detail) = + unwrap_refused(run_vendor(root, &blobs, &installed, &record, false).await); + assert_eq!(code, "vendor_artifact_gitignored", "{detail}"); + assert!(detail.contains("*.nupkg"), "{detail}"); + assert_eq!(hub_files(root), before); + assert!( + !root.join(".socket/vendor").exists(), + "nothing stays written" + ); + + // Without that file the rule of the project is no bar: the folder's + // own `.gitignore` re-includes what lies below it. + let (result, entry, _) = + unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + assert!(result.success && entry.is_some(), "{:?}", result.error); + } } diff --git a/crates/socket-patch-core/src/vendor/path.rs b/crates/socket-patch-core/src/vendor/path.rs index c05fd8f07..bf66d7e7d 100644 --- a/crates/socket-patch-core/src/vendor/path.rs +++ b/crates/socket-patch-core/src/vendor/path.rs @@ -26,7 +26,7 @@ //! | composer | `/@/` | //! | gem | `-/` | //! | pypi | `--.whl` (PEP 427); server sdist: `-.tar.gz` / `.tgz` / `.zip` | -//! | nuget | `..nupkg` | +//! | nuget | `..nupkg`; for a rules_csharp hub: `//..nupkg` | //! | maven | `///-.jar` | use std::path::{Path, PathBuf}; @@ -488,9 +488,13 @@ pub(crate) fn leaf_to_purl(eco: &str, leaf: &str) -> Option { Some(format!("pkg:pypi/{dist}@{version}")) } "nuget" => { - let stem = leaf.strip_suffix(".nupkg")?; + // The file itself, or the same below `//`, + // where a rules_csharp hub has the package. + let (below, file) = leaf.rsplit_once('/').unwrap_or(("", leaf)); + let stem = file.strip_suffix(".nupkg")?; let (name, version) = split_nuget_leaf(stem)?; - if !is_safe_single_segment(version) { + let hub = below == format!("{name}/{version}"); + if !is_safe_single_segment(version) || !(below.is_empty() || hub) { return None; } Some(format!("pkg:nuget/{name}@{version}")) @@ -1069,6 +1073,20 @@ mod tests { // nested leaf whose recovered version would span a `/`. assert!(leaf_to_purl("nuget", ".1.2.3.nupkg").is_none()); assert!(leaf_to_purl("nuget", "foo.1.0/evil.nupkg").is_none()); + // Below `//`, where a rules_csharp hub has the + // package, and below no other directory. + assert_eq!( + leaf_to_purl("nuget", "foo.bar/1.0.0-rc1/foo.bar.1.0.0-rc1.nupkg").as_deref(), + Some("pkg:nuget/foo.bar@1.0.0-rc1") + ); + for elsewhere in [ + "foo.bar/2.0.0/foo.bar.1.0.0.nupkg", + "other/1.0.0/foo.bar.1.0.0.nupkg", + "a/foo.bar/1.0.0/foo.bar.1.0.0.nupkg", + "1.0.0/foo.bar.1.0.0.nupkg", + ] { + assert!(leaf_to_purl("nuget", elsewhere).is_none(), "{elsewhere}"); + } // maven: an empty group component, and an unsafe group (colon). assert!(leaf_to_purl("maven", "/app/1.0.0/app-1.0.0.jar").is_none()); assert!(leaf_to_purl("maven", "a:b/x/1.0/x-1.0.jar").is_none()); diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 437316fc8..3c7a85e0d 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -23,10 +23,14 @@ //! as a skip); //! 6. a Maven version no module of the build selects //! (`vendor_maven_version_not_selected`, a skip too); -//! 7. a Composer project in a Bazel workspace -//! (`vendor_composer_bazel_workspace`), unless the user allowed it -//! ([`ALLOW_IN_BAZEL_ENV`]) or the lock already names the patch's copy -//! ([`bazel_workspace_refusals`]); +//! 7. what rests on the Bazel workspace of the project +//! ([`bazel_workspace_refusals`]), unless the user allowed it +//! ([`ALLOW_IN_BAZEL_ENV`]): a Composer project in one +//! (`vendor_composer_bazel_workspace`), unless the lock already names +//! the patch's copy; and a NuGet package of a project whose lock a +//! rules_csharp hub reads, where the block that makes the hub take the +//! copy cannot be shown to work (`vendor_nuget_bazel_workspace`), unless +//! `nuget.config` already names the patch's folder. //! 8. a Maven jar that only a rules_jvm_external hub of a Bazel workspace //! builds and whose entry cannot be written there (the `maven_bazel_*` //! codes of [`crate::bazel::maven`]), from the same dispatch. @@ -43,7 +47,9 @@ use crate::crawlers::Ecosystem; use crate::patch::redirect::upstream::HostedPin; use crate::utils::purl_key::PurlKey; use crate::vendor::state::{lookup_entry, VendorEntry}; -use crate::vendor::{bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock}; +use crate::vendor::{ + bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, nuget_feed, vlt_lock, +}; /// The vendor ledger as the refusals consume it: the caller's own load /// outcome, so an UNREADABLE ledger is a refusal the run can report @@ -105,10 +111,6 @@ fn is_cargo(purl: &str) -> bool { Ecosystem::from_purl(purl) == Some(Ecosystem::Cargo) } -fn is_composer(purl: &str) -> bool { - Ecosystem::from_purl(purl) == Some(Ecosystem::Composer) -} - /// The refusals of vendored mode that rest on the Bazel workspace of the /// project at `project_root`, for `candidates` (`(purl, uuid)` pairs): /// each refused purl with its code and detail. None when the user allowed @@ -116,8 +118,9 @@ fn is_composer(purl: &str) -> bool { /// vendored entry point takes this one answer: [`vendor_refusals`] hands it /// to a scan, a `get` and a `vendor`, and the eject of hosted pins asks it /// before it fetches or restores anything. A refusal of this kind for -/// another ecosystem belongs here. Composer's is the one the user's word -/// lifts. Maven's is not lifted: vendored mode patches a pinned +/// another ecosystem belongs here: Composer's, NuGet's and Maven's are the +/// three today. Composer's and NuGet's are the ones the user's word lifts. +/// Maven's is not lifted: vendored mode patches a pinned /// rules_jvm_external hub, and where the hub is the only build of a patch /// and no entry can be shown to work for it /// ([`super::maven_repo::hub_refusals`]), there is nothing else to write. @@ -125,14 +128,13 @@ pub async fn bazel_workspace_refusals<'a>( project_root: &Path, candidates: &[(&'a str, &str)], ) -> Vec<(&'a str, &'static str, String)> { - let composer: Vec<(&str, &str)> = candidates - .iter() - .filter(|(purl, _)| is_composer(purl)) - .copied() - .collect(); - let mut refused = composer_lock::bazel::refusals(project_root, &composer).await; - let maven = |(purl, _): &&(&str, &str)| Ecosystem::from_purl(purl) == Some(Ecosystem::Maven); - let maven: Vec<(&'a str, &str)> = candidates.iter().filter(maven).copied().collect(); + let of = |ecosystem: Ecosystem| -> Vec<(&'a str, &str)> { + let named = |(purl, _): &&(&str, &str)| Ecosystem::from_purl(purl) == Some(ecosystem); + candidates.iter().filter(named).copied().collect() + }; + let mut refused = composer_lock::bazel::refusals(project_root, &of(Ecosystem::Composer)).await; + refused.extend(nuget_feed::bazel_refusals(project_root, &of(Ecosystem::Nuget)).await); + let maven = of(Ecosystem::Maven); if !maven.is_empty() { let owned = |(purl, uuid): &(&str, &str)| (purl.to_string(), uuid.to_string()); let owned: Vec<(String, String)> = maven.iter().map(owned).collect(); @@ -503,6 +505,30 @@ mod tests { assert!(!refusal_is_benign(got[one].code)); } + /// A NuGet package of a project whose lock a rules_csharp hub reads, + /// in a checkout that names no Bazel release: refused with NuGet's own + /// code, beside no candidate of another ecosystem. Where no tag reads + /// the lock nothing is. + #[tokio::test] + #[serial_test::serial] + async fn nuget_candidates_of_a_hub_without_its_block_are_refused() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let tmp = tempfile::tempdir().unwrap(); + let (one, other) = ("pkg:nuget/Lib@1.0.0", "pkg:cargo/lib@1.0.0"); + let pairs = [(one, UUID), (other, OTHER_UUID)]; + let empty = HashMap::new(); + std::fs::write(tmp.path().join("packages.lock.json"), "{}").unwrap(); + let module = crate::bazel::nuget::tests::checkout(tmp.path()); + std::fs::remove_file(tmp.path().join(".bazelversion")).unwrap(); + let got = run(tmp.path(), &pairs, Ok(&empty)).await; + assert_eq!(got.keys().collect::>(), [one]); + assert_eq!(got[one].code, "vendor_nuget_bazel_workspace"); + assert!(!refusal_is_benign(got[one].code)); + let elsewhere = module.replace("//:packages", "//api:packages"); + std::fs::write(tmp.path().join("MODULE.bazel"), elsewhere).unwrap(); + assert!(run(tmp.path(), &pairs, Ok(&empty)).await.is_empty()); + } + mod gem { use super::*; diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d..925f36f68 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -1297,6 +1297,7 @@ async fn wiring_file_refusal(rec: &WiringRecord, project_root: &Path) -> Option< one_of(&crate::patch::redirect::NUGET_CONFIG_FILE_NAMES) } "nuget_lock_entry" => super::nuget_feed::ledger_lock_file_refusal(project_root, file), + super::nuget_feed::BAZEL_WIRING_KIND => one_of(&[crate::bazel::nuget::FILE]), "maven_pom_repository" => one_of(&[super::jvm::layout::POM_FILE]), // The JVM kinds: `jvm::apply` checks each record's path against its // kind before it reads anything. Any other kind is a newer build's. @@ -2809,6 +2810,7 @@ mod tests { ("nuget", "nuget_config_source", "NuGet.Config"), ("nuget", "nuget_lock_entry", "src/App/packages.lock.json"), ("nuget", "nuget_lock_entry", "packages.App.lock.json"), + ("nuget", "nuget_bazel_feed", "MODULE.bazel"), ("maven", "maven_pom_repository", "pom.xml"), ]; for (ecosystem, kind, file) in passes { @@ -2844,6 +2846,8 @@ mod tests { ("nuget", "nuget_config_source", "Directory.Build.props"), ("nuget", "nuget_lock_entry", "tools/build.json"), ("nuget", "nuget_lock_entry", ".config/packages.lock.json"), + ("nuget", "nuget_bazel_feed", "BUILD.bazel"), + ("nuget", "nuget_bazel_feed", "svc/MODULE.bazel"), ("maven", "maven_pom_repository", "module/pom.xml"), ]; for (ecosystem, kind, file) in refused { diff --git a/crates/socket-patch-core/src/vex/discover/nuget.rs b/crates/socket-patch-core/src/vex/discover/nuget.rs index b495b8d16..b082f6165 100644 --- a/crates/socket-patch-core/src/vex/discover/nuget.rs +++ b/crates/socket-patch-core/src/vex/discover/nuget.rs @@ -22,11 +22,12 @@ //! | writer | `value` | mode | version from | pin | //! |---|---|---|---|---| //! | `patch::redirect::rewrite_nuget` (`scan --mode hosted`) | `https://patch.socket.dev/patch-registry/nuget///index.json` ([`DiscoverCtx::hosted_uuid`], must equal the key's uuid) | Hosted | every `packages.lock.json` entry for the id (`dependencies...resolved`, id case-insensitive) | its `contentHash` | -//! | `vendor::nuget_feed` (`vendor`, `scan --mode vendored`) | `.socket/vendor/nuget/` ([`vendor_uuid_dir`], must be the nuget dir of the key's uuid) | Vendored | the feed's single `..nupkg` (the patched version), else every locked `resolved` as above | `contentHash` when locked | +//! | `vendor::nuget_feed` (`vendor`, `scan --mode vendored`) | `.socket/vendor/nuget/` ([`vendor_uuid_dir`], must be the nuget dir of the key's uuid), or `/` below it for a package of a rules_csharp hub | Vendored | the feed's single `..nupkg` (the patched version), else every locked `resolved` as above | `contentHash` when locked | //! //! The vendored artifact is `.socket/vendor/nuget//. //! .nupkg` ([`nupkg_leaf`], the writer's own stable leaf: -//! lowercased id, version through the SAME `normalize_nuget_version`) — the exact +//! lowercased id, version through the SAME `normalize_nuget_version`), in +//! the directory the source's value names — the exact //! `VendorArtifact::path` the ledger records, which the CLI's liveness check //! compares verbatim. The feed dir is listed for the patched version (one //! nupkg for the mapped id; its name is split at the KNOWN id, not guessed @@ -597,7 +598,15 @@ async fn emit( value, id, } = src; - if let Some((eco, dir_uuid)) = vendor_uuid_dir(value) { + // The folder of a patch, or the one below it where a rules_csharp hub + // has the package (`/`), which vendored mode names + // for a package of such a hub. + let folder = vendor_uuid_dir(value).map(|(eco, uuid)| (eco, uuid, String::new())); + let folder = folder.or_else(|| { + let below = vendor_ref(value)?; + Some((below.eco, below.uuid, format!("{}/", below.leaf))) + }); + if let Some((eco, dir_uuid, below)) = folder { if eco != "nuget" || dir_uuid != *uuid { // The value is this project's vendor tree, so the key names a // Socket patch too — rejected (discover rule 11). @@ -612,7 +621,7 @@ async fn emit( ); return; } - emit_vendored(ctx, cfg_rel, src, lock, out).await; + emit_vendored(ctx, cfg_rel, src, &below, lock, out).await; return; } match ctx.hosted_uuid(value) { @@ -735,10 +744,13 @@ fn emit_hosted( /// lock's entries at it, if any — and a lock entry at any other version is /// reported through [`other_versions`], never as a ref of its own (no /// artifact serves it). Without one, the lock's versions are the refs. +/// `below` is where the feed lies under the folder of the patch: empty, +/// or a path with a `/` at its end. async fn emit_vendored( ctx: &DiscoverCtx<'_>, cfg_rel: &str, src: &SocketSource, + below: &str, lock: &Lock, out: &mut Discovery, ) { @@ -753,7 +765,7 @@ async fn emit_vendored( let serves = format!("the vendored feed {VENDOR_DIR}/nuget/{}", src.uuid); // (purl version, artifact leaf, integrity, other versions) let mut rows: Vec<(String, String, Option, Option)> = Vec::new(); - let leaves = feed_leaves(ctx, &src.uuid, &id_lower).await; + let leaves = feed_leaves(ctx, &src.uuid, below, &id_lower).await; if let [(leaf, version)] = leaves.as_slice() { let norm = normalize_nuget_version(version); match locks { @@ -803,7 +815,7 @@ async fn emit_vendored( return; } for (version, leaf, integrity, other) in rows { - let artifact = format!("{VENDOR_DIR}/nuget/{}/{leaf}", src.uuid); + let artifact = format!("{VENDOR_DIR}/nuget/{}/{below}{leaf}", src.uuid); let (Some(purl), Some(vref)) = ( simple_purl("nuget", &src.id, &version), vendor_ref(&artifact), @@ -828,16 +840,23 @@ async fn emit_vendored( } /// `(leaf, version)` of every regular `..nupkg` in the vendored -/// feed dir (id compared case-insensitively, version digit-leading and in -/// NuGet's version charset), sorted. -async fn feed_leaves(ctx: &DiscoverCtx<'_>, uuid: &str, id_lower: &str) -> Vec<(String, String)> { - // `uuid` passed the canonical grammar (socket_patch_name_uuid), so the - // join cannot escape `.socket/vendor/nuget/`. +/// feed dir, `below` under the folder of the patch (id compared +/// case-insensitively, version digit-leading and in NuGet's version +/// charset), sorted. +async fn feed_leaves( + ctx: &DiscoverCtx<'_>, + uuid: &str, + below: &str, + id_lower: &str, +) -> Vec<(String, String)> { + // `uuid` passed the canonical grammar (socket_patch_name_uuid) and + // `below` is a traversal-safe path ([`vendor_ref`]), so the join cannot + // escape `.socket/vendor/nuget/`. // The vendored feed is a dir of packages: only a disk has one. let Some(root) = ctx.disk_root() else { return Vec::new(); }; - let dir = root.join(VENDOR_DIR).join("nuget").join(uuid); + let dir = root.join(VENDOR_DIR).join("nuget").join(uuid).join(below); let Ok(mut entries) = tokio::fs::read_dir(&dir).await else { return Vec::new(); }; @@ -1065,6 +1084,37 @@ mod tests { assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); } + /// The folder a package of a rules_csharp hub lies in, below the folder + /// of the patch: the ref names the nupkg there. The folder of another + /// patch is rejected, as for the folder itself. + #[tokio::test] + async fn vendored_below_the_folder_of_the_patch_for_a_hub() { + let below = format!("{}/newtonsoft.json/13.0.3", feed(UUID_A)); + let p = Project::new(); + let wired = |value: &str| { + config( + &[ORG, (&socket_key(UUID_A), value)], + &[("nuget.org", "*"), (&socket_key(UUID_A), "Newtonsoft.Json")], + ) + }; + p.write("nuget.config", wired(&below)); + let entries = [("net8.0", "Newtonsoft.Json", "13.0.3", Some(HASH))]; + p.write("packages.lock.json", lock(&entries)); + let nupkg = format!("{below}/newtonsoft.json.13.0.3.nupkg"); + p.write(&nupkg, "PK"); + let out = run(&p).await; + assert_eq!(out.refs.len(), 1, "{:?}", out.diagnostics); + assert_eq!(out.refs[0].artifact_rel.as_deref(), Some(nupkg.as_str())); + assert_eq!(out.refs[0].mode, WiringMode::Vendored); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + let other = format!("{}/newtonsoft.json/13.0.3", feed(UUID_B)); + p.write("nuget.config", wired(&other)); + let out = run(&p).await; + assert!(out.refs.is_empty(), "{:?}", out.refs); + assert_eq!(out.diagnostics[0].code, DIAG_REF_INVALID); + } + /// The leaf uses the writer's version normalization (4th zero segment /// dropped, lowercased pre-release) while the purl keeps the lock's /// resolved spelling. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1388da628..89ed5fcec 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -26,7 +26,7 @@ below is about what a package manager installs and builds. | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | -| NuGet (`nuget`) | ✅ in-place patching deletes `.nupkg.metadata` and advises on the `.nupkg.sha512` tamper-evidence sidecar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) | ✅ committed folder feed (its `.gitignore` re-includes the nupkg against `*.nupkg` rules) + `packageSourceMapping` + `packages.lock.json` contentHash pin | ✅ `nuget.config` source + source-mapping, `packages.lock.json` contentHash rewrite. See the locked-mode note in [Maven & NuGet caveats](#maven--nuget-caveats). In a Bazel workspace whose rules_csharp `nuget.from_lock` hub would not take the pin (it reads the lock and not that `nuget.config`, or has the package from a lock the run does not re-pin), nothing is written (`redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`); see [Bazel workspaces: NuGet](#bazel-workspaces-nuget) | +| NuGet (`nuget`) | ✅ in-place patching deletes `.nupkg.metadata` and advises on the `.nupkg.sha512` tamper-evidence sidecar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) | ✅ committed folder feed (its `.gitignore` re-includes the nupkg against `*.nupkg` rules) + `packageSourceMapping` + `packages.lock.json` contentHash pin. In a Bazel workspace whose rules_csharp `nuget.from_lock` reads the project's lock, also a block in the root `MODULE.bazel`, or the package is declined (`vendor_nuget_bazel_workspace`); see [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) | ✅ `nuget.config` source + source-mapping, `packages.lock.json` contentHash rewrite. See the locked-mode note in [Maven & NuGet caveats](#maven--nuget-caveats). In a Bazel workspace whose rules_csharp `nuget.from_lock` hub would not take the pin (it reads the lock and not that `nuget.config`, or has the package from a lock the run does not re-pin), nothing is written (`redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`); see [Bazel workspaces: NuGet](#bazel-workspaces-nuget) | | Composer (`composer`) | ✅ in place (`vendor/`) | ✅ `composer.lock` `dist: path` rewrite; declined in a Bazel workspace, see [Bazel workspaces: Composer](#bazel-workspaces-composer) | ✅ `composer.lock` dist url + shasum rewrite; the entry's `source` and `dist.mirrors` are removed. See [composer-compatibility.md](testing/composer-compatibility.md) | | Deno (`deno`) | ✅ in place (the only mode for Deno) | ❌ refused (`vendor_unsupported_ecosystem`) | ❌ not supported | @@ -1755,6 +1755,166 @@ name. Nothing is evaluated and no Bazel is run. as it does without Bazel. - A pin that an earlier release wrote in such a workspace stays in the two files: `socket-patch rollback` takes it out, and the attribute makes the build read it. +- **A package of the project is vendored.** The block of vendored mode (below) is the hub's + last tag, and its `feeds` stand in the place of the config's sources. Hosted mode then + writes nothing for another package of the project and says so: vendor that package too, or + take the vendored ones out and run the command again. + +### Vendored mode under a rules_csharp hub + +Vendored mode commits the patched package under `.socket/vendor/nuget//`, names that +folder as a package source in `nuget.config`, and re-pins the lock. NuGet takes a folder as a +source. The hub reads the same line as the URL of a feed: after a vendored run that exited 0, +the next `bazel build` crashed Bazel 9.3.2 in the module extension and failed on 8.8.2 and +7.7.2 with `Bad URL: .socket/vendor/nuget/...`. + +So in the root of a Bazel workspace whose `nuget.from_lock` reads the project's lock, `scan +--mode vendored`, `get --mode vendored` and `vendor` write three things differently: + +- The package lies where a feed of the hub has one: + `.socket/vendor/nuget////..nupkg`, with the id in lower case. + It is the one copy. +- `nuget.config` names that directory, `.socket/vendor/nuget///`, so + `dotnet restore` outside Bazel takes the same file. +- One block is appended to the root `MODULE.bazel`, after one blank line: + +```starlark +# >>> socket-patch: NuGet patches for Bazel (managed block: socket-patch writes and removes it) >>> +socket_patch_nuget = use_extension("@rules_csharp//csharp:extensions.bzl", "nuget") +socket_patch_nuget.from_lock( + feeds = [ + "file:.socket/vendor/nuget/", + "https://api.nuget.org/v3/index.json", + ], + packages_lock_json = "//:packages.lock.json", +) +# <<< socket-patch <<< +``` + +The block is a second `nuget.from_lock` of the same hub, after every tag of yours, so its +`feeds` are the ones the hub asks: first the folder of each vendored patch, which Bazel reads +from the root of the workspace, then the sources the hub had without the block (those of your +tag's `nuget_config`, or else its `feeds`). It carries the label of your `use_extension`, your +`packages_lock_json`, and your hub's `name` where the tag gives one. No call of yours is +edited, and nothing is written to `.bazelrc` or `.bazelignore`: the folder holds no BUILD +file, and `bazel query //...` lists what it listed. + +The build then takes the committed package and asks no host for it: with the patch host +unreachable, from a new output base, with the package in no repository cache (rules_csharp +0.5.0 on Bazel 9.3.2, 8.8.2 and 7.7.2). A committed package that is changed or missing fails +the build, over the lock's `contentHash` or the sha256 that `MODULE.bazel.lock` records; it is +never replaced by the upstream package. The one exception is a machine whose repository cache +holds the package under the sha256 that `MODULE.bazel.lock` records: Bazel builds the cached +file there, which is the patched one, and does not read the folder. `vendor --check` catches a +changed or missing copy on every machine. Commit `.socket/vendor`, `nuget.config`, the lock +and `MODULE.bazel` together. + +`vendor --revert`, `rollback` and `remove` take the folder of a patch out of the block, and +the block goes with its last folder: `MODULE.bazel` is then byte for byte what it was. With +one vendored patch every other file is too. With several, `nuget.config` can keep the source +mapping that the first of them created, as it does without Bazel: `vendor --revert` and +`rollback` leave it, and so does `remove` in the order the patches were vendored. + +A block that was changed by hand is not taken out, and then nothing is: the three commands +fail (`revert_failed`, `vendor_revert_failed`), name the line of the block and leave every +file as it is. With the lock restored beside such a block, the hub would hold the committed +package to the upstream `contentHash` and the build would fail. Put the block back as +socket-patch wrote it, or delete it, and run the command again. + +A `nuget.config` that was written anew since the vendored run, and still names the folder, is +left as it is with a warning (`vendor_lock_entry_drifted`), as without Bazel. Its lock pin and +its package stay with it, and so does the block: the hub takes the package through the block +alone, and `dotnet restore` and the Bazel build both keep the patched package. + +`vendor --check`, `list` and `vex` see the package as any vendored NuGet package. A later +vendored run keeps the block in step with your tag: a source you add to `nuget.config` +reaches the hub once socket-patch has run again. A later patch of the same package takes the +place of the earlier one's folder in the block. + +**Where it declines.** The block is written only where the checkout shows that it works. +Elsewhere every command that would vendor the package reports it `failed` with +`vendor_nuget_bazel_workspace` and exits 1; it downloads nothing and writes nothing, and a +package that is pinned hosted stays pinned. With `--dry-run`, `scan` and `get` list the package +and exit 0. The message names the reason, with the file and line where there is one, and +`--mode hosted`. The reasons: + +- The project is not the root of its Bazel workspace, or another Bazel workspace lies above + it in the checkout. +- The workspace has more than one `nuget.from_lock`, or socket-patch cannot read with + certainty which tags it has. +- The tag is not a call of its own with every argument written out, or it is called on a + `use_extension` that is isolated or a dev dependency. +- The tag has `local_package_dirs`: the hub asks those directories before every feed, and + with the upstream package in one the build fails on the re-pinned lock. Or it has `netrc` + or `auth_patterns`, which the block was not built with. +- Its `nuget_config` cannot be read, or a package source cannot stand in a string. +- The tag has `feeds` and names a `nuget_config` that has no package source. Vendored mode + names its folder in that file, and rules_csharp takes the sources of a `nuget_config` in + place of `feeds`: a later run would write the block without those feeds. Name the feeds in + the file. +- `MODULE.bazel.lock` does not show that Bazel selected rules_csharp 0.5.0. Build once, so + that Bazel writes its lock. +- The checkout does not name Bazel 9.3.2, 8.8.2 or 7.7.2 in `.bazelversion` or `.bazeliskrc`. + The block rests on Bazel reading a relative `file:` URL from the root of the workspace, + which Bazel does not document, and Bazel 9.1.0 has other code for such a URL than its + neighbours. So no other release is taken, and a checkout that names none is declined. +- An rc file of the checkout names `--repository_disable_download` or `--vendor_dir`, or a + directory at the root is a vendor directory of Bazel's (it holds `VENDOR.bazel`). +- An rc file of the checkout names a remote downloader (`--experimental_remote_downloader`), + which takes no `file:` feed. By Bazel's source, 7.7.2 hands it the folder, which it cannot + read, and 8.8.2 and 9.3.2 download every package of the lock without it. That is read and + not built. +- `MODULE.bazel` is a symbolic link, or its block was changed by hand. +- A lock spells the package's version otherwise than NuGet writes it (`1.2.3.0` for `1.2.3`). + The hub asks its feeds for the version as the lock spells it, and the folder of the patch + holds the version as `dotnet restore` writes it. Run `dotnet restore`, which rewrites the + lock. + +`--allow-vendored-in-bazel` (or `SOCKET_ALLOW_VENDORED_IN_BAZEL=1`) lifts the decline. The +package is then vendored as in a project without Bazel, which the hub does not take: that is +for a project whose lock a tag names and which Bazel does not build. A package that was +vendored that way, or by an earlier release, stays as it is on later runs, without a block; +`vendor --revert` and a new vendored run give it the layout above. + +Nothing changes for a NuGet project in no Bazel workspace, and for one whose locks no +`nuget.from_lock` reads: the package lies in the folder of the patch, and no line of +`MODULE.bazel` is written. + +**Limits.** + +- The block works in the root module only. In a workspace that depends on this one as a + module, Bazel reads the folder from the other root and the build fails. Hosted mode works + there. +- A module this workspace depends on may have a `nuget.from_lock` of its own with + `nuget_config` or `feeds`. The hub takes that tag after the block and drops the block's + feeds, and the build fails on the re-pinned lock. Hosted mode fails the same way there. +- A build with `--nofetch` in an output base that built the unpatched project, and a build + from a vendor directory made before the patch (`--vendor_dir` with `--nofetch`), build the + unpatched package and exit 0, with a warning of Bazel's. Such a build still rewrites + `MODULE.bazel.lock` to the pins of the patched package. Fetch again, or run `bazel vendor` + again. socket-patch sees `--vendor_dir` and `--repository_disable_download` in an rc file + and a vendor directory at the root of the workspace; it does not see `--nofetch`, in an rc + file or on a command line. +- A checkout that is deleted and made again at the same path under a running Bazel server + does not find the committed package until the server has restarted (`bazel shutdown`). The + build fails; it does not take the upstream package. +- `MODULE.bazel.lock` is stale right after the run, as after a hosted run: a build with + `--lockfile_mode=error` fails until a build that may update the lock has run and the lock + is committed. That build needs a registry for the other packages and no patch host. +- When the module extension runs, Bazel prints three `WARNING: Download from file:...` lines + for every other package of the lock, which the folder does not hold, for each vendored + patch. +- A source you add to `nuget.config` reaches the hub only after socket-patch has run again. +- An earlier release of socket-patch does not know the layout or the block. On a checkout + that this one vendored, its `vendor --check` fails (`vendor_check_failed`), its vendored + run writes a second copy of the package in the folder of the patch, and its + `vendor --revert` exits 0, restores the lock and leaves the block and the package: the Bazel + build then fails on the lock's `contentHash` (measured on Bazel 9.3.2). Undo with the + release that vendored. +- Measured on macOS arm64, with packages that carry no signature. + +[`e2e_bazel_build/nuget.rs`](../crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs) runs +the vendored flow on a real Bazel: `nuget::vendored_from_lock`. ## Gradle @@ -2155,7 +2315,7 @@ workspace and that Bazel does not build keeps the matrix at the top. | Go: gazelle `go_deps.from_file` over `go.mod` | Supported | Supported | Not supported | Supported with a hosted or vendored patch | | RubyGems: rules_ruby `ruby.bundle_fetch` over `Gemfile.lock` | Supported with no `gem_checksums` on the call, or with one written out in the call that does not name the gem or holds it to the patched gem's sha256 | Not supported | Not supported | Supported | | Cargo: rules_rust `crate.from_cargo` over `Cargo.lock` | Supported with `cargo_config` on the hub | Supported | Not supported | Supported with a hosted or vendored patch | -| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported with no restored copy on the machine | +| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Supported with the Bazel release in `.bazelversion` | Not supported | Supported with a vendored patch, or a hosted one and no restored copy on the machine | | Composer: a rule of your own that runs `composer install` from `composer.lock` | Supported | Not supported | Not supported | Supported with a hosted patch | | Maven: rules_jvm_external `maven.install` with a `lock_file` | Supported with Bazel 7.4.0 or later | Supported with Bazel 7.4.0 or later | Not supported | Supported with a hosted or vendored patch | @@ -2226,7 +2386,13 @@ What the table was tested with: `packages_lock_json = "//:packages.lock.json"` and `nuget_config = "//:nuget.config"`. `scan` finds a NuGet package only where a restore unpacked it (NuGet's global packages folder, a folder that an `obj/project.assets.json` records, or a `packages` folder): on a - machine where only Bazel ever ran it finds none, exits 0 and writes nothing. + machine where only Bazel ever ran it finds none, exits 0 and writes nothing. Vendored mode + was tested for that one tag, with the project at the root of the workspace, a + `.bazelversion` that names one of the three releases, and the `MODULE.bazel.lock` of a + build. It keeps a block in `MODULE.bazel` there, and where the checkout does not show that + the block works it declines the package and writes nothing: + [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) has the block, every + reason to decline and the limits. - **Composer**: no ruleset builds PHP, so the two shapes are rules a project writes itself: a repository rule that runs `composer install` from the committed `composer.lock` and takes the lock with `rctx.read`, and a genrule that runs it in a build action. Composer 2 and PHP @@ -2252,12 +2418,12 @@ fails until one that may has rewritten it. Known problems. In each of these a command exits 0 today and the next Bazel build fails: -- **Vendored mode for PyPI, RubyGems and NuGet.** The path of the committed copy means - nothing where Bazel runs: rules_python takes it for a package name, rules_ruby's - `bundle install` does not find it (`The path ... does not exist`), and rules_csharp reads - it as a URL (`Bad URL`, or a crash of Bazel 9.3.2). Run `socket-patch vendor --revert`, - then `socket-patch scan --mode hosted`. Of these builds a test of this repository runs the - PyPI one; the others were measured by hand on the three Bazel releases. +- **Vendored mode for PyPI and RubyGems.** The path of the committed copy means nothing + where Bazel runs: rules_python takes it for a package name, and rules_ruby's + `bundle install` does not find it (`The path ... does not exist`). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. Of these builds a + test of this repository runs the PyPI one; the other was measured by hand on the three + Bazel releases. - **Vendored mode for Composer, where its refusal is lifted or does not apply.** In a Bazel workspace vendored mode declines a Composer package: [Bazel workspaces: Composer](#bazel-workspaces-composer) has the refusal, what lifts it and @@ -2265,6 +2431,18 @@ Known problems. In each of these a command exits 0 today and the next Bazel buil rule runs in another directory fails the build with `Source path ... is not found`. Run `socket-patch vendor --revert`, then `socket-patch scan --mode hosted`. A test of this repository builds that failure on the three Bazel releases. +- **Vendored mode for NuGet, where its refusal is lifted or does not see the cause.** For a + package of a rules_csharp hub, vendored mode keeps a block in `MODULE.bazel` or declines: + [Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub) has both. With + `--allow-vendored-in-bazel`, and for a package that an earlier release vendored, the folder + stands in `nuget.config` alone, rules_csharp reads it as a URL, and the build fails + (`Bad URL`, or a crash of Bazel 9.3.2; measured on the three Bazel releases). Run + `socket-patch vendor --revert`, then `socket-patch scan --mode vendored` without the + switch, or `--mode hosted`. With the block, the build fails in two shapes that the checkout + does not show: a workspace that depends on this one as a module, and a module this one + depends on that has a `nuget.from_lock` with sources of its own. It also fails after the + `vendor --revert` of an earlier release, which leaves the block and the package beside the + restored lock: undo with the release that vendored. - **Hosted Cargo on a hub without `cargo_config`**, which is the hub as the rules_rust README shows it: the hub's cargo does not see the patch registry that `.cargo/config.toml` defines (`registry index was not found in any configuration`). Add @@ -2314,6 +2492,12 @@ In these a command exits 0 and the Bazel build passes on the unpatched package: - **Hosted NuGet on a machine without a restore.** `scan` reads no package out of `packages.lock.json`, so where only Bazel ever ran it finds none and writes nothing. Run it where `dotnet restore` has run. +- **Vendored NuGet in a build that may not fetch.** `--nofetch` in an output base that built + the unpatched project, and `--vendor_dir` with `--nofetch` over a vendor directory made + before the patch, build the package Bazel already has, with a warning of Bazel's. Fetch + again, or run `bazel vendor` again. Vendored mode declines where it sees a vendor directory + at the root of the workspace or `--vendor_dir` in an rc file; it does not see `--nofetch`, + in an rc file or on a command line. - **Go, when another Bazel module of the build requires a higher version** of the patched module: gazelle builds that version and drops the replacement. With `go_deps.config(check_direct_dependencies = "error")` and the module required directly in @@ -3726,7 +3910,10 @@ project's directory, or where the build finds the copy all the same: socket-patch checks none of these. The switch is not Composer's alone: it lets vendored mode write for any package it would decline because the project is in a Bazel workspace, where the -build may not find the vendored copy. The Composer refusal is the only such refusal today. +build may not find the vendored copy. It lifts two refusals today: this one, and the one for a +NuGet package of a rules_csharp hub whose block cannot be shown to work +(`vendor_nuget_bazel_workspace`, see +[Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)). `vendor --revert` is never declined. Neither is a package that is already vendored: where `composer.lock` already names the copy of the same patch, a vendored run leaves the lock as it @@ -4412,7 +4599,9 @@ Three more flows hold the document of `vex` to their patched build on the same r after a hosted scan: Cargo through rules_rust's `crate.from_cargo` with `cargo_config` (and after a vendored scan), Composer through a rule or a genrule of the project's own that runs `composer install` from the lock, and NuGet through rules_csharp's `nuget.from_lock` with -`nuget_config`, on a machine whose NuGet folder does not hold the package. For these, and +`nuget_config`, on a machine whose NuGet folder does not hold the package (and after a +vendored scan that kept its block in `MODULE.bazel`, on the machine that restored the +project as well: `vex` reads the committed package). For these, and for a Maven entry in `MODULE.bazel`, [Bazel workspaces: what is supported](#bazel-workspaces-what-is-supported) says what the document does not show. @@ -4440,6 +4629,12 @@ the build is broken): lists as `srcs`, so the path of the copy does not exist there. Read from its source and measured by hand, where the build fails; no test runs it yet, so the statement is left as it is. +- **Vendored mode for NuGet** beside `nuget.from_lock`, where the package is vendored and + `MODULE.bazel` does not hold its block: a run with `--allow-vendored-in-bazel`, a package + that an earlier release vendored, a block that was taken out by hand. `vex` reads + `nuget.config`, the lock and the committed package, and not the block. Measured for the + first two, where the build fails. With the block in place, a build that may not fetch + (`--nofetch`) can build the unpatched package while the statement says `not_affected`. - **A vendored package whose own files the hub does not read**, while the lock the hub does read still lists the registry's package: a uv or Poetry project vendored through `pyproject.toml` and its lock while `pip.parse` reads a requirements file exported before; diff --git a/scripts/loc-budget.json b/scripts/loc-budget.json index 2be5dcf83..9a77c9967 100644 --- a/scripts/loc-budget.json +++ b/scripts/loc-budget.json @@ -4,7 +4,7 @@ "paths": [ "crates/socket-patch-core/src/bazel/" ], - "max": 3917 + "max": 4343 }, "lock-readers": { "paths": [