diff --git a/.github/workflows/bazel-nuget.yml b/.github/workflows/bazel-nuget.yml index 135293751c..60ed07e9f7 100644 --- a/.github/workflows/bazel-nuget.yml +++ b/.github/workflows/bazel-nuget.yml @@ -3,8 +3,9 @@ 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`, for a tag that names no -# `nuget_config`, and agent mode for the copy of the package in NuGet's -# global packages folder, on each Bazel release below. +# `nuget_config`, agent mode for the copy of the package in NuGet's +# global packages folder, 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. # @@ -40,10 +41,15 @@ on: # files, the upstream restore of `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. + # (bazel/mod.rs, starlark.rs and 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). # patch/sidecars/nuget.rs is what agent mode does to a package in # NuGet's folder beyond its files. Last, the VEX code: `vex/` of the # core, the files of the `vex` command, and what `vex` makes of the tag @@ -78,9 +84,13 @@ 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/built.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-core/src/patch/sidecars/nuget.rs' @@ -92,8 +102,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 flows run - # through, and the toolchain files. A main push outside this list waits - # for the nightly run below. + # through, 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' @@ -109,9 +122,13 @@ 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/built.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-core/src/patch/sidecars/nuget.rs' @@ -120,6 +137,8 @@ on: - '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/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 1b72dfe936..7483cc9cce 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 | **Experimental** (no stability guarantee; see [Bazel workspaces (experimental)](#bazel-workspaces-experimental)). 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, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`, which a package meets until `packages` of the lock, or the section of the lock that holds the package, names a vendored copy: 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_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. For a project whose build does find the copy, or does not take its packages from that lock. 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: PyPI and RubyGems vendored mode" | +| `--allow-vendored-in-bazel` | — | `SOCKET_ALLOW_VENDORED_IN_BAZEL` | `false` | bool | **Experimental** (no stability guarantee; see [Bazel workspaces (experimental)](#bazel-workspaces-experimental)). 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, and the switch lifts each of those refusals. `vendor_composer_bazel_workspace`, which a package meets until `packages` of the lock, or the section of the lock that holds the package, names a vendored copy: 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_pypi_bazel_hub` and `vendor_gem_bazel_hub`: a rules_python or rules_ruby hub of the workspace reads the lock, which then names the patched copy by a path under `.socket/vendor`, and neither ruleset builds from that. `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. For a project whose build does find the copy, does not take its packages from that lock, 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", "Bazel workspaces: PyPI and RubyGems vendored mode" 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. @@ -562,11 +562,11 @@ A patch mirror is a caching proxy the operator runs in front of the patch server ### Bazel workspaces (experimental) -**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the block it keeps in `MODULE.bazel` and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. +**Experimental, and outside the semver policy.** What socket-patch does because a project is in a Bazel workspace is experimental in its first release. `--allow-vendored-in-bazel`, `--no-bazel` / `--vex-no-bazel`, `SOCKET_ALLOW_VENDORED_IN_BAZEL`, `SOCKET_VEX_NO_BAZEL`, `SOCKET_NO_BAZEL`, the codes that only a Bazel workspace can produce (`vendor_composer_bazel_workspace`, `vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`, `vendor_nuget_bazel_workspace`, `bazelignore_not_updated`, `vex_bazel_not_in_build`, `redirect_pnpm_bazel_workspace_hidden`, `redirect_cargo_bazel_config_unread`, `redirect_bazel_nuget_config_undeclared`, `redirect_bazel_nuget_lock_not_repinned`, `redirect_bazel_gem_checksums_pinned` and every `maven_bazel_*`), the lines socket-patch keeps in `.bazelignore`, the blocks it keeps in `MODULE.bazel` (the Maven entries, and the feeds of the NuGet packages vendored for a rules_csharp hub) and what vendored mode keeps for the jar of a hub (the directory `.socket/vendor/maven//` and the ledger entry of flavor `bazel`) may change or be removed in any release without a semver bump. The flags, variables and codes are marked **Experimental** where this document lists them, and so are its passages about a Bazel workspace; every other sentence of this document about a Bazel workspace, such as a reference to one of those codes, is under this section's rule as well. The one rule that is not experimental: none of it applies to a project in no Bazel workspace, whose runs are those of a release without it. * **The lookup.** A project is in a Bazel workspace when its directory, or one above it up to the root of its git checkout (a checkout whose `.git` belongs to a trusted owner; in no such checkout the project's own directory only), holds a regular file named `MODULE.bazel`, `REPO.bazel`, `WORKSPACE` or `WORKSPACE.bazel`. A link to a regular file counts, and a directory of such a name does not. The name is looked up as Bazel's own client looks it up, by whether a file answers to it: on a disk that folds case a regular file named `workspace` or `Module.bazel` counts, as it does for Bazel itself, and is read as the workspace file it answers for. `SOCKET_NO_BAZEL` is the way out for a checkout where such a file is no workspace. -* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the PyPI and RubyGems refusals beside a hub that reads the lock (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry unless the hub's build takes a routed lock (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. -* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. +* **The off switch (`SOCKET_NO_BAZEL`).** The lookup cannot tell whether Bazel builds the project: a service of a monorepo that Bazel never builds, and a checkout with a leftover workspace file, are in a Bazel workspace by it. A truthy `SOCKET_NO_BAZEL` (`1`/`true`/`yes`/`on`/`y`/`t`, in any case and with blanks around it: what `SOCKET_NO_CONFIG`, `SOCKET_NO_API_TOKEN` and `SOCKET_NO_UPDATE_CHECK` take) makes the lookup answer that there is none, on disk and for the in-memory engine, whose path selection then asks for no Bazel file and which judges none that a host hands over all the same. Every command then gives what it gives in the same checkout without the workspace file: the exit code, both streams and every written file. It switches off the Composer refusal (`vendor_composer_bazel_workspace`), the PyPI and RubyGems refusals beside a hub that reads the lock (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), the block and the refusal of vendored mode for a NuGet package of a rules_csharp hub (`vendor_nuget_bazel_workspace`: the package is vendored as in a checkout without the workspace file), the adding of `.bazelignore` lines, the hosted withholds for Cargo, NuGet, gems and pnpm (`redirect_cargo_bazel_config_unread`, `redirect_bazel_*`, `redirect_pnpm_bazel_workspace_hidden`), the rule that keeps a pnpm lock that a rules_js hub reads, or may read, off the route through a named registry unless the hub's build takes a routed lock (the lock is then routed where it is in the checkout without the workspace file), everything of Maven that rests on a hub (the entries hosted and vendored mode write to the block, the directory vendored mode keeps for a hub's jar, the jars of a hub as packages of a hosted scan, the sweep of stale entries and every `maven_bazel_*` refusal and warning), the `affected` statements of VEX (`vex_bazel_not_in_build`), and the allowance for the `BUILD.bazel` that cargo-bazel writes into a vendored crate. For a vendored Maven patch that means the run of a checkout no hub is in: beside a Maven or Gradle build the run vendors for that build alone, writes nothing for a hub, says nothing of one and names no file of one among those to commit, so a Bazel build that is there after all keeps the upstream jar of a patch the run reports as vendored; and in a checkout only Bazel builds the patch is refused for want of a build (`vendor_jvm_shape_unsupported`, `no_build_file`, with no word of an entry the block holds), and a hosted entry of the block is no pin that `vendor` ejects. The switch is for the whole run and for every program it starts, while whether Bazel builds a project is a fact of each project: a bare scan covers every project of a checkout, and with the switch set a project that Bazel does build loses each of these guards too, in a run that exits 0. Set it for runs in the directory of the project that Bazel does not build, not for a run over a checkout that also holds projects Bazel builds; there is no setting per project. Environment only: there is no flag (`vex --no-bazel` is the VEX step's own option), no repository file can set it, and a run that honours it prints nothing about it. A child process inherits it (it is not among the variables of the child-process paragraph below): it is the user's word about the checkout, no credential and no flag of one run, so a socket-patch that a spawned program starts in that checkout gives the same run. +* **What stays on with the switch.** Listing and undoing what an earlier run wrote for Bazel. The block of the root `MODULE.bazel` is still read by `list`, `vex`, `scan`, `vendor --check`, `repair`, `rollback`, `remove`, `vendor --revert` and a vendored takeover, by the reader of a run without the switch: an entry of hosted mode as a hosted pin, an entry of vendored mode as the wiring of the jar committed under `.socket/vendor/maven//`, and either one withheld from attestation when no pinned hub takes it any more, which `vendor --check` names for a vendored one. `rollback` and `remove` take a hosted entry out; they and `vendor --revert` take a vendored one out with its directory and its ledger entry, in the one commit that also holds the files of a Maven or Gradle build; `repair` puts back a lost directory of a patch that only a hub takes. Each of them says what it says without the switch. No entry is written or replaced: `vendor` leaves a hosted entry of the block as it is, and a hosted run takes over no patch that vendored mode keeps for a hub alone, which stays vendored (`redirect_takeover_kept_vendored`). Beside a Maven or Gradle build the hub's directory is a copy that `vendor` writes only without the switch: with it, one that was lost is named by `vendor --check` and stays lost until the undo takes its entry out. The `.bazelignore` pair of a copy directory that is gone is still removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan), with `bazelignore_not_updated` when the file cannot be written; no pair is added. The block that vendored mode keeps in `MODULE.bazel` for the NuGet packages of a rules_csharp hub is undone as without the switch: `vendor --revert`, `rollback` and `remove` take the folder of a patch out of it, and the block with its last folder; no folder is added. This is of the commands on disk: the in-memory engine writes no block and undoes none, and with the switch it is handed no `MODULE.bazel` to read one from. ### socket.yml patch policy (v5.0) @@ -1745,7 +1745,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). Where a rules_python hub of the project's Bazel workspace reads `requirements.txt` or a file it includes with `-r`, the project is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | -| 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 @@ -2238,7 +2238,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` | **Experimental** (Bazel workspaces). 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` | **Experimental** (Bazel workspaces). 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. | @@ -2551,6 +2551,7 @@ command's integration tests check its output. | `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` | **Experimental** (Bazel workspaces). 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` or `SOCKET_NO_BAZEL=1`, `vendor --revert`, and a package of a project that uses vendored mode already, by a release before this refusal or by a run with the flag: any package when `packages` of `composer.lock` names a copy under `.socket/vendor/composer`, and a package of `packages-dev` when `packages-dev` names one. Such a package is refused nothing: not a newer patch, not its first patch, not a `scan` or `get` with no `--mode`. A package of `packages` is still refused while only `packages-dev` names a copy, and so is a package the lock does not hold. So the first vendored path in a section a Bazel rule may install is what is refused, and the detail says so. That keeps a setup of an earlier release working and breaks no build: either no Bazel rule installs from that lock, or one does and its build already fails on a path in a section it installs, which one more path there does not change. The section matters because a rule may run `composer install --no-dev`, which reads `packages` alone: a copy that only `packages-dev` names breaks no such build. 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_pypi_bazel_hub` / `vendor_gem_bazel_hub` | `failed` | **Experimental** (Bazel workspaces). vendor / scan / get `--mode vendored` (pypi, gem): a hub of the project's Bazel workspace reads a file of the project that the run would point at the copy under `.socket/vendor`. That is a rules_python `pip.parse` whose `requirements_lock`, `requirements_by_platform`, `requirements_darwin`, `requirements_linux`, `requirements_windows` or `uv_lock` names a requirements file of the project that the run may write (`requirements.txt` or a file it includes with `-r`, as one set: in a project with no tool lock or with a lone Poetry or PDM lock that resolves no package, for a package they name beside a uv, Pipenv or PEP 751 lock, and for a package they hold by a URL, which is a hosted pin, beside a Poetry or PDM lock) or the `uv.lock` of a uv project; a rules_ruby `ruby.bundle_fetch` whose `gemfile` or `gemfile_lock` names the project's `Gemfile` or `Gemfile.lock`; and a call of a `WORKSPACE` file that passes one of those attributes (`pip_parse`, `rb_bundle_fetch`), where `@//` is the main repository when the file says `workspace(name = "")`. A `WORKSPACE` file counts unless the checkout names a Bazel release of 9 or later, which never reads one (`.bazelversion`, or `USE_BAZEL_VERSION` in `.bazeliskrc`, as three numbers; with an older release, `latest`, a release candidate or neither file it counts): there it is no reason to refuse and no doubt. Neither ruleset builds from such a file: rules_python 2.5.0-rc4 fails with `invalid user-provided repo name '___/_socket/vendor/pypi/…'`, and the `bundle install` action of rules_ruby 1.0.0-rc2 with `The path … does not exist.`, after a command that exited 0 (Bazel 9.3.2, 8.8.2, 7.7.2). Also refused, for every package whose run would write such a file: a workspace whose files cannot be read with certainty where a call of the hub may be behind that (a call of the hub whose file is not a plain string label or that passes `*` or `**`; a hub proxy handed on; a module file or a statement of one that cannot be read, while the workspace calls the hub or a file that was read names its ruleset; a root `MODULE.bazel` that cannot be read at all, or a `WORKSPACE` file that cannot be and counts, for which one byte that is not UTF-8 is enough), because a call may then read the project's lock. 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 call with its file and line, the lock (or the place and the reason of the doubt), the Bazel root, and the mode whose pin both rulesets build, `--mode hosted` (rules_ruby where its call passes no `gem_checksums`, which the detail for a gem says). Not refused: a package whose run writes no file that such a call names, in a Bazel workspace or outside one (a Poetry or PDM project, whose lock is wired alone, beside a hub that reads its exported `requirements.txt`, unless that file holds the package by a URL); a workspace whose files were read and neither call the hub nor name its ruleset; a run with `--allow-vendored-in-bazel`; `vendor --revert`; and a package that the file the call names already names by the copy of the same patch (`.socket/vendor/pypi//`, `.socket/vendor/gem//`): the run adds nothing to what the hub reads, so a project vendored earlier keeps passing its runs, a `scan` or `get` with no `--mode` included, while a new patch for the package is refused; where the calls name more than one file of the project, each of them that holds the package has to name the copy. Where the reading is in doubt no file is known to be the hub's, and every run without the switch is refused. See docs/ecosystems.md "Bazel workspaces: PyPI and RubyGems vendored mode" | +| `vendor_nuget_bazel_workspace` | `failed`; `skipped` (warning, vendor advisory event) for a package that is already vendored for the hub | **Experimental** (Bazel workspaces). 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, or may, 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; `MODULE.bazel` holds the block and the `nuget.from_lock` it was written beside is gone (the block's own tag still hands the lock to the hub: put the tag back, or run `socket-patch vendor --revert`); no tag that reads a lock of the project is found and one may be hidden (`MODULE.bazel` or a file it includes is there and is not read as a whole, or the workspace names rules_csharp and a part of those files is not read with certainty: the detail names what could not be read); 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` or `SOCKET_NO_BAZEL=1` (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 and none can be hidden (also in a workspace that does not name rules_csharp and whose files are all read as a whole, whatever else of them is not read with certainty), 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. | @@ -4193,7 +4194,7 @@ match it, withholds the statement: | `gradle_unpatched_copy` | `failed[].reason` | The purl the warning above (or `vex_gradle_derived_cache_check_failed`) withheld. | | `vex_gradle_derived_cache_check_failed` | run warning | The derived-cache check of an attested Gradle copy did not finish (it crashed), so a copy derived from the unpatched jar cannot be ruled out; no statement for that purl. | | `vex_gradle_lock_above_base` | run warning and `failed[].reason` | A hosted pin is wired, but a lock file records a release above its base, which that build resolves instead of the patch; no statement until it is re-locked or the patch is rolled back. | -| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | **Experimental** (Bazel workspaces). In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, the lock of a pnpm workspace above it that names that directory among its importers, or a `packages.lock.json` below it), or it is a patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it, or holds one that does not reach the hub because the hub's `use_extension` is isolated (`isolate = True`: no `override_repo` of the block reaches such a usage, and the hub keeps the jar of its lock) (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock, with the attribute the call has to carry for a crate, `cargo_config`, and for a NuGet package, `nuget_config`, and for a crate `scan --mode vendored` as well; for a Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``, and when it holds the entry of the patch itself, which does not reach an isolated hub, ``The entry that MODULE.bazel holds for this patch does not reach this hub.``; for a vendored PyPI copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, for a vendored gem or NuGet package (no test builds one under its hub), for a vendored crate (rules_rust builds it), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it unless it is a `packages.lock.json`, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**`, a `pip.parse` with `uv_lock` or a `crate.from_cargo` with a cargo-bazel lock, `lockfile` (it may take its packages from a file that is not read), for a crate the lock does not take from a registry, for a NuGet package when the `nuget_config` of any `nuget.from_lock` call names the patch, is not a plain string label of the main repository or cannot be read, or when such a call passes `*` or `**` (rules_csharp makes one hub of all the calls, so the pin of another project may be what it builds), for a Maven jar when the block holds the entry of its patch and no hub that fetches the jar is on an isolated `use_extension` (a usage that cannot be read may be a shared one: the entry stands), or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | +| `vex_bazel_not_in_build` | run warning and `skipped` event of `vex` | **Experimental** (Bazel workspaces). In a Bazel workspace, `MODULE.bazel` or a file it includes hands the package to a hub that builds it from a lock (aspect_rules_js `npm.npm_translate_lock`, rules_python `pip.parse`, rules_ruby `ruby.bundle_fetch`, rules_rust `crate.from_cargo`, rules_csharp `nuget.from_lock`, rules_jvm_external `maven.install`), and the patch is not in what the hub builds: it is in the installed copy while the project's own lock, which the call names, lists the package at that version without naming the patch (the lock in the project's directory, the lock of a pnpm workspace above it that names that directory among its importers, or a `packages.lock.json` below it), or it is a patch of a Maven artifact in any mode (in an installed jar, in a pin of a `pom.xml` or a Gradle file, in a copy vendored for such a build) while a pinned hub fetches the plain jar of that artifact at that version and the block that hosted and vendored mode keep in the root `MODULE.bazel` holds no entry of that patch for it, or holds one that does not reach the hub because the hub's `use_extension` is isolated (`isolate = True`: no `override_repo` of the block reaches such a usage, and the hub keeps the jar of its lock) (no file of a project decides what a hub fetches: the same from every project of the workspace, and the same after a hosted or vendored command that wrote no entry for the hub; a jar that the hub takes from the Maven local repository under `m2local` counts as fetched, and the lock's sha256 is not compared with the patch), or it is a PyPI copy under `.socket/vendor` and the call names the file that points at it. The package is not omitted: each advisory of its patch gets a statement of the package's own with `status: "affected"`, the package as the one subcomponent of the product, and an `action_statement` that says what Bazel builds the package from and what to run (`scan --mode hosted` in the directory of that lock, with the attribute the call has to carry for a crate, `cargo_config`, and for a NuGet package, `nuget_config`, and for a crate `scan --mode vendored` as well; for a Maven jar `get pkg:maven//@ --mode hosted` at the Bazel root, or with `--mode vendored`, the package by its coordinates alone, without the qualifiers of its purl; where hosted and vendored mode write no entry for the hub, in the place of the command ``Hosted and vendored mode write no entry for this hub (``): .`` with the `maven_bazel_*` code and the reason of the warning that the command gives (those of vendored mode: an option about downloads does not count); before either, when the block holds the entry of another patch for the jar, ``MODULE.bazel holds the entry of patch for this jar, and where the block is in effect the Bazel build takes that patch's jar.``, and when it holds the entry of the patch itself, which does not reach an isolated hub, ``The entry that MODULE.bazel holds for this patch does not reach this hub.``; for a vendored PyPI copy `vendor --revert` first), and for an installed copy ends with the way out of a repository that ships the installed tree (``If what you ship is the installed tree and not what Bazel builds, pass `--no-bazel` (`--vex-no-bazel` on scan, apply and vendor).``; a Maven statement, which is one for every mode, says ``the patch is only in what Maven or Gradle builds from`` where the others say ``the patch is only in the installed copy``, and ends ``If what you ship is what Maven or Gradle builds and not what Bazel builds, pass …``), with no `justification` and no `impact_statement`; they come after the `not_affected` statement of an advisory that a patched package shares. The warning, one per package, starts `: the VEX document says affected.` and goes on with the action statement; no `vendored_tree_out_of_sync` warning is given for such a package. The document is always written for it, and the exit code is the one of a run without it: standalone `vex` exits 0 with the document, also when every statement is `affected`. It does not report the package as verified: each such statement is a `skipped` event with this `errorCode` and `details.status: "affected"`, counted in `summary.skipped` and not in `summary.verified`, and the envelope's `status` is `partialFailure`. A command run with `--vex` writes the document, keeps its exit code and status, and carries the warning in `vex.warnings` and the number of such statements in `vex.affected`. The one-line summary counts them: `Wrote OpenVEX document with 2 statements (1 affected) to `. `--no-verify` changes none of it. Not raised in a run with `--no-bazel` / `--vex-no-bazel` / `SOCKET_VEX_NO_BAZEL`, under which the Bazel workspace is not read for the document (see "The installed tree" under "VEX provenance markers": what the host command itself does and says in a Bazel workspace stays), for a hosted pin of another ecosystem than Maven, for a vendored gem (rules_ruby builds it only when the call lists every file of the copy among its `srcs`, which is not read), for a vendored crate (rules_rust builds it), for a vendored NuGet package (rules_csharp builds it through the block that vendored mode keeps in `MODULE.bazel`, which `vex` does not read: the statement is the same where that block is missing and the build fails), in a `--global` run, for a patch whose record names no advisory (no run attests it), for the lock of another project (beside the project, below it unless it is a `packages.lock.json`, or above it without naming it), for a package that only the env document of a pnpm 11 lock lists, for a call that is not a statement of its own (in a comprehension, behind `and`, in a conditional, in the arguments of another call: it may never run), for a call that passes `*` or `**`, a `pip.parse` with `uv_lock` or a `crate.from_cargo` with a cargo-bazel lock, `lockfile` (it may take its packages from a file that is not read), for a crate the lock does not take from a registry, for a NuGet package when the `nuget_config` of any `nuget.from_lock` call names the patch, is not a plain string label of the main repository or cannot be read, or when such a call passes `*` or `**` (rules_csharp makes one hub of all the calls, so the pin of another project may be what it builds), for a Maven jar when the block holds the entry of its patch and no hub that fetches the jar is on an isolated `use_extension` (a usage that cannot be read may be a shared one: the entry stands), or was changed by hand and still calls `override_repo`, when a `maven.override` names the artifact, when the hub that would fetch it or its lock cannot be read (what is not known of another hub, such as a second hub without `lock_file` or a `maven_install` of a `WORKSPACE` file, changes nothing), or when the checkout does not say that Bazel reads `MODULE.bazel` as it stands (`.bazeliskrc` or `.bazelversion` names a Bazel before 7.0, or neither names a release while a `WORKSPACE` file defines a repository; an rc file of the checkout names `enable_bzlmod` other than switched on while the checkout names no Bazel 9 or later, or `--ignore_dev_dependency` without switching it off, on whatever line, or cannot be read), or where the files are not read with certainty (a doubt of the reader, a `WORKSPACE` file that defines repositories, which for a Maven jar counts only while the checkout names no Bazel release, a label that is not a plain string, a lock that cannot be read, is over 64 MiB or is a link out of the Bazel root): the statement is then the `not_affected` one of a project without Bazel. See "Bazel workspaces: VEX" in `docs/ecosystems.md`. | | `vex_pnpm_bundled_copy` | run warning and `failed[].reason` | An npm pin is wired, but its pnpm lock names a package whose `bundledDependencies` may ship an unpatched copy of it (the lock does not record that copy's version); no statement while that package bundles it. `vendor --check` and `scan` still treat the wiring as live. | | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven patch is wired in a reactor (`` / ``, a profile's included, or Maven 4 subproject discovery) one of whose modules may build the unpatched version: it resolves the patched version, or its selection cannot be told on the machine that runs `vex`, and no pin or declaration of the patch reaches it; or a declaration may still build the base version; or a pom of the reactor cannot be read. No statement; the note names the module (#261). `list`, `rollback` and `remove` still find the wiring. | diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2f1354fcda..d890d745da 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -430,13 +430,15 @@ pub struct GlobalArgs { /// 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, and a PyPI or RubyGems package whose lock - /// a rules_python or rules_ruby hub of the workspace reads + /// directory does not find; a PyPI or RubyGems package whose lock a + /// rules_python or rules_ruby hub of the workspace reads /// (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), which builds - /// nothing from a lock that names a copy under `.socket/vendor`. Pass - /// it when the build does find the copy, or does not take the - /// project's packages from that lock. Other subcommands accept it - /// silently. + /// nothing from a lock that names a copy under `.socket/vendor`; 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, does not take the project's packages from that lock, 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 b3e6ea3caf..926d164624 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/harness.rs @@ -968,6 +968,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 b4df3ccca0..6a54df4258 100644 --- a/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs +++ b/crates/socket-patch-cli/tests/e2e_bazel_build/nuget.rs @@ -1,4 +1,4 @@ -//! Hosted and agent mode for a NuGet package that comes through +//! Hosted, vendored and agent mode for a NuGet package that comes through //! rules_csharp's `nuget.from_lock(packages_lock_json = "//:packages.lock.json", //! nuget_config = "//:nuget.config")` under Bzlmod: the lock that //! `dotnet restore` writes beside a project, and a `nuget.config` whose one @@ -136,6 +136,22 @@ //! 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 flows assert are gaps of the product, not its @@ -160,7 +176,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, with_vex, Cell, Claim, Fixture, How, Ran, StandIn, Tree, CONSUMER, NOTHING, @@ -213,6 +229,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. @@ -1001,6 +1020,701 @@ 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, `list` says what it says without Bazel and +/// `vex` says not affected, through the committed copy; and +/// `vendor --revert`, `rollback` and `remove` each put every file back +/// byte for byte, the block with its one folder, also for a user who +/// switched the Bazel support off (`SOCKET_NO_BAZEL`). 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. So it is where no tag of the checkout +/// shows the hub: a module file that is not read may hold the tag, and a +/// block without the tag it was written beside still hands the lock to +/// the hub. 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, whatever declined it. With +/// `SOCKET_NO_BAZEL=1` the run is the one of the same checkout without its +/// Bazel files, to the byte, where the block works and wherever the +/// package is declined. +#[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 bare = tempfile::tempdir().expect("create a .NET home"); + 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); + // `vex` says not affected, through the committed copy: the hub + // builds that copy through the block, so the call that hands the + // lock to rules_csharp is no reason to say affected. It is asked + // on a machine that restored nothing, where it has nothing to + // warn of: NuGet's folder of `home` holds the unpatched copy. + let run = |cell: &Cell, args: &[&str]| socket_patch(cell, &standin, bare.path(), args); + hub.stands_alone(run, &Claim::new(&purl, &patch.uuid, How::Vendored), true); + 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 + ); + } + // The switch for a project that Bazel does not build leaves the undo + // on: with it the folder goes out of the block all the same. + let ran = scan(&hub, &[]); + assert_eq!(ran.code, 0, "{test}: {}", ran.dump); + let ran = on_machine(&standin, home.path(), |api, env| { + let env = [env, &[("SOCKET_NO_BAZEL", "1")]].concat(); + hub.socket_patch(api, undo[0], &env) + }); + 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 + // fourth 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. The last + // two are hubs that no tag of the checkout shows. The module file is + // larger than socket-patch reads, so it may hold the tag; and the tag + // is gone, while the block of an earlier vendored run still hands the + // lock to the hub. + let asked = standin.asked(&service); + let large = format!("{module}{}", "#\n".repeat(1 << 19)); + let unread = "MODULE.bazel: it cannot be read: it is larger than 1 MiB, so socket-patch \ + cannot tell which `nuget.from_lock` tags the workspace has"; + let tag = + format!("nuget.from_lock(\n{NAMES_CONFIG} packages_lock_json = \"//:{LOCK}\",\n)\n"); + let untagged = module.replace(&tag, ""); + assert_ne!(untagged, module, "{test}"); + let earlier = block(".socket/vendor/nuget/7e57ce11-0000-4000-8000-5184602cd3cc"); + let orphaned = format!("{untagged}\n{earlier}"); + let orphan = format!( + "MODULE.bazel:{}: the block that socket-patch keeps there still reads `//:{LOCK}` for the \ + hub, and the `nuget.from_lock` it was written beside is gone, so a package vendored now \ + would not be among the block's feeds: put that tag back, or take the vendored packages \ + out (`socket-patch vendor --revert`), and run this command again", + untagged.lines().count() + 2 + ); + 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); 6] = [ + ( + &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", + ), + (&large, Some("9.3.2"), None, unread), + (&orphaned, Some("9.3.2"), None, &orphan), + ]; + 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, + // also where no tag of the checkout shows the hub. + let lifted: [(&str, Option<&str>); 3] = [ + (&module, None), + (&large, Some("9.3.2")), + (&orphaned, Some("9.3.2")), + ]; + for ((module, release), flag) in lifted.iter().flat_map(|row| [(*row, true), (*row, false)]) { + let cell = checkout(Some(module), release); + 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); + } + + // The switch for a project that Bazel does not build: the run of the + // same checkout without its Bazel files, to the byte. Beside those + // files the run is another one: the block, or the package declined, + // also where no tag of the checkout shows the hub. + let bazel = [MODULE, BAZEL_LOCK, BAZEL_VERSION]; + let switched: [(&str, Option<&str>, i32); 4] = [ + (&module, Some("9.3.2"), 0), + (&module, None, 1), + (&large, Some("9.3.2"), 1), + (&orphaned, Some("9.3.2"), 1), + ]; + for (module, release, code) in switched { + let cell = checkout(Some(module), release); + let origin = standin.origin(); + let args = [&VENDORED[..], &["--patch-server-url", &origin]].concat(); + let beside = on_machine(&standin, home.path(), |api, env| { + cell.off_is_without_bazel(api, &args, env, &bazel) + }); + assert_eq!(beside[0]["code"], code, "{test}: {beside:#}"); + } +} + /// What a run of agent mode is made of. struct Restored { /// The stand-in of the run: nuget.org with the two packages of the 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 0000000000..f5ae5b9b60 --- /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/built.rs b/crates/socket-patch-core/src/bazel/built.rs index fc2f0c6d31..f00abe0474 100644 --- a/crates/socket-patch-core/src/bazel/built.rs +++ b/crates/socket-patch-core/src/bazel/built.rs @@ -19,8 +19,9 @@ //! rules_ruby 1.0.0-rc2 fails the build on a vendored gem (same three //! releases) unless the call lists every file of the copy among its //! `srcs`, which it copies beside the Gemfile: `srcs` is not read here, so -//! a vendored gem is not judged. What rules_csharp does with a vendored -//! package no test here builds, so that is not judged either. +//! a vendored gem is not judged. rules_csharp builds a vendored package +//! through the block that vendored mode keeps in `MODULE.bazel` +//! ([`super::nuget`]), which is not read here either. //! //! A sixth, rules_jvm_external, takes each jar that the lock of a hub pins //! (`maven.install`) at the lock's sha256: from a repository of the lock, @@ -194,7 +195,7 @@ struct Hub { /// Whether a call of the tag may build a package from a line that /// points at a copy under `.socket/vendor`: rules_js and rules_rust /// do, rules_ruby does when the call lists the files of the copy, and - /// of rules_csharp no test here has shown that it does not. + /// rules_csharp does through the block of vendored mode. builds_vendored: bool, /// The attributes that name a file beside the lock, where a pin in /// the lock does not name its patch. The calls of such a tag make one diff --git a/crates/socket-patch-core/src/bazel/maven.rs b/crates/socket-patch-core/src/bazel/maven.rs index 1527d531bf..41b53515f7 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, reads_workspace_file, 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 @@ -173,7 +172,7 @@ pub struct Hub { /// nothing a string of the block would have to escape. Otherwise, whether /// the usage is isolated for certain (`isolate = True`): one that cannot /// be read may be shared. -fn proxy(ws: &Workspace, tag: &Tag) -> Result { +pub(super) fn proxy(ws: &Workspace, tag: &Tag) -> Result { let made = || { let (_, file) = ws.files.iter().find(|(path, _)| path == tag.file)?; let Bound::Call(made) = file.binds.get(tag.call.bind?)?.to else { @@ -411,7 +410,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 @@ -446,11 +445,42 @@ 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, + } + } +} + +/// Whether a call of a file of `ws` that was read names the ruleset +/// `module`: a `bazel_dep` of it, or an override. +pub(super) fn names(ws: &Workspace, module: &str) -> bool { + let module = Value::Str(module.to_string()); + let names = |call: &Call| [call.arg("name"), call.arg("module_name")].contains(&Some(&module)); + let mut files = ws.files.iter(); + files.any(|(_, file)| file.calls.iter().any(names)) +} + +/// 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) }; @@ -544,9 +574,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; } } @@ -566,7 +594,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") { @@ -620,13 +648,7 @@ impl Hubs { } } } - let module = Value::Str(EXTENSION.module.to_string()); - let names = - |call: &Call| [call.arg("name"), call.arg("module_name")].contains(&Some(&module)); - let named = ws - .files - .iter() - .any(|(_, file)| file.calls.iter().any(names)); + let named = names(&ws, EXTENSION.module); let calls = matches!(ws.legacy, Some(Ok(_))); // The file as the Bazel of the checkout may read it: one rule for // the doubt about a `maven_install` and for [`Hubs::legacy`]. @@ -914,48 +936,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, @@ -964,14 +964,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 @@ -1074,26 +1067,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. @@ -1250,19 +1227,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 \ @@ -1272,7 +1237,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" ), @@ -1876,6 +1841,7 @@ pub fn upstream(root: &Path, patches: &[(&str, &str)]) -> Vec Option { crate::test_env::guarded_var(OFF_ENV) } +mod block; pub mod built; pub mod cargo; pub(crate) mod cargo_bazel; @@ -100,13 +101,30 @@ pub(crate) fn root_of(project: &Path) -> Option { root_in(&dirs, repo_at_end_of(dirs.clone())) } -/// [`root_of`] 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) - })?; + }) +} + +/// [`root_of`] 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(), @@ -152,11 +170,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(); @@ -168,6 +189,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 da4b8811e6..022a2b685f 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, names, 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,45 @@ 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)) => Some(match named(ws, label, dir, locks)? { + Ok(lock) => Read::Ours(lock.clone()), + Err(path) => Read::Other(at, path, None), + }), + Some(_) => Some(Read::Any(at)), + None => tag.call.unpacks().then_some(Read::Any(at)), + } +} + +/// The file of the checkout that the label `label` names: the lock of +/// `locks` it is for the project in `dir`, or else its path from the Bazel +/// root. `None`: it names no file of the main repository. +fn named<'a>( + ws: &Workspace, + label: &str, + dir: &str, + locks: &'a [String], +) -> Option> { + 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(locks.iter().find(ours).ok_or(path)) +} + /// [`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 +354,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 +434,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,14 +490,531 @@ 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 and none that does can + /// be hidden. + Plain, + /// Nothing: the hub reads a lock of the project, or may, 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. +/// +/// A project whose lock no tag reads is vendored as without Bazel, unless +/// a hub may read the lock all the same. That is declined too: a package +/// in the folder of its patch alone is in no feed of such a hub, whose +/// build then fails on the re-pinned lock. The block is there and the tag +/// it was written beside is gone, so the block's own tag still hands the +/// lock to the hub; or a tag may not have been read ([`gate`]). +/// +/// 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 (ws, dir) = (Workspace::read(&view), prefix(&root)); + let feeds = match (gate(&ws, &files, &dir, locks), &found) { + // The tag the block was written beside is gone, and the block's + // own still hands the lock to the hub: what the hub is to hold + // for another package is no longer known. + (Vendored::Plain, Block::Ours(at, kept, _)) + if matches!(named(&ws, &kept.lock, &dir, locks), Some(Ok(_))) => + { + let line = module[..at.start].matches('\n').count() + 1; + return Vendored::Declined(format!( + "{FILE}:{line}: the block that socket-patch keeps there still reads `{}` for the \ + hub, and the `nuget.from_lock` it was written beside is gone, so a package \ + vendored now would not be among the block's feeds: put that tag back, or take \ + the vendored packages out (`socket-patch vendor --revert`), and run this command \ + again", + kept.lock + )); + } + (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. +/// +/// Where no tag that was read reads a lock of the project, one that was +/// not read still may. A doubt of the reader declines the package in a +/// workspace that has to do with the ruleset: a call of a file that was +/// read names it ([`names`]), as the `bazel_dep` of every workspace does +/// that uses the extension. In a workspace of other rulesets such a doubt +/// is about no hub, and only a file that is there and was not read as a +/// whole declines ([`Workspace::unread`]): it may be the one that names +/// the ruleset. +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) { + // A tag that was not read may read the lock. The doubt that says + // so: the first one in a workspace that has to do with the + // ruleset, else the one about a file that was not read. + None => { + let first = ws.doubts.iter().chain(&tags.doubts).next(); + let doubt = first.filter(|_| names(ws, EXTENSION.module)); + let doubt = doubt.or(ws.unread.as_ref()); + doubt.map_or(Vendored::Plain, |doubt| Vendored::Declined(unsure(doubt))) + } + Some(tag) => match feeds(ws, files, &tags, tag, dir) { + Ok(feeds) => Vendored::Block(feeds), + Err(why) => Vendored::Declined(why), + }, + } +} + +/// What `doubt` of the reader stands against: the tags of the workspace +/// are not all known. +fn unsure(Doubt { file, line, why }: &Doubt) -> String { + let place = match line { + 0 => file.clone(), + line => format!("{file}:{line}"), + }; + format!( + "{place}: {why}, so socket-patch cannot tell which `nuget.from_lock` tags the workspace has" + ) +} + +/// 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) = ws.doubts.iter().chain(&tags.doubts).next() { + return Err(unsure(doubt)); + } + 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).ok()).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::starlark::MAX_BYTES; use super::super::workspace::Entry; use super::*; /// The tag of the fixture that hosted mode patches on a real Bazel, and /// the same tag without its `nuget_config`. - const WIRED: &str = r#"nuget.from_lock( + pub(crate) const WIRED: &str = r#"nuget.from_lock( nuget_config = "//:nuget.config", packages_lock_json = "//:packages.lock.json", )"#; @@ -1051,4 +1623,636 @@ 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(), + ] { + assert_eq!(gated(&rest, &[]), Vendored::Plain, "{rest}"); + // Also where the block could not be shown to work. + let unnamed = [(".bazelversion", None)]; + assert_eq!(gated(&rest, &unnamed), Vendored::Plain, "{rest}"); + } + } + + /// What was not read may hide the tag that reads the lock, and a + /// package vendored as without Bazel is not among the feeds of that + /// hub: its build would fail on the re-pinned lock. So where no tag + /// is found, a doubt of the reader declines the package in a workspace + /// that has to do with the ruleset, and a file that is there and was + /// not read as a whole declines it in any workspace: that file may be + /// the one that names the ruleset. A doubt in a workspace of other + /// rulesets whose files were all read is about no hub, and a + /// `WORKSPACE` file is never one of those files. + #[test] + fn a_tag_that_may_be_hidden_declines_where_none_is_found() { + let lock = ["packages.lock.json".to_string()]; + let gated = |files: &[(&str, Entry)]| { + let view = |path: &str| { + let found = files.iter().find(|(name, _)| *name == path); + found.map_or(Entry::Absent, |(_, entry)| entry.clone()) + }; + gate(&Workspace::read(&view), &view, "", &lock) + }; + let text = |text: &str| Entry::Text(text.to_string()); + let tells = "so socket-patch cannot tell which `nuget.from_lock` tags the workspace has"; + let declined = |says: &str| Vendored::Declined(format!("{says}, {tells}")); + // In a workspace of the ruleset: a use of the proxy that may call + // a tag, and an included file that is not there. + let include = "include(\"//:more.MODULE.bazel\")"; + let elsewhere = BARE.replace("//:", "//api:"); + for (rest, says) in [ + ( + format!("{elsewhere}\nMORE = [nuget]"), + "MODULE.bazel:5: `nuget` is used other than to call a tag", + ), + ( + include.to_string(), + "more.MODULE.bazel: it does not exist; MODULE.bazel:4 includes it", + ), + ] { + let read = gated(&[(FILE, text(&module(&rest)))]); + assert_eq!(read, declined(says), "{rest}"); + } + // The same include where nothing names the ruleset. + let go = format!("bazel_dep(name = \"rules_go\", version = \"0.50.1\")\n{include}\n"); + assert_eq!(gated(&[(FILE, text(&go))]), Vendored::Plain); + // A file that is there and is not read: the included one, and the + // root file itself. + let binary = Entry::Unreadable("it is not UTF-8".to_string()); + let files = [(FILE, text(&go)), ("more.MODULE.bazel", binary.clone())]; + let says = "more.MODULE.bazel: it cannot be read: it is not UTF-8; MODULE.bazel:2 \ + includes it"; + assert_eq!(gated(&files), declined(says)); + let says = "MODULE.bazel: it cannot be read: it is not UTF-8"; + assert_eq!(gated(&[(FILE, binary.clone())]), declined(says)); + // A `WORKSPACE` file hides no tag: rules_csharp has no form for + // that file, and what the reader makes of it is kept apart from + // its doubts. One that cannot be read, and one that defines + // something, decline nothing where no tag is found and change + // nothing beside a tag, whether the Bazel the checkout names reads + // such a file (7.7.2) or not (9.3.2). + let bare = [(FILE, text(&module("")))]; + let wired = [ + (FILE, text(&module(WIRED))), + ("MODULE.bazel.lock", text(SELECTED)), + ("nuget.config", text(CONFIG)), + ]; + for release in ["9.3.2\n", "7.7.2\n"] { + for legacy in [binary.clone(), text("nuget_repo(name = \"nuget\")\n")] { + let beside = [("WORKSPACE", legacy), (".bazelversion", text(release))]; + let read = gated(&[&bare[..], &beside].concat()); + assert_eq!(read, Vendored::Plain, "{release}"); + let read = gated(&[&wired[..], &beside].concat()); + let block = Vendored::Block(feeds(None, &[NUGET_ORG])); + assert_eq!(read, block, "{release}"); + } + } + } + + #[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"); + } + } + + /// A hub can read the lock while no tag of the checkout is found: the + /// tag is gone and the block that was written beside it still reads + /// the lock, or the root file cannot be read. Vendored as without + /// Bazel, a package would not be among the feeds of that hub, and its + /// build would fail on the re-pinned lock: the package is declined. A + /// project whose lock neither the tag nor the block reads is vendored + /// as without Bazel. + #[test] + fn a_hub_that_no_tag_of_the_checkout_shows_is_declined() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("repo"); + let below = root.join("svc"); + std::fs::create_dir_all(&below).unwrap(); + std::fs::create_dir(base.join(".git")).unwrap(); + let lock = ["packages.lock.json".to_string()]; + let module = checkout(&root); + std::fs::write(root.join("nuget.config"), CONFIG).unwrap(); + let Vendored::Block(read) = vendored(&root, &lock) else { + panic!("no block"); + }; + let declined = |why: &str| Vendored::Declined(why.to_string()); + + // The block of an earlier run, without the tag it was written + // beside. + let wired = with_folder(&module, &read, FOLDER_A, &[]).expect("a block"); + let orphaned = wired.replace(WIRED, ""); + assert_ne!(orphaned, wired); + std::fs::write(root.join(FILE), &orphaned).unwrap(); + let says = "MODULE.bazel:7: the block that socket-patch keeps there still reads \ + `//:packages.lock.json` for the hub, and the `nuget.from_lock` it was written \ + beside is gone, so a package vendored now would not be among the block's \ + feeds: put that tag back, or take the vendored packages out (`socket-patch \ + vendor --revert`), and run this command again"; + assert_eq!(vendored(&root, &lock), declined(says)); + // The block reads the lock of the project at the root alone, with + // its tag and without it. + assert_eq!(vendored(&below, &lock), Vendored::Plain); + std::fs::write(root.join(FILE), &wired).unwrap(); + assert_eq!(vendored(&below, &lock), Vendored::Plain); + + // The root file is larger than the reader takes: for every project + // of the workspace. + let tells = "so socket-patch cannot tell which `nuget.from_lock` tags the workspace has"; + let large = format!("{module}{}", "#\n".repeat(MAX_BYTES / 2)); + std::fs::write(root.join(FILE), large).unwrap(); + let says = format!("MODULE.bazel: it cannot be read: it is larger than 1 MiB, {tells}"); + assert_eq!(vendored(&root, &lock), declined(&says)); + assert_eq!(vendored(&below, &lock), declined(&says)); + // Or it is a link that leads out of the workspace. + #[cfg(unix)] + { + std::fs::write(base.join("module"), &module).unwrap(); + std::fs::remove_file(root.join(FILE)).unwrap(); + std::os::unix::fs::symlink(base.join("module"), root.join(FILE)).unwrap(); + let out = "MODULE.bazel: it cannot be read: it leads out of the Bazel workspace"; + assert_eq!(vendored(&root, &lock), declined(&format!("{out}, {tells}"))); + } + } + + #[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 8d38a2ca4c..45ba03a1be 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 621d80c338..bdce196d09 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,474 @@ 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( + " = warnings + .iter() + .filter(|w| w.code == VENDOR_DECLINED) + .collect(); + assert!( + warned.len() == 1 && warned[0].detail.starts_with(says), + "{warnings:?}" + ); + assert_eq!(hub_files(root), before); + } + + /// A config that the revert leaves wired (tooling wrote it anew, and + /// it still names the folder) keeps its lock pin and its package, and + /// so the block: the hub takes that package through the block alone. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_config_that_is_left_wired_keeps_the_block() { + 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 (_, entry, _) = unwrap_done(run_vendor(root, &blobs, &installed, &record, false).await); + let entry = entry.expect("a ledger entry"); + let config = std::fs::read_to_string(root.join("nuget.config")).unwrap(); + std::fs::write(root.join("nuget.config"), config.replace(" <", "\t\t<")).unwrap(); + let kept = hub_files(root); + + let outcome = revert_nuget(&entry, root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.kept_artifact, "{:?}", outcome.warnings); + assert_eq!(hub_files(root), kept, "the block, the config and the lock"); + assert!(root.join(&entry.artifact.path).is_file()); + let says = format!("so the block of {MODULE_FILE} is kept"); + let warned = |w: &VendorWarning| w.detail.contains(&says); + assert!( + outcome.warnings.iter().any(warned), + "{:?}", + outcome.warnings + ); + } + + /// A config without a package source gets nuget.org beside the folder + /// of the patch, and the block holds the sources of the hub's tag as + /// they are after that: the next run writes no file. + #[tokio::test] + #[serial_test::serial] + async fn a_hub_config_without_a_source_gives_the_block_of_the_next_run() { + let _unset = crate::test_env::EnvGuard::unset(ALLOW_IN_BAZEL_ENV); + let bare = + "\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 c05fd8f077..bf66d7e7df 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 36da592e52..67eec23eb3 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -23,14 +23,18 @@ //! as a skip); //! 6. a Maven version no module of the build selects //! (`vendor_maven_version_not_selected`, a skip too); -//! 7. a project in a Bazel workspace whose build would not find the -//! vendored copy ([`bazel_workspace_refusals`]), unless the user allowed -//! it ([`ALLOW_IN_BAZEL_ENV`]): any Composer project -//! (`vendor_composer_bazel_workspace`), unless the lock already names a -//! vendored copy in `packages` or in the package's section, and a PyPI +//! 7. what rests on the Bazel workspace of the project +//! ([`bazel_workspace_refusals`]), unless the user allowed it +//! ([`ALLOW_IN_BAZEL_ENV`]): any Composer project in one +//! (`vendor_composer_bazel_workspace`), unless the lock already names +//! a vendored copy in `packages` or in the package's section; a PyPI //! or RubyGems project whose lock a hub of the workspace reads //! (`vendor_pypi_bazel_hub`, `vendor_gem_bazel_hub`), unless that lock -//! already names the patch's copy; +//! 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. @@ -48,7 +52,8 @@ use crate::patch::redirect::upstream::HostedPin; use crate::utils::purl_key::PurlKey; use crate::vendor::state::{lookup_entry, VendorEntry}; use crate::vendor::{ - bazel_hub, bun_lock, composer_lock, gem, lock_inventory, npm_flavor, npm_lock, vlt_lock, + bazel_hub, 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 @@ -111,10 +116,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 @@ -123,25 +124,26 @@ fn is_composer(purl: &str) -> bool { /// 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. The user's word lifts the one of any -/// Composer project ([`composer_lock::bazel::refusals`]) and the one of a +/// Composer project ([`composer_lock::bazel::refusals`]), the one of a /// PyPI or RubyGems project whose lock a hub of the workspace reads -/// ([`bazel_hub::refusals`]). 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 +/// ([`bazel_hub::refusals`]) and the one of a NuGet package of a +/// rules_csharp hub ([`nuget_feed::bazel_refusals`]). 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. 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 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(bazel_hub::refusals(project_root, candidates).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(); + 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(); @@ -512,6 +514,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()); + } + /// A project whose requirements a hub of its Bazel workspace reads: /// every PyPI candidate is refused with the one answer of the project, /// and no candidate of an ecosystem whose hub the workspace does not diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 5857af81d1..925f36f68f 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 b495b8d167..b082f61650 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 3301668c2d..2edadac141 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 | @@ -1763,6 +1763,184 @@ 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. +- `MODULE.bazel` holds the block, and the `nuget.from_lock` it was written beside is gone. + The block is a `nuget.from_lock` of the hub itself: it still hands the lock to + rules_csharp, with the folders of the packages vendored before as its feeds, and a package + vendored now would not be among them. Put the tag back, or take the vendored packages out + with `socket-patch vendor --revert`, and run the command again. +- No tag that reads the lock is found, and one may be hidden. `MODULE.bazel`, or a file it + includes, is there and is not read as a whole: a link that leads out of the workspace, a + file over 1 MiB, one that is not UTF-8 or cannot be parsed, an `include` that is not + followed. Or the workspace names rules_csharp, and a part of those files cannot be read + with certainty: an `include` of a file that does not exist, a use of the extension that is + no call of a tag. A hub that such a part declares does not get the package, and its build + fails: on the upstream package, which no longer matches the re-pinned lock, or on the + folder that `nuget.config` names, which it reads as a URL. The message names what could + not be read. +- 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 neither a +`nuget.from_lock` nor the block reads, where no tag can be hidden: the package lies in the +folder of the patch, and no line of `MODULE.bazel` is written. That includes a workspace that +does not name rules_csharp and whose files are all read as a whole: a part of them that +cannot be read with certainty is then about no hub. For a project that Bazel does not build +and that is declined all the same, pass `--allow-vendored-in-bazel`, or set +[`SOCKET_NO_BAZEL`](#bazel-workspaces-a-project-that-bazel-does-not-build). + +**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 @@ -2175,7 +2353,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 | -| NuGet: rules_csharp `nuget.from_lock` over `packages.lock.json` | Supported with `nuget_config` on the tag | Not supported | Not supported | Supported; for a hosted patch, 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; for a hosted patch, with 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 | @@ -2258,7 +2436,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 @@ -2284,10 +2468,6 @@ 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 NuGet.** The path of the committed copy means nothing where Bazel - runs: 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`. Measured by hand on - the three Bazel releases; no test of this repository runs that build. - **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 @@ -2295,6 +2475,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. - **A hosted Cargo pin that is already in the files, 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 @@ -2352,6 +2544,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 @@ -2404,6 +2602,11 @@ projects too. What the sections below then do for it: - PyPI and RubyGems: vendored mode is declined where a hub call of the workspace reads the project's lock, or may read it ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)). +- NuGet: for a package whose lock a rules_csharp `nuget.from_lock` reads, vendored mode + keeps a block in the root `MODULE.bazel`, or declines the package where it cannot show + that the block works. It also declines a package whose lock such a tag may read, behind a + part of the workspace files that is not read + ([Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)). - Go, Cargo and Maven: the `.bazelignore` at the Bazel root gets two lines for each kind of copy under `.socket` that a run wrote: the Go module copies, the vendored crates of a crate hub, the jars that vendored mode keeps for a rules_jvm_external hub @@ -2464,6 +2667,11 @@ What an earlier run wrote for Bazel is still listed and undone with the variable Beside a Maven or Gradle build the hub's directory is a copy that only a `vendor` run without the variable writes: one that was lost stays lost, `vendor --check` names it, and the undo still takes its entry out. +- The block that vendored mode keeps there for the NuGet packages of a rules_csharp hub + ([Bazel workspaces: NuGet](#vendored-mode-under-a-rules_csharp-hub)): `vendor --revert`, + `rollback` and `remove` take the folder of a patch out of it, and the block with its last + folder, as they do without the variable. No folder is added: a vendored run writes a + package as in a checkout without the workspace file. - The `.bazelignore` lines: no pair is added, and the pair of a copy that is gone is removed by the command that removed the copy (`rollback`, `remove`, `vendor --revert`, `repair`, a scan). @@ -4009,6 +4217,9 @@ write for any package it would decline because the project is in a Bazel workspa build may not find the vendored copy. PyPI and RubyGems have such a refusal too, for a project whose lock a hub of the workspace reads: see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode). +So has NuGet, for a 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 of a project that uses vendored mode already, by a release before this refusal or with the flag: @@ -4860,11 +5071,12 @@ patched: - **A PyPI patch committed under `.socket/vendor`** (vendored mode), when such a call names the file that points at the copy. rules_python 2.5.0-rc4 takes the path of the line for the name of a project, and the build of everything the hub serves fails (same three - releases). A vendored npm tarball is built by rules_js and a vendored crate by rules_rust, - and each keeps its statement. So do a vendored gem and a vendored NuGet package, for - other reasons: rules_ruby builds a gem only when the call lists every file of the copy - among its `srcs`, which is not read, and no test here runs the build of a NuGet package - yet, so nothing is said of either. + releases). A vendored npm tarball is built by rules_js, a vendored crate by rules_rust and + a vendored NuGet package by rules_csharp, through the block that vendored mode keeps in + `MODULE.bazel`, and each keeps its statement. `vex` does not read that block: a vendored + NuGet package keeps its statement without it too (the list at the end of this section). + So does a vendored gem, for another reason: rules_ruby builds a gem only when the call + lists every file of the copy among its `srcs`, which is not read, so nothing is said of it. Vendored mode declines a PyPI package and a gem by default where the hub reads the file ([Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode)), so this is the state of a project vendored with `--allow-vendored-in-bazel` or by an @@ -5066,11 +5278,12 @@ 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 Cargo and -NuGet a flow of agent mode holds the documents to the unpatched build as well: the run -(`--vex`), `vex` and `vex --no-verify` each write one `affected` statement, and -`vex --no-bazel` one `not_affected` statement. For these, and for a Maven entry in -`MODULE.bazel`, +`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 Cargo and NuGet a flow of agent +mode holds the documents to the unpatched build as well: the run (`--vex`), `vex` and +`vex --no-verify` each write one `affected` statement, and `vex --no-bazel` one +`not_affected` statement. 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. @@ -5121,9 +5334,13 @@ the build is broken): is listed. Measured on the three releases: the build fails, and the statement still says `not_affected`. Vendored mode declines such a gem by default, so this is the state of a project vendored with `--allow-vendored-in-bazel` or by an earlier release. -- **Vendored mode for NuGet** beside `nuget.from_lock`. rules_csharp 0.5.0 reads the path of - the committed copy as a URL. 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. rules_csharp 0.5.0 + then reads the path of the committed copy as a URL. `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;