From 63020c432442183519755fea9b6bd0557fb3047f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 17:22:18 +0000 Subject: [PATCH 1/4] Start fix for multi-source Gemfile lock warning Refs #2162 Assisted-by: Claude Code:claude-fable-5-2 From 263543a66c8976ddafab9881137cdbb424f33225 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 17:40:36 +0000 Subject: [PATCH 2/4] Test the lock warning for several top-level sources A Gemfile with two top-level `source` lines makes Bundler 2.2 to 2.7 write one GEM section with two remotes. The hosted scan blames a Bundler < 2.2 lock for it and prescribes a `bundle lock` that changes nothing. The new test fails until the warning names the real cause. Refs #2162 Assisted-by: Claude Code:claude-fable-5-2 --- .../src/patch/redirect/mod.rs | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 78a61276f..be0cd1aae 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -32230,6 +32230,118 @@ packages: ); } + /// A Gemfile with more than one top-level `source` line makes bundler + /// 2.2 to 2.7 write ONE `GEM` section naming every one of them (the + /// locks below are what 2.5.22 and 2.6.9 write), and `bundle lock` + /// leaves that lock as it is. The gem is still refused whole, but the + /// warning names the Gemfile's sources as the cause and the remedy that + /// works: the extra source in a `source "" do … end` block. It does + /// not blame an old bundler, does not send the user to a `bundle lock` + /// that changes nothing by itself, and offers agent mode only (vendored + /// mode refuses a gem in a `group` block or with a native extension, + /// which the planner cannot tell apart here). #2162. + #[test] + fn gem_lock_of_a_gemfile_with_several_top_level_sources_names_the_block_remedy() { + let specs = " specs:\n rack (2.2.8)\n rack-test (2.1.0)\n rack (>= 1.3)\n\n\ + PLATFORMS\n ruby\n x86_64-linux\n\n\ + DEPENDENCIES\n rack (= 2.2.8)\n rack-test (= 2.1.0)\n\n"; + let remotes = "GEM\n remote: https://rubygems.org/\n remote: https://user:secret@gems.acme.example/private/\n"; + let locks = [ + format!("{remotes}{specs}BUNDLED WITH\n 2.5.22\n"), + format!( + "{remotes}{specs}CHECKSUMS\n rack (2.2.8) sha256={}\n rack-test (2.1.0) sha256={}\n\n\ + BUNDLED WITH\n 2.6.9\n", + "2".repeat(64), + "3".repeat(64) + ), + ]; + let gemfiles = [ + "source \"https://rubygems.org\"\nsource \"https://user:secret@gems.acme.example/private/\"\n\n\ + gem \"rack\", \"2.2.8\"\n\ngroup :test do\n gem \"rack-test\", \"2.1.0\"\nend\n", + // CRLF, and the second source in call parentheses. + "source 'https://rubygems.org'\r\nsource('https://user:secret@gems.acme.example/private/')\r\n\r\n\ + gem \"rack\", \"2.2.8\"\r\n\r\ngroup :test do\r\n gem \"rack-test\", \"2.1.0\"\r\nend\r\n", + ]; + for lock in &locks { + for gemfile in gemfiles { + let lock = if gemfile.contains('\r') { + lock.replace('\n', "\r\n") + } else { + lock.clone() + }; + for (gem, version) in [("rack", "2.2.8"), ("rack-test", "2.1.0")] { + let (out, locked, r) = gem_redirect(gemfile, &lock, gem_override(gem, version)); + assert!( + r.files.is_empty() && r.edits.is_empty(), + "neither file may be touched: files={:?} edits={:?}", + r.files.keys(), + r.edits + ); + assert_eq!((out.as_str(), &locked), (gemfile, &lock)); + assert_eq!( + warning_codes(&r), + vec!["redirect_gem_lock_unconvergeable"], + "{:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("Gemfile has 2 top-level `source` lines") + && detail.contains("`source \"\" do … end` block") + && detail.contains("then run `bundle lock`") + && detail.contains(&format!("patch {gem} with `--mode agent`")), + "the cause and the remedy that works: {detail}" + ); + assert!( + !detail.contains("bundler < 2.2") + && !detail.contains("with your current bundler") + && !detail.contains("--mode vendored"), + "no old-bundler blame, no bare `bundle lock`, no vendored offer: {detail}" + ); + assert!( + !detail.contains("secret"), + "a source's credentials stay out of the warning: {detail}" + ); + } + } + } + } + + /// The same lock under a Gemfile with ONE top-level source is a stale + /// lock, which `bundle lock` does rewrite (verified on bundler 2.5.22): + /// that remedy stays. A second `source` in a block, or as a `source:` + /// option, is no top-level source. + #[test] + fn gem_stale_multi_remote_lock_keeps_the_bundle_lock_remedy() { + let lock = "GEM\n remote: https://rubygems.org/\n remote: https://gems.acme.example/\n specs:\n \ + rack (2.2.8)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n rack (= 2.2.8)\n\n\ + BUNDLED WITH\n 2.5.22\n"; + for gemfile in [ + "source \"https://rubygems.org\"\n\ngem \"rack\", \"2.2.8\"\n", + "source \"https://rubygems.org\"\nsource \"https://rubygems.org/\"\n\ngem \"rack\", \"2.2.8\"\n", + "source \"https://rubygems.org\"\n\ngem \"rack\", \"2.2.8\"\n\n\ + source \"https://gems.acme.example/\" do\n gem \"acme\"\nend\n", + "source \"https://rubygems.org\"\n\ngem \"rack\", \"2.2.8\"\n\ + gem \"acme\", source: \"https://gems.acme.example/\"\n", + ] { + let (_, _, r) = gem_redirect(gemfile, lock, gem_override("rack", "2.2.8")); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + warning_codes(&r), + vec!["redirect_gem_lock_unconvergeable"], + "{:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("names 2 remotes") + && detail.contains("run `bundle lock` with your current bundler") + && !detail.contains("top-level"), + "{detail}\n{gemfile}" + ); + } + } + /// B1: lock shapes that cannot record the Socket source — a multi-remote /// GEM section under a bundler >= 2.2, a spec duplicated across GEM /// sections, no DEPENDENCIES section, a lock that names no bundler — From fd240c00569642f0db64b4bf1f3536130f59c9ea Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:01:51 +0000 Subject: [PATCH 3/4] Name the Gemfile cause of a multi-remote gem lock A Gemfile with more than one top-level `source` line makes Bundler 2.2 to 2.7 lock every gem in one GEM section that names every source. The hosted scan refused such a gem with a warning that blamed a Bundler < 2.2 lock and prescribed `bundle lock`, which writes the same lock again, so the user went round in a loop. The refusal stays (nothing is written), but for that Gemfile the warning now names the top-level sources as the cause and the remedy that works: move each extra source into a `source "" do ... end` block, then `bundle lock`. It offers agent mode only, since vendored mode refuses a gem in a group block or with a native extension, and it does not print the source URLs, which can carry credentials. A stale multi-remote lock under a one-source Gemfile keeps the `bundle lock` remedy, which does rewrite it. A real-Bundler case in e2e_redirect_gem_build covers the refusal and the remedy on Bundler 2.2 to 2.7. Fixes #2162 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- .../tests/e2e_redirect_gem_build.rs | 170 ++++++++++++++++++ .../src/formats/gem/declarations.rs | 91 +++++++--- .../src/formats/gem/hosted.rs | 14 ++ .../src/patch/redirect/mod.rs | 32 +++- docs/ecosystems.md | 2 +- 6 files changed, 285 insertions(+), 28 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8f2665cba..8bc7496b1 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -408,7 +408,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm **Non-UTF-8 candidate files (#721)**: the rewriters edit UTF-8 text only. A candidate file that exists but is not UTF-8 (for example a UTF-16 `requirements.txt`, which is what Windows PowerShell 5.1's `pip freeze >` writes and which pip installs from) is never read as absent. When a candidate of its ecosystem could rewrite it, the run is refused with `candidate_file_unreadable` (exit 1, `--dry-run` included), the message names the file, and nothing is written; the remedy is to re-save the file as UTF-8. Two exceptions keep their own refusals. A Gradle build file the Gradle planner reaches gets that planner's per-build refusal (`redirect_gradle_build_file_unreadable`, exit 0) and the rest of the run goes ahead, and with no readable Gradle build a stray Gradle file (a lock, a nested script) is never rewritten, so it does not refuse the run, while a non-UTF-8 root `settings.gradle(.kts)` or `build.gradle(.kts)` still refuses it (it may be the build itself). An unreadable `socket-patch.sbt` is refused with `redirect_sbt_owned_file_unreadable`. A vendored→hosted takeover checks this before it reverts anything, so a refused run leaves the vendored wiring, ledger entry and artifact byte-identical. Vendored mode likewise refuses a non-UTF-8 `requirements.txt` or `-r` include by name (`pypi_no_requirements`) instead of wiring around it. Lock-only discovery reads `requirements.txt` and its in-root `-r` includes the way pip decodes them (a UTF-16 or UTF-32 byte-order mark selects that encoding), so such a project's pins are still found instead of reporting "No packages found". -**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. The patch registry serves a patched platform gem (a "prebuild": the upstream platform gem's name, gemspec and file list, with the patch's files replaced) for each platform the patch's grant lists (`registryOverride.identifiers.gemPlatforms`, `{platform, gemChecksumSha256}` each; absent or empty when it has none). When EVERY platform entry of the gem at the patched version has a prebuild there, the gem is wired like any other: the manifest edit is the same, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to the patch registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 of its own build (a platform entry to its prebuild's, the ruby-platform entry to `gemChecksumSha256`); a lock with no `CHECKSUMS` section gets none. A frozen `bundle install` of that pair fetches the one platform gem of the machine from the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15). When a locked platform has no prebuild the gem is skipped with `redirect_gem_platform_unsupported`, which names the builds the lock holds, the ones the patch has no patched build for, and what the registry serves; so is a platform build in the merged layout of Bundler < 2.2. A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, or a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain), `redirect_gem_platform_unsupported` (a locked platform build the patch has no prebuild for, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. +**Gem hosted wiring**: for a gem the manifest (`Gemfile` / `gems.rb`) declares, hosted mode appends ONE option to the user's own declaration, `, source: ""`, after its last argument, and changes nothing else of it: version requirement(s), quote style, other options, trailing comment, position, enclosing `group` / `platforms` / `install_if` block and indentation stay byte for byte. This covers a parenthesized call (the option goes inside the parentheses), a declaration continued over several lines (after the last argument, on its line), several version requirements, `%w` / symbol option values, a trailing `if` / `unless` / `while` / `until` / `rescue` modifier (the option goes before the modifier) and a declaration followed by another statement after a `;`. For a gem the manifest does not declare (a transitive dependency: the lock's `DEPENDENCIES` does not list it) hosted mode adds exactly one line at the end of the manifest, `gem "", "", source: "", require: false # added by socket-patch (transitive dependency)`, after one blank line, in the file's own line ending and keeping whether the file ends on one. `require: false` keeps `Bundler.require` from loading a gem it did not load before the line existed; the marker comment is what tells the unwind the whole line is socket-patch's. **The lock always follows** (the pair is what the Bundler that wrote the lock writes for that manifest, so frozen / deployment installs accept it as committed): on a lock written by Bundler ≥ 2.2 the gem's spec moves to a `GEM` section of its own whose `remote:` is the index URL (sections ordered as Bundler orders them); on a lock written by Bundler 1.17–2.1 the index URL joins the `remote:` lines of the one merged `GEM` section, in the order Bundler derives from the manifest's sources; the `DEPENDENCIES` entry keeps the requirement the manifest declares and gains `!` (a transitive gem gets ` (= )!`); and where the lock has a `CHECKSUMS` section the gem's entry is set to the patched artifact's sha256. A lock with no `CHECKSUMS` section (Bundler < 2.6) is converged the same way and pins the gem by source alone; the run reports that ONCE, naming the gems, as `redirect_gem_no_checksums_section`. **Precompiled platform gems**: a gem Bundler locks as platform builds has one lock entry per platform (`nokogiri (1.18.10-arm64-darwin)`, `nokogiri (1.18.10-x86_64-linux-gnu)`) and usually no ruby-platform `nokogiri (1.18.10)`. The patch registry serves a patched platform gem (a "prebuild": the upstream platform gem's name, gemspec and file list, with the patch's files replaced) for each platform the patch's grant lists (`registryOverride.identifiers.gemPlatforms`, `{platform, gemChecksumSha256}` each; absent or empty when it has none). When EVERY platform entry of the gem at the patched version has a prebuild there, the gem is wired like any other: the manifest edit is the same, every entry of that version (each spec line with its dependency sub-lines, verbatim and in the lock's order, plus a ruby-platform entry when one sits beside them) moves to the patch registry's `GEM` section, `DEPENDENCIES` is pinned the same way, and each `CHECKSUMS` entry of the gem is set to the sha256 of its own build (a platform entry to its prebuild's, the ruby-platform entry to `gemChecksumSha256`); a lock with no `CHECKSUMS` section gets none. A frozen `bundle install` of that pair fetches the one platform gem of the machine from the patch registry, compiles nothing and leaves the lock byte-identical (verified on Bundler 4.0.15). When a locked platform has no prebuild the gem is skipped with `redirect_gem_platform_unsupported`, which names the builds the lock holds, the ones the patch has no patched build for, and what the registry serves; so is a platform build in the merged layout of Bundler < 2.2. A lock does not record which Bundler installs it, only which one wrote it (`BUNDLED WITH`), so the pair is converged for that one; when it is the merged layout of Bundler < 2.2, which later Bundlers deprecate and from 2.5 on refuse under frozen / deployment mode, the run that writes the lock adds `redirect_gem_merged_lock_layout` naming the Bundler the pair is for. **Never a half-applied pair**: each gem is planned on a copy of the pair and committed only when the planned manifest and lock agree about it (the manifest gives it the index URL as its one source; the lock resolves it from a `GEM` section naming that remote, with a source-pinned `DEPENDENCIES` entry). A gem whose declaration cannot take the option, or whose lock cannot follow, is refused with neither file changed for it, and the warning's detail gives the reason and the way out: `redirect_gem_unrecognized_declaration` (the declaration cannot be edited in place — a heredoc or `do` block among its arguments, code before it on its line, a string spanning lines, a last argument that is not a literal and may be an options hash: it is taken for a version requirement only when the lock shows one requirement per positional argument, every other positional is a single quoted string, and the manifest has no `gemspec` directive, whose own requirement for the gem bundler folds into the lock entry, …), `redirect_gem_source_option` (it already selects a source: a `source:` / `git:` / `github:` / `path:` option or one a `**opts` splat may hold, a declaration inside a `source` / `git` / `github` / `path` block, a `DEPENDENCIES` entry that is already source-pinned, or a lock that resolves the gem from a `GIT` / `PATH` section), `redirect_gem_declared_more_than_once`, `redirect_gem_declaration_not_visible` (a direct dependency declared in an `eval_gemfile`d file, a loop or a gemspec; vendored mode refuses it for the same reason, so the way out is a literal `gem` line or `--mode agent`), `redirect_gem_dependency_not_locked` (declared, but the lock's `DEPENDENCIES` does not list it), `redirect_gem_lock_unconvergeable` (no `BUNDLED WITH` section to say which layout the lock's Bundler accepts, a merged Bundler < 2.2 section whose remotes the manifest's sources do not explain, or the one multi-remote `GEM` section Bundler 2.2 to 2.7 write for a manifest with more than one top-level `source` line, where the detail names that cause and the remedy: move each extra source into a `source "" do … end` block, then `bundle lock`), `redirect_gem_platform_unsupported` (a locked platform build the patch has no prebuild for, above) and `redirect_gem_inconsistent_plan` (the self-check above failed; a bug guard, never expected). A re-scan recognizes its own option (the grant-token and patch-uuid path levels of the URL rotate, so they are matched as wildcards) and refreshes the URL in place, in the manifest and the lock together; a re-scan of an unchanged project writes nothing. A lock reverted or regenerated without its manifest (the option still there, the lock back on the registry) is converged again by the next hosted scan. **Pins written by socket-patch 5.0 / 5.1** used a `source "" do … end` block in the declaration's place and, on a lock with no `CHECKSUMS` section, left the lock alone. That form is never written any more but stays recognized everywhere (re-scan, `list`, `vex`, `rollback` / `remove`, the takeovers): a re-scan keeps the block as it is, refreshes its URL like the option's, and converges a lock that never followed it; only where that lock cannot be converged does the run still warn `redirect_gem_frozen_install`. Human mode prints one line after the summary naming the declarations changed, e.g. ``Added `source:` to 3 gem declarations in Gemfile (puma, rack, and rexml); added 1 line for the transitive dependency nokogiri.`` **Update hold**: a gem wired this way has the patch registry as its only source, and that source serves the one patched version, so `bundle outdated` no longer lists the gem and `bundle update` cannot move it (a range requirement included) until its pin is rolled back. When a run newly wires at least one gem (an option appended or a line added, not a refreshed URL), human mode prints one more stdout line under that one, naming those gems once each: ``Bundler now takes rack from its Socket patch source only, which serves the patched version and no other: `bundle outdated` no longer lists it and `bundle update` cannot move it. To move it to a newer release, run `socket-patch rollback pkg:gem/rack@3.1.8`, then `bundle update rack`, then `socket-patch scan` again.`` The rollback step always names a purl (the gem's own for one gem, the shape `pkg:gem/@` for several), never a bare `rollback`, which would unwind every patch; after `get` the last step reads "then patch the new version the same way"; `--dry-run` words the first sentence as what the run would hold and prints no steps. `--json` and `--silent` output are unchanged (no warning code). Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. See `docs/ecosystems.md` ("Ruby gems: hosted mode") for the user-facing description. **Gem stale-install guard (the canonical narrative; other mentions point here)**: the gem hosted rewrite is pure Gemfile/lock text, and Bundler keeps a gem it already holds whatever source the lock names. So after the rewrite a hosted run looks for the gems the project already has on disk, replaces the project's own stale copies with the patched gem itself, and warns about the rest. The unwind (`rollback`, `remove`, a withdrawn-patch restore) does the same in the other direction. Exit code and `status` never change: a refresh that cannot be done leaves everything as it was and falls back to the warning. @@ -2329,7 +2329,7 @@ command's integration tests check its output. | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | | `redirect_gem_source_option` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem already has a source of its own (an option on its declaration, an enclosing `source` / `git` / `github` / `path` block, a source-pinned `DEPENDENCIES` entry, or a `GIT` / `PATH` lock section) and Bundler allows one per gem. The gem is skipped, nothing written for it. When the source is socket-patch's own vendored `path:`, the detail names the un-vendor step instead. | | `redirect_gem_dependency_not_locked` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the manifest declares the gem but the lock's `DEPENDENCIES` does not list it (an out-of-date lock, or a conditional declaration). The gem is skipped, nothing written for it; run `bundle lock` and re-run. | -| `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). | +| `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to move each extra source into a `source "" do … end` block, run `bundle lock` and re-run, or `--mode agent`; it does not print the source URLs. | | `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch has no patched platform gem ("prebuild", the grant's `gemPlatforms`) for at least one of them, or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds, the ones with no prebuild and what the patch registry serves. The gem is skipped and the manifest and lock stay byte-identical for it. With a prebuild for every locked platform the gem is redirected and no warning is given. | | `redirect_gem_inconsistent_plan` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the rewriter's self-check found the planned manifest and lock disagreeing about the gem, a pair Bundler refuses frozen. Nothing is written for it. Not expected; report it. | | `redirect_gem_frozen_install` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): a pin socket-patch 5.0 / 5.1 wrote as a `source … do` block sits beside a lock that still records the upstream source and that this run changed but could not converge; Bundler rejects the pair under frozen / deployment mode until an unfrozen `bundle install` records the source. Never raised for the `source:` option form, whose lock always follows. | diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index d4722593c..27ae623c7 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -511,6 +511,13 @@ enum Driver { /// [`Driver::ScanVexSourceBlock`] whose `source … do` follows another /// statement and a `;` on its line (#1531). ScanVexSourceBlockAfterSemicolon, + /// [`Driver::ScanVex`] on a Gemfile with a second top-level `source` + /// line (#2162). Bundler 2.2 to 2.7 lock such a Gemfile into ONE `GEM` + /// section naming both remotes, which `bundle lock` writes again as it + /// is: the run refuses the gem, names the Gemfile's sources as the + /// cause, and the remedy it prescribes (the second source in a block, + /// `bundle lock`) makes the next scan wire the gem. + ScanVexTwoGlobalSources, /// A heredoc option continues beyond the declaration's physical line. ScanVexHeredocDeclaration, /// A double-quoted interpolation can itself contain a heredoc opener. @@ -605,6 +612,9 @@ impl Driver { Driver::ScanVexTwin => "scan --mode hosted (Gemfile + gems.rb twin)", Driver::ScanVexGroupBlock => "scan --mode hosted (gem in a group block)", Driver::ScanVexSourceBlock => "scan --mode hosted (gem in a source block)", + Driver::ScanVexTwoGlobalSources => { + "scan --mode hosted (Gemfile with two top-level sources)" + } Driver::ScanVexSourceBlockAssignment => { "scan --mode hosted (gem in a source block after `v = if … end`)" } @@ -740,6 +750,11 @@ async fn redirect_scanned_project( { Some("custom lockfiles need bundler >= 4") } + // Before 2.2 the lock is the merged layout anyway; bundler 4 + // refuses the Gemfile. + Driver::ScanVexTwoGlobalSources if !bundler.at_least(2, 2) || bundler.at_least(4, 0) => { + Some("a Gemfile with two top-level sources is locked into one multi-remote GEM section by bundler 2.2 to 2.7 only") + } _ => None, }; if let Some(why) = only { @@ -919,6 +934,30 @@ async fn redirect_scanned_project( "source \"{up}/upstream\"\n\nsource \"{up}/upstream\" do\n gem \"{DEP}\", \"{DEP_VERSION}\"\nend\n", up = server.uri() ), + Driver::ScanVexTwoGlobalSources => { + // A second gem server with a gem of its own, as a private + // server beside rubygems.org has. + let gem = build_gem( + &stage, + SECOND_SOURCE_GEM, + "1.0.0", + "second_only.rb", + TINY_LIB, + &[], + ); + let second = IndexGem { + name: SECOND_SOURCE_GEM, + version: "1.0.0", + deps: vec![], + gem, + }; + mount_compact_index(&server, "/second", &[second]).await; + format!( + "source \"{up}/upstream\"\nsource \"{up}/second\"\n\ngem \"{DEP}\"\n\ + gem \"{SECOND_SOURCE_GEM}\"\n", + up = server.uri() + ) + } Driver::ScanVexSourceBlockAssignment => format!( "source \"{up}/upstream\"\n\nsource \"{up}/upstream\" do\n v = if ENV[\"ZZ\"]\n \"a\"\n \ else\n \"b\"\n end\n w = case ENV[\"ZZ\"]\n when \"x\" then \"a\"\n \ @@ -1211,6 +1250,7 @@ async fn redirect_scanned_project( | Driver::ScanVexEvalGemfile | Driver::ScanVexGroupBlock | Driver::ScanVexSourceBlock + | Driver::ScanVexTwoGlobalSources | Driver::ScanVexSourceBlockAssignment | Driver::ScanVexSourceBlockMultiLineOpener | Driver::ScanVexSourceBlockBraces @@ -1329,6 +1369,7 @@ async fn redirect_scanned_project( | Driver::ScanVexSourceBlockMultiLineOpener | Driver::ScanVexSourceBlockBraces | Driver::ScanVexSourceBlockAfterSemicolon => Some("redirect_gem_source_option"), + Driver::ScanVexTwoGlobalSources => Some("redirect_gem_lock_unconvergeable"), Driver::ScanVexHeredocDeclaration | Driver::ScanVexInterpolatedHeredocDeclaration => { Some("redirect_gem_unrecognized_declaration") } @@ -1348,6 +1389,9 @@ async fn redirect_scanned_project( &pristine_gemfile, &pristine_lock, ); + if driver == Driver::ScanVexTwoGlobalSources { + assert_two_global_sources_remedy_wires(&proj, &api, &index_url, &lock_before, &stdout); + } return None; } assert_eq!( @@ -1449,6 +1493,7 @@ async fn redirect_scanned_project( | Driver::ScanVexMirrorAllEnv | Driver::ScanVexCustomGitSource | Driver::ScanVexSourceBlock + | Driver::ScanVexTwoGlobalSources | Driver::ScanVexSourceBlockAssignment | Driver::ScanVexSourceBlockMultiLineOpener | Driver::ScanVexSourceBlockBraces @@ -1593,6 +1638,108 @@ fn assert_unwirable_declaration_redirects_nothing( ); } +/// The gem only the second source of [`Driver::ScanVexTwoGlobalSources`] +/// serves. +const SECOND_SOURCE_GEM: &str = "second_only"; + +/// #2162, after the refused scan of [`Driver::ScanVexTwoGlobalSources`]: +/// the fixture lock is the one multi-remote `GEM` section the report is +/// about and `bundle lock` leaves it alone; the warning names the Gemfile's +/// top-level sources and the block remedy, never an old bundler or +/// vendored mode; and that remedy works: with the second source in a +/// block, `bundle lock` gives each source a section, the next scan wires +/// the gem, and bundler installs the pair frozen. +fn assert_two_global_sources_remedy_wires( + proj: &Path, + api: &str, + index_url: &str, + lock_before: &str, + refused_stdout: &str, +) { + assert_eq!(gem_remotes(lock_before).len(), 2, "{lock_before}"); + assert_eq!( + lock_before.matches("GEM\n").count(), + 1, + "one GEM section names both remotes:\n{lock_before}" + ); + let relock = bundle(proj, &["lock"]); + assert!(relock.status.success(), "bundle lock failed"); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock_before, + "`bundle lock` leaves the two-remote lock as it is" + ); + for said in [ + "Gemfile has 2 top-level `source` lines", + "do … end` block", + "--mode agent", + ] { + assert!( + refused_stdout.contains(said), + "the warning says {said:?}:\n{refused_stdout}" + ); + } + for unsaid in ["bundler < 2.2", "--mode vendored"] { + assert!( + !refused_stdout.contains(unsaid), + "the warning must not say {unsaid:?}:\n{refused_stdout}" + ); + } + + // The remedy the warning names. + let gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + let second = gemfile + .lines() + .nth(1) + .filter(|line| line.starts_with("source \"") && line.ends_with("/second\"")) + .unwrap_or_else(|| panic!("the second top-level source: {gemfile}")); + let own_gem = format!("gem \"{SECOND_SOURCE_GEM}\"\n"); + assert!(gemfile.ends_with(&own_gem), "{gemfile}"); + let remedied = format!( + "{}\n{second} do\n {own_gem}end\n", + gemfile + .replacen(&format!("{second}\n"), "", 1) + .replacen(&own_gem, "", 1) + ); + std::fs::write(proj.join("Gemfile"), &remedied).unwrap(); + let relock = bundle(proj, &["lock"]); + assert!( + relock.status.success(), + "bundle lock over the remedied Gemfile failed:\n{}", + String::from_utf8_lossy(&relock.stderr) + ); + // The install the helper above ran is stale for the scan to come. + std::fs::remove_dir_all(proj.join("vendor")).expect("remove the materialization"); + let (code, stdout, stderr) = run_hosted_scan(proj, api); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + !stdout.contains("redirect_gem_lock_unconvergeable"), + "the remedied project is wired:\n{stdout}" + ); + let wired = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert_eq!( + wired, + with_source_option(&remedied, &format!("gem \"{DEP}\""), index_url), + "the declaration gains the `source:` option" + ); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!( + gem_remotes(&lock).contains(&index_url), + "the lock records the patch source:\n{lock}" + ); + let install = bundle_env(proj, &["install"], &[("BUNDLE_FROZEN", "true")]); + assert!( + install.status.success(), + "a frozen install must accept the wired pair:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + assert_eq!( + std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(), + lock, + "the frozen install leaves the lock alone" + ); +} + /// The contract of a hosted scan that must refuse every gem: #749's /// `custom.lock` named in `.bundle/config` (bundler 4), or #751's /// `Gemfile` + `gems.rb` twin. The scan reports `refusal`, redirects and @@ -3733,6 +3880,29 @@ async fn gem_hosted_gem_in_a_user_source_block_is_refused_and_still_installs() { } } +/// #2162: a Gemfile with two top-level `source` lines, which bundler 2.2 to +/// 2.7 lock into one `GEM` section with two remotes. The scan refuses the +/// gem and leaves the project installable, as for any lock it cannot +/// follow; the warning names the two top-level sources and the remedy +/// (the second source in a block, `bundle lock`), and after that remedy +/// the same scan wires the gem and bundler installs it frozen. See +/// [`assert_two_global_sources_remedy_wires`]. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "host capstone: shells out to a real ruby/gem/bundler (2.2 to 2.7 for this arm); \ + the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] +async fn gem_hosted_two_top_level_sources_are_refused_with_the_block_remedy() { + let fx = redirect_scanned_project( + "two-global-sources", + Spelling::Gemfile, + false, + true, + None, + Driver::ScanVexTwoGlobalSources, + ) + .await; + assert!(fx.is_none(), "the driver asserts in place"); +} + /// A pin socket-patch 5.0 / 5.1 wrote: the declaration replaced by a /// `source "" do … end` block declaring the exact version, the /// lock (one without CHECKSUMS) left on the registry — the pair a frozen diff --git a/crates/socket-patch-core/src/formats/gem/declarations.rs b/crates/socket-patch-core/src/formats/gem/declarations.rs index 3250e5cc9..b3e3117f9 100644 --- a/crates/socket-patch-core/src/formats/gem/declarations.rs +++ b/crates/socket-patch-core/src/formats/gem/declarations.rs @@ -647,9 +647,56 @@ fn remove_line(lines: &mut Vec, k: usize) { /// that is not a plain string literal is left out, so a caller must check /// the answer against the lock bundler wrote before relying on it. pub(crate) fn rubygems_sources(text: &str) -> Vec { + let (global, mut scoped) = source_calls(text); + for decl in declarations(text).literal { + if let Some((arg, Some(url))) = decl.source() { + scoped.push((arg.start, url.to_string())); + } + } + scoped.sort_by_key(|(at, _)| *at); + let mut out: Vec = Vec::new(); + let same = super::same_remote; + for url in global { + if !out.iter().any(|seen| same(seen, &url)) { + out.push(url); + } + } + let globals = out.len(); + for (_, url) in scoped { + if out[..globals].iter().any(|seen| same(seen, &url)) { + continue; + } + // Bundler moves a source it meets again to the end. + out.retain(|seen| !same(seen, &url)); + out.push(url); + } + out +} + +/// The top-level sources of a manifest: each `source ""` call with no +/// block, in file order, one written twice counted once. Bundler 2.2 to 2.7 +/// lock a manifest with more than one of them into ONE `GEM` section that +/// names them all (and deprecate it; bundler 4 refuses the manifest). A +/// source that is not a plain string literal is left out. +pub(crate) fn global_rubygems_sources(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for url in source_calls(text).0 { + if !out.iter().any(|seen| super::same_remote(seen, &url)) { + out.push(url); + } + } + out +} + +/// The sources [`source_calls`] reads off a manifest's `source` calls: the +/// url of each call with no block, then `(byte offset, url)` of each call +/// with one. +type SourceCalls = (Vec, Vec<(usize, String)>); + +/// The literal `source ""` calls of a manifest, in file order. +fn source_calls(text: &str) -> SourceCalls { let masked = masked_source(text); let mut global: Vec = Vec::new(); - // (byte offset, url) of each block or option source. let mut scoped: Vec<(usize, String)> = Vec::new(); for (word, start, end) in ruby_words(&masked) { if word != "source" { @@ -692,29 +739,7 @@ pub(crate) fn rubygems_sources(text: &str) -> Vec { scoped.push((start, value.to_string())); } } - for decl in declarations(text).literal { - if let Some((arg, Some(url))) = decl.source() { - scoped.push((arg.start, url.to_string())); - } - } - scoped.sort_by_key(|(at, _)| *at); - let mut out: Vec = Vec::new(); - let same = super::same_remote; - for url in global { - if !out.iter().any(|seen| same(seen, &url)) { - out.push(url); - } - } - let globals = out.len(); - for (_, url) in scoped { - if out[..globals].iter().any(|seen| same(seen, &url)) { - continue; - } - // Bundler moves a source it meets again to the end. - out.retain(|seen| !same(seen, &url)); - out.push(url); - } - out + (global, scoped) } #[cfg(test)] @@ -1028,6 +1053,24 @@ mod tests { assert!(!is_added_line(&text, &one(&text))); } + /// Only a `source ""` call with no block is a top-level source; + /// one written twice (a trailing slash apart) counts once. + #[test] + fn global_rubygems_sources_are_the_blockless_source_calls() { + let text = "source \"https://rubygems.org\"\r\n\ + source('https://second.example/')\r\n\ + source \"https://rubygems.org/\"\r\n\ + # source \"https://commented.example\"\r\n\ + source COMPUTED\r\n\ + source \"https://block.example\" do\r\n gem \"c\"\r\nend\r\n\ + gem \"a\", source: \"https://a.example/\"\r\n"; + assert_eq!( + global_rubygems_sources(text), + ["https://rubygems.org", "https://second.example/"] + ); + assert!(global_rubygems_sources("gem \"a\"\n").is_empty()); + } + /// Bundler < 2.2 lists the global sources first, then each block or /// option source in the order it last meets it. #[test] diff --git a/crates/socket-patch-core/src/formats/gem/hosted.rs b/crates/socket-patch-core/src/formats/gem/hosted.rs index 2d484bf91..586c967ee 100644 --- a/crates/socket-patch-core/src/formats/gem/hosted.rs +++ b/crates/socket-patch-core/src/formats/gem/hosted.rs @@ -531,6 +531,20 @@ pub(crate) fn lock_layout(lock: &str) -> Option { } } +/// How many remotes the `GEM` section that locks `dep` names, when it names +/// more than one: the section [`converge_gem_lock_source`] refuses, since +/// no spec of it can be given a source of its own. +pub(crate) fn shared_gem_section_remotes(lock: &str, dep: &DepOverride) -> Option { + let model = super::parse(lock); + let section = model.gem_sections().find(|section| { + section + .specs + .iter() + .any(|spec| spec.locks(&dep.name, &dep.version)) + })?; + (section.remotes.len() > 1).then_some(section.remotes.len()) +} + /// Converge a bundler < 2.2 lock ([`LockLayout::Merged`]) for one /// redirected dep: the patch registry joins the `remote:` lines of the /// lock's one `GEM` section and DEPENDENCIES source-pins the gem as `pin` diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index be0cd1aae..d56aaecfe 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -68,7 +68,8 @@ use crate::formats::cargo::{is_crates_io_patch_table, is_crates_io_source, Cargo use crate::formats::composer::hosted::rewrite_composer_lock; use crate::formats::gem::hosted::{ bundled_before_2_2, checksum_entry_span, converge_gem_lock_source, lock_layout, - merge_gem_lock_remote, refresh_merged_gem_lock_remote, DependencyPin, LockLayout, + merge_gem_lock_remote, refresh_merged_gem_lock_remote, shared_gem_section_remotes, + DependencyPin, LockLayout, }; use crate::formats::gem::locked_specs as gem_locked_specs; use crate::formats::maven::declared_maven::DeclaredMaven; @@ -8398,6 +8399,35 @@ fn plan_gem_redirect( &mut staged, ) .map_err(|why| { + // A lock this bundler wrote for a manifest with several + // top-level sources: `bundle lock` writes the same lock + // again, so the way out is the manifest (#2162). The + // urls stay out of the text: a source can carry + // credentials. Vendored mode is not offered: it refuses + // a gem in a `group` block or with a native extension, + // which this plan cannot tell. + let globals = declarations::global_rubygems_sources(&gf).len(); + if let Some(remotes) = + shared_gem_section_remotes(&lk, dep).filter(|_| globals > 1) + { + return refuse( + "redirect_gem_lock_unconvergeable", + format!( + "{gemfile_name} has {globals} top-level `source` lines, and \ + for such a manifest bundler locks every gem in one GEM \ + section that names every source ({lock_name} lists \ + {remotes} remotes over `{name} ({})`), where no gem can be \ + given the Socket source alone; nothing was changed for \ + {name} — keep one top-level `source` line and move each \ + other one into a `source \"\" do … end` block around \ + the gems that come from it (bundler's own deprecation \ + warning asks for the same), then run `bundle lock`, commit \ + {gemfile_name} and {lock_name} and re-run the hosted scan, \ + or patch {name} with `--mode agent`", + dep.version + ), + ); + } refuse( "redirect_gem_lock_unconvergeable", format!( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 236ad6665..a7ce3bf4a 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2183,7 +2183,7 @@ wire is skipped, neither file changes for it, and the warning says why and what | `redirect_gem_declared_more_than_once` | the Gemfile declares it more than once. Merge the declarations into one. | | `redirect_gem_declaration_not_visible` | the lock lists it as a direct dependency, but it is declared where the scan cannot edit: an `eval_gemfile`d file, a loop, a gemspec. Declare it with a literal `gem ""` line in the Gemfile, in place of any other `gem` call that declares it (a gemspec's development dependency stays), or patch it with `--mode agent`. Vendored mode refuses it for the same reason. | | `redirect_gem_dependency_not_locked` | the Gemfile declares it and the lock's `DEPENDENCIES` does not list it. Run `bundle lock` and re-run. | -| `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. | +| `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. Also a Gemfile with more than one top-level `source` line: Bundler 2.2 to 2.7 lock all its gems in one `GEM` section that names every source, where no gem can be given the patch source alone, and `bundle lock` writes the same lock again. Keep one top-level `source` and move each other one into a `source "" do … end` block around the gems that come from it (Bundler's own deprecation warning asks for the same), then run `bundle lock` and re-run; or use `--mode agent`. | | `redirect_gem_platform_unsupported` | the lock holds a platform-specific build of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) that the patch has no patched build for. The warning names the builds the lock holds, the ones that are missing, and what the patch registry serves. See "Precompiled platform gems" below. | `--mode agent` can still patch a gem hosted mode skips. `--mode vendored` can too, unless it From 425bcbdf7672bc55c6665dc27a0be309792b3ccb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:20:37 +0000 Subject: [PATCH 4/4] Gate the multi-source warning on the real cause Review follow-ups for the warning on a Gemfile with several top-level sources: - Count every block-less `source` call outside any other construct, a computed URL included, so a second source read from ENV gets the remedy too. A `source` in a conditional or with a trailing modifier is not counted: Bundler may never run it. - Take the new wording only when the multi-remote section is why the lock was refused; any other reason is still reported as it is. - Say hosted mode does not rewrite that lock, not that it cannot be done, and tell the user to keep the patched gem's source top-level. - Bundler 2.2.15 and 2.2.18 keep the one section on `bundle lock` after the Gemfile is fixed (2.2.25 and later split it), so a lock written by an early 2.2 release names a Bundler that splits it. Refs #2162 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/formats/gem/declarations.rs | 170 +++++++++++------- .../src/formats/gem/hosted.rs | 106 ++++++++--- .../src/patch/redirect/mod.rs | 105 ++++++++--- docs/ecosystems.md | 2 +- 5 files changed, 275 insertions(+), 110 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8bc7496b1..95f1abb8c 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2329,7 +2329,7 @@ command's integration tests check its output. | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | | `redirect_gem_source_option` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem already has a source of its own (an option on its declaration, an enclosing `source` / `git` / `github` / `path` block, a source-pinned `DEPENDENCIES` entry, or a `GIT` / `PATH` lock section) and Bundler allows one per gem. The gem is skipped, nothing written for it. When the source is socket-patch's own vendored `path:`, the detail names the un-vendor step instead. | | `redirect_gem_dependency_not_locked` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the manifest declares the gem but the lock's `DEPENDENCIES` does not list it (an out-of-date lock, or a conditional declaration). The gem is skipped, nothing written for it; run `bundle lock` and re-run. | -| `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to move each extra source into a `source "" do … end` block, run `bundle lock` and re-run, or `--mode agent`; it does not print the source URLs. | +| `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to keep the source that serves the gem as the one top-level `source`, move each other one into a `source "" do … end` block, run `bundle lock` (with Bundler 2.2.25 or later, which the detail says when the lock was written by an earlier 2.2 release, since those keep the one section) and re-run, or `--mode agent`; it does not print the source URLs. The gate counts block-less `source` calls outside every other construct, a computed URL included; a `source` inside a conditional is not counted and keeps the generic detail. | | `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the patch has no patched platform gem ("prebuild", the grant's `gemPlatforms`) for at least one of them, or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds, the ones with no prebuild and what the patch registry serves. The gem is skipped and the manifest and lock stay byte-identical for it. With a prebuild for every locked platform the gem is redirected and no warning is given. | | `redirect_gem_inconsistent_plan` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the rewriter's self-check found the planned manifest and lock disagreeing about the gem, a pair Bundler refuses frozen. Nothing is written for it. Not expected; report it. | | `redirect_gem_frozen_install` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): a pin socket-patch 5.0 / 5.1 wrote as a `source … do` block sits beside a lock that still records the upstream source and that this run changed but could not converge; Bundler rejects the pair under frozen / deployment mode until an unfrozen `bundle install` records the source. Never raised for the `source:` option form, whose lock always follows. | diff --git a/crates/socket-patch-core/src/formats/gem/declarations.rs b/crates/socket-patch-core/src/formats/gem/declarations.rs index b3e3117f9..7122e2d30 100644 --- a/crates/socket-patch-core/src/formats/gem/declarations.rs +++ b/crates/socket-patch-core/src/formats/gem/declarations.rs @@ -28,7 +28,7 @@ use super::gemfile::NON_SOURCE_KEYS; use super::is_plain_gem_token; -use super::ruby::{is_ident_byte, masked_source, ruby_words, source_call_args}; +use super::ruby::{block_stack, is_ident_byte, masked_source, ruby_words, source_call_args}; use crate::utils::line_endings; /// The trailing comment of a line the hosted rewriter ADDED for a gem the @@ -647,7 +647,51 @@ fn remove_line(lines: &mut Vec, k: usize) { /// that is not a plain string literal is left out, so a caller must check /// the answer against the lock bundler wrote before relying on it. pub(crate) fn rubygems_sources(text: &str) -> Vec { - let (global, mut scoped) = source_calls(text); + let masked = masked_source(text); + let mut global: Vec = Vec::new(); + // (byte offset, url) of each block or option source. + let mut scoped: Vec<(usize, String)> = Vec::new(); + for (word, start, end) in ruby_words(&masked) { + if word != "source" { + continue; + } + let line_start = masked[..start].rfind('\n').map_or(0, |i| i + 1); + let lead = masked[line_start..start].trim(); + let Some(paren) = source_call_args(&masked[end..]) else { + continue; + }; + if !(lead.is_empty() || lead.ends_with(';')) { + continue; + } + let line_end = masked[end..].find('\n').map_or(masked.len(), |i| end + i); + // Past the `(` or the blank that follows the word. + let args = &masked[end + 1..line_end]; + let arg_at = end + 1 + (args.len() - args.trim_start().len()); + let Some(url) = masked[arg_at..line_end] + .chars() + .next() + .filter(|q| matches!(q, '"' | '\'')) + .and_then(|q| masked[arg_at + 1..line_end].find(q)) + .map(|len| (arg_at + 1, arg_at + 1 + len)) + else { + continue; + }; + let value = &text[url.0..url.1]; + if value.contains('\\') || value.contains("#{") { + continue; + } + let rest = masked[url.1 + 1..line_end].trim_start(); + let rest = if paren { + rest.strip_prefix(')').unwrap_or(rest).trim_start() + } else { + rest + }; + if rest.is_empty() || rest.starts_with(';') { + global.push(value.to_string()); + } else if rest.starts_with("do") || rest.starts_with('{') { + scoped.push((start, value.to_string())); + } + } for decl in declarations(text).literal { if let Some((arg, Some(url))) = decl.source() { scoped.push((arg.start, url.to_string())); @@ -673,31 +717,20 @@ pub(crate) fn rubygems_sources(text: &str) -> Vec { out } -/// The top-level sources of a manifest: each `source ""` call with no -/// block, in file order, one written twice counted once. Bundler 2.2 to 2.7 -/// lock a manifest with more than one of them into ONE `GEM` section that -/// names them all (and deprecate it; bundler 4 refuses the manifest). A -/// source that is not a plain string literal is left out. -pub(crate) fn global_rubygems_sources(text: &str) -> Vec { - let mut out: Vec = Vec::new(); - for url in source_calls(text).0 { - if !out.iter().any(|seen| super::same_remote(seen, &url)) { - out.push(url); - } - } - out -} - -/// The sources [`source_calls`] reads off a manifest's `source` calls: the -/// url of each call with no block, then `(byte offset, url)` of each call -/// with one. -type SourceCalls = (Vec, Vec<(usize, String)>); - -/// The literal `source ""` calls of a manifest, in file order. -fn source_calls(text: &str) -> SourceCalls { +/// How many top-level sources a manifest declares: its `source ` +/// calls that take no block and sit outside every other construct, a +/// literal url written twice counted once. Bundler 2.2 to 2.7 lock a +/// manifest with more than one of them into ONE `GEM` section that names +/// them all (and deprecate it; bundler 4 refuses the manifest). +/// +/// A url that is computed counts too, since only the number matters. A +/// call inside an `if`, a `group` or any other construct does not (bundler +/// may never run it), nor does one whose arguments run past its line: the +/// count is a floor, for a caller that words a diagnosis with it. +pub(crate) fn top_level_source_count(text: &str) -> usize { let masked = masked_source(text); - let mut global: Vec = Vec::new(); - let mut scoped: Vec<(usize, String)> = Vec::new(); + let mut literal: Vec<&str> = Vec::new(); + let mut computed = 0; for (word, start, end) in ruby_words(&masked) { if word != "source" { continue; @@ -711,35 +744,35 @@ fn source_calls(text: &str) -> SourceCalls { continue; } let line_end = masked[end..].find('\n').map_or(masked.len(), |i| end + i); + let call = masked[end..line_end].trim_end(); + // A block (`do`, `do |x|`, `{`), a trailing modifier (`… if x`), + // or arguments that go on: not known to be a top-level source. + let qualified = call.contains('{') + || ruby_words(call).any(|(word, _, _)| { + matches!(word, "do" | "if" | "unless" | "while" | "until" | "rescue") + }) + || (paren && !call.contains(')')) + || call.ends_with([',', '\\']); + if qualified || !block_stack(text, line_start).is_empty() { + continue; + } // Past the `(` or the blank that follows the word. let args = &masked[end + 1..line_end]; let arg_at = end + 1 + (args.len() - args.trim_start().len()); - let Some(url) = masked[arg_at..line_end] + let url = masked[arg_at..line_end] .chars() .next() .filter(|q| matches!(q, '"' | '\'')) .and_then(|q| masked[arg_at + 1..line_end].find(q)) - .map(|len| (arg_at + 1, arg_at + 1 + len)) - else { - continue; - }; - let value = &text[url.0..url.1]; - if value.contains('\\') || value.contains("#{") { - continue; - } - let rest = masked[url.1 + 1..line_end].trim_start(); - let rest = if paren { - rest.strip_prefix(')').unwrap_or(rest).trim_start() - } else { - rest - }; - if rest.is_empty() || rest.starts_with(';') { - global.push(value.to_string()); - } else if rest.starts_with("do") || rest.starts_with('{') { - scoped.push((start, value.to_string())); + .map(|len| &text[arg_at + 1..arg_at + 1 + len]) + .filter(|url| !url.contains('\\') && !url.contains("#{")); + match url { + Some(url) if literal.iter().any(|seen| super::same_remote(seen, url)) => {} + Some(url) => literal.push(url), + None => computed += 1, } } - (global, scoped) + literal.len() + computed } #[cfg(test)] @@ -1053,22 +1086,37 @@ mod tests { assert!(!is_added_line(&text, &one(&text))); } - /// Only a `source ""` call with no block is a top-level source; - /// one written twice (a trailing slash apart) counts once. + /// Only a block-less `source` call outside every construct is a + /// top-level source; a literal url written twice (a trailing slash + /// apart) counts once, a computed one counts. #[test] - fn global_rubygems_sources_are_the_blockless_source_calls() { - let text = "source \"https://rubygems.org\"\r\n\ - source('https://second.example/')\r\n\ - source \"https://rubygems.org/\"\r\n\ - # source \"https://commented.example\"\r\n\ - source COMPUTED\r\n\ - source \"https://block.example\" do\r\n gem \"c\"\r\nend\r\n\ - gem \"a\", source: \"https://a.example/\"\r\n"; - assert_eq!( - global_rubygems_sources(text), - ["https://rubygems.org", "https://second.example/"] - ); - assert!(global_rubygems_sources("gem \"a\"\n").is_empty()); + fn top_level_source_count_is_the_blockless_calls_outside_any_construct() { + let two = "source \"https://rubygems.org\"\r\n\ + source('https://second.example/')\r\n\ + source \"https://rubygems.org/\"\r\n\ + # source \"https://commented.example\"\r\n\ + source \"https://block.example\" do\r\n gem \"c\"\r\nend\r\n\ + source(\"https://brace.example\") { gem \"d\" }\r\n\ + gem \"a\", source: \"https://a.example/\"\r\n"; + assert_eq!(top_level_source_count(two), 2); + // A computed url is a source all the same. + for computed in [ + "source \"https://rubygems.org\"\nsource ENV[\"GEM_SOURCE\"]\n", + "source \"https://rubygems.org\"\nsource \"https://#{ENV['TOKEN']}@gems.acme.example/\"\n", + "source 'https://rubygems.org'; source PRIVATE_SOURCE\n", + ] { + assert_eq!(top_level_source_count(computed), 2, "{computed}"); + } + // Bundler runs one branch of a conditional, and maybe none. + for one in [ + "if ENV['MIRROR']\n source \"https://mirror.example\"\nelse\n source \"https://rubygems.org\"\nend\n", + "source \"https://rubygems.org\"\nsource \"https://mirror.example\" if ENV['MIRROR']\n", + "source \"https://rubygems.org\"\nsource(\n \"https://block.example\"\n) do\n gem \"c\"\nend\n", + "source \"https://rubygems.org\"\nsource = \"https://not-a-call.example\"\n", + ] { + assert!(top_level_source_count(one) < 2, "{one}"); + } + assert_eq!(top_level_source_count("gem \"a\"\n"), 0); } /// Bundler < 2.2 lists the global sources first, then each block or diff --git a/crates/socket-patch-core/src/formats/gem/hosted.rs b/crates/socket-patch-core/src/formats/gem/hosted.rs index 586c967ee..53864750c 100644 --- a/crates/socket-patch-core/src/formats/gem/hosted.rs +++ b/crates/socket-patch-core/src/formats/gem/hosted.rs @@ -160,6 +160,32 @@ fn pin_dependency<'a>( } } +/// Why [`converge_gem_lock_source`] left a lock alone. +#[derive(Debug)] +pub(crate) struct LockRefusal { + /// The reason, worded to follow "the lock cannot record the source (…)". + pub(crate) why: String, + /// How many remotes the `GEM` section that locks the gem names, when + /// that is the reason: no older bundler wrote it if the manifest has + /// several top-level sources, which bundler 2.2 to 2.7 lock that way. + pub(crate) shared_remotes: Option, +} + +impl From for LockRefusal { + fn from(why: String) -> Self { + LockRefusal { + why, + shared_remotes: None, + } + } +} + +impl std::fmt::Display for LockRefusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.why) + } +} + /// Converge the lock's source attribution for one redirected dep so the /// Gemfile + lock pair is what bundler >= 2.2 itself writes after an /// install from the redirected Gemfile (verified byte for byte against @@ -200,7 +226,7 @@ pub(crate) fn converge_gem_lock_source( pin: DependencyPin<'_>, lock_changed: &mut bool, result: &mut RewriteResult, -) -> Result<(), String> { +) -> Result<(), LockRefusal> { let eol = crate::utils::line_endings::terminator(lk); // Borrowed until edited: most of a large lock's lines are only moved. let mut lines: Vec> = lk.split_inclusive('\n').map(Cow::Borrowed).collect(); @@ -221,10 +247,10 @@ pub(crate) fn converge_gem_lock_source( }) .collect(); let Some(deps) = &model.dependencies else { - return Err("it has no DEPENDENCIES section".to_string()); + return Err("it has no DEPENDENCIES section".to_string().into()); }; let Some(&(sec_idx, _, _)) = spec_at.first() else { - return Err(format!("no GEM section lists `{spec_raw}`")); + return Err(format!("no GEM section lists `{spec_raw}`").into()); }; if let Some((_, _, twice)) = spec_at .iter() @@ -232,22 +258,27 @@ pub(crate) fn converge_gem_lock_source( .find(|(at, (_, _, raw))| spec_at[..*at].iter().any(|(_, _, earlier)| earlier == raw)) .map(|(_, entry)| entry) { - return Err(format!("more than one GEM section lists `{twice}`")); + return Err(format!("more than one GEM section lists `{twice}`").into()); } if spec_at.iter().any(|(k, _, _)| *k != sec_idx) { return Err(format!( "the builds of {} {} are spread over more than one GEM section", dep.name, dep.version - )); + ) + .into()); } // Exclusive of the header. let deps_start = deps.line_no; if sections[sec_idx].remotes.len() != 1 { - return Err(format!( - "the GEM section that lists `{spec_raw}` names {} remotes (the one-section layout \ - of bundler < 2.2, which a later bundler rewrites on its next unfrozen install)", - sections[sec_idx].remotes.len() - )); + let remotes = sections[sec_idx].remotes.len(); + return Err(LockRefusal { + why: format!( + "the GEM section that lists `{spec_raw}` names {remotes} remotes (the \ + one-section layout of bundler < 2.2, which a later bundler rewrites on its \ + next unfrozen install)" + ), + shared_remotes: (remotes > 1).then_some(remotes), + }); } // Bundler always writes source sections before DEPENDENCIES — the pin // edit below runs first on that premise (its lines sit after the parsed @@ -258,7 +289,8 @@ pub(crate) fn converge_gem_lock_source( if deps_start < sections[sec_idx].end { return Err(format!( "its DEPENDENCIES section comes before the GEM section that lists `{spec_raw}`" - )); + ) + .into()); } let remote_idx = sections[sec_idx].remote_line_nos[0] - 1; let remote_url = sections[sec_idx].remotes[0].to_string(); @@ -475,6 +507,18 @@ pub(crate) fn bundled_before_2_2(lock: &str) -> bool { bundled_with(lock).is_some_and(|version| version < (2, 2)) } +/// The version of the lock's bundler when it is a 2.2 release that keeps a +/// multi-remote `GEM` section as one on `bundle lock`, even after the +/// manifest stops declaring several top-level sources. Run against the +/// real thing: 2.2.15 and 2.2.18 keep it (and say so on `bundle install`), +/// 2.2.25, 2.2.29, 2.2.31, 2.2.33 and 2.5.22 split it. The releases between +/// 2.2.18 and 2.2.25 are taken to keep it. +pub(crate) fn bundler_keeps_merged_section(lock: &str) -> Option<&str> { + let (version, text) = bundled_with_version(lock)?; + let patch = text.split('.').nth(2)?.parse::().ok()?; + (version == (2, 2) && patch < 25).then_some(text) +} + /// The `major.minor` of the bundler the lock's `BUNDLED WITH` names, and /// the version as written. fn bundled_with_version(lock: &str) -> Option<((u32, u32), &str)> { @@ -531,20 +575,6 @@ pub(crate) fn lock_layout(lock: &str) -> Option { } } -/// How many remotes the `GEM` section that locks `dep` names, when it names -/// more than one: the section [`converge_gem_lock_source`] refuses, since -/// no spec of it can be given a source of its own. -pub(crate) fn shared_gem_section_remotes(lock: &str, dep: &DepOverride) -> Option { - let model = super::parse(lock); - let section = model.gem_sections().find(|section| { - section - .specs - .iter() - .any(|spec| spec.locks(&dep.name, &dep.version)) - })?; - (section.remotes.len() > 1).then_some(section.remotes.len()) -} - /// Converge a bundler < 2.2 lock ([`LockLayout::Merged`]) for one /// redirected dep: the patch registry joins the `remote:` lines of the /// lock's one `GEM` section and DEPENDENCIES source-pins the gem as `pin` @@ -890,7 +920,8 @@ BUNDLED WITH &mut changed, &mut result, ) - .unwrap_err(); + .unwrap_err() + .why; assert!( why.contains("spread over more than one GEM section"), "{why}" @@ -1411,6 +1442,29 @@ DEPENDENCIES } } + /// The 2.2 releases before 2.2.25 keep a merged section on relock. + #[test] + fn bundler_keeps_merged_section_names_the_early_2_2_releases() { + for (version, want) in [ + ("2.1.4", false), + ("2.2.0", true), + ("2.2.18", true), + ("2.2.25", false), + ("2.2.33", false), + ("2.5.22", false), + ("2.2", false), + ("2.2.x", false), + ] { + let lock = format!("GEM\n specs:\n\nBUNDLED WITH\r\n {version}\r\n"); + assert_eq!( + bundler_keeps_merged_section(&lock), + want.then_some(version), + "{version}" + ); + } + assert_eq!(bundler_keeps_merged_section("GEM\n specs:\n"), None); + } + /// Only a lock bundler < 2.2 wrote counts as the merged era. #[test] fn bundled_before_2_2_reads_the_bundled_with_version() { diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index d56aaecfe..70f670c1b 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -67,8 +67,8 @@ use crate::formats::cargo::source_replacement::{crates_io_source, ConfigLayer, C use crate::formats::cargo::{is_crates_io_patch_table, is_crates_io_source, CargoLock}; use crate::formats::composer::hosted::rewrite_composer_lock; use crate::formats::gem::hosted::{ - bundled_before_2_2, checksum_entry_span, converge_gem_lock_source, lock_layout, - merge_gem_lock_remote, refresh_merged_gem_lock_remote, shared_gem_section_remotes, + bundled_before_2_2, bundler_keeps_merged_section, checksum_entry_span, + converge_gem_lock_source, lock_layout, merge_gem_lock_remote, refresh_merged_gem_lock_remote, DependencyPin, LockLayout, }; use crate::formats::gem::locked_specs as gem_locked_specs; @@ -8399,31 +8399,38 @@ fn plan_gem_redirect( &mut staged, ) .map_err(|why| { - // A lock this bundler wrote for a manifest with several - // top-level sources: `bundle lock` writes the same lock - // again, so the way out is the manifest (#2162). The - // urls stay out of the text: a source can carry - // credentials. Vendored mode is not offered: it refuses - // a gem in a `group` block or with a native extension, - // which this plan cannot tell. - let globals = declarations::global_rubygems_sources(&gf).len(); - if let Some(remotes) = - shared_gem_section_remotes(&lk, dep).filter(|_| globals > 1) - { + // A multi-remote section under a manifest with several + // top-level sources is what this bundler writes for + // it, and `bundle lock` writes it again: the way out + // is the manifest (#2162). The urls stay out of the + // text: a source can carry credentials. Vendored mode + // is not offered: it refuses a gem in a `group` block + // or with a native extension, which this plan cannot + // tell. + let globals = declarations::top_level_source_count(&gf); + if let Some(remotes) = why.shared_remotes.filter(|_| globals > 1) { + let relock = match bundler_keeps_merged_section(&lk) { + Some(bundler) => format!( + "then run `bundle lock` with bundler 2.2.25 or later (bundler \ + {bundler}, which wrote {lock_name}, keeps the one section)" + ), + None => "then run `bundle lock`".to_string(), + }; return refuse( "redirect_gem_lock_unconvergeable", format!( "{gemfile_name} has {globals} top-level `source` lines, and \ for such a manifest bundler locks every gem in one GEM \ section that names every source ({lock_name} lists \ - {remotes} remotes over `{name} ({})`), where no gem can be \ - given the Socket source alone; nothing was changed for \ - {name} — keep one top-level `source` line and move each \ - other one into a `source \"\" do … end` block around \ - the gems that come from it (bundler's own deprecation \ - warning asks for the same), then run `bundle lock`, commit \ - {gemfile_name} and {lock_name} and re-run the hosted scan, \ - or patch {name} with `--mode agent`", + {remotes} remotes over `{name} ({})`), which hosted mode \ + does not rewrite; nothing was changed for {name} — keep \ + the source that serves {name} as the one top-level \ + `source` line and move each other one into a \ + `source \"\" do … end` block around the gems that \ + come from it (bundler's own deprecation warning asks for \ + the same), {relock}, commit {gemfile_name} \ + and {lock_name} and re-run the hosted scan, or patch \ + {name} with `--mode agent`", dep.version ), ); @@ -32288,6 +32295,9 @@ packages: let gemfiles = [ "source \"https://rubygems.org\"\nsource \"https://user:secret@gems.acme.example/private/\"\n\n\ gem \"rack\", \"2.2.8\"\n\ngroup :test do\n gem \"rack-test\", \"2.1.0\"\nend\n", + // A url the Gemfile computes is a top-level source all the same. + "source \"https://rubygems.org\"\nsource \"https://#{ENV['GEM_USER']}:secret@gems.acme.example/private/\"\n\n\ + gem \"rack\", \"2.2.8\"\n\ngroup :test do\n gem \"rack-test\", \"2.1.0\"\nend\n", // CRLF, and the second source in call parentheses. "source 'https://rubygems.org'\r\nsource('https://user:secret@gems.acme.example/private/')\r\n\r\n\ gem \"rack\", \"2.2.8\"\r\n\r\ngroup :test do\r\n gem \"rack-test\", \"2.1.0\"\r\nend\r\n", @@ -32317,6 +32327,7 @@ packages: let detail = &r.warnings[0].detail; assert!( detail.contains("Gemfile has 2 top-level `source` lines") + && detail.contains(&format!("keep the source that serves {gem} as")) && detail.contains("`source \"\" do … end` block") && detail.contains("then run `bundle lock`") && detail.contains(&format!("patch {gem} with `--mode agent`")), @@ -32353,6 +32364,9 @@ packages: source \"https://gems.acme.example/\" do\n gem \"acme\"\nend\n", "source \"https://rubygems.org\"\n\ngem \"rack\", \"2.2.8\"\n\ gem \"acme\", source: \"https://gems.acme.example/\"\n", + // Bundler runs one branch only. + "if ENV[\"MIRROR\"]\n source \"https://gems.acme.example/\"\nelse\n \ + source \"https://rubygems.org\"\nend\n\ngem \"rack\", \"2.2.8\"\n", ] { let (_, _, r) = gem_redirect(gemfile, lock, gem_override("rack", "2.2.8")); assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); @@ -32372,6 +32386,55 @@ packages: } } + /// Bundler 2.2.15 keeps the one section on `bundle lock` even once the + /// second source sits in a block (run against the real thing), so for + /// a lock an early 2.2 release wrote the remedy names a bundler that + /// splits it. + #[test] + fn gem_lock_of_an_early_bundler_2_2_names_a_bundler_that_splits_it() { + let gemfile = "source \"https://rubygems.org\"\nsource \"https://gems.acme.example/\"\n\n\ + gem \"rack\", \"2.2.8\"\n"; + let lock = "GEM\n remote: https://rubygems.org/\n remote: https://gems.acme.example/\n specs:\n \ + rack (2.2.8)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n rack (= 2.2.8)\n\n\ + BUNDLED WITH\n 2.2.15\n"; + let (_, _, r) = gem_redirect(gemfile, lock, gem_override("rack", "2.2.8")); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("Gemfile has 2 top-level `source` lines") + && detail.contains( + "then run `bundle lock` with bundler 2.2.25 or later (bundler 2.2.15, \ + which wrote Gemfile.lock, keeps the one section)" + ), + "{detail}" + ); + } + + /// A lock refused for another reason keeps that reason, whatever the + /// Gemfile's sources: here the gem is listed in two `GEM` sections. + #[test] + fn gem_lock_refused_for_another_reason_is_not_blamed_on_the_sources() { + let gemfile = "source \"https://rubygems.org\"\nsource \"https://gems.acme.example/\"\n\n\ + gem \"rack\", \"2.2.8\"\n"; + let lock = "GEM\n remote: https://rubygems.org/\n remote: https://gems.acme.example/\n specs:\n \ + rack (2.2.8)\n\nGEM\n remote: https://other.example/\n specs:\n rack (2.2.8)\n\n\ + PLATFORMS\n ruby\n\nDEPENDENCIES\n rack (= 2.2.8)\n\nBUNDLED WITH\n 2.5.22\n"; + let (_, _, r) = gem_redirect(gemfile, lock, gem_override("rack", "2.2.8")); + assert!(r.files.is_empty() && r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + warning_codes(&r), + vec!["redirect_gem_lock_unconvergeable"], + "{:?}", + r.warnings + ); + let detail = &r.warnings[0].detail; + assert!( + detail.contains("more than one GEM section lists `rack (2.2.8)`") + && !detail.contains("top-level"), + "{detail}" + ); + } + /// B1: lock shapes that cannot record the Socket source — a multi-remote /// GEM section under a bundler >= 2.2, a spec duplicated across GEM /// sections, no DEPENDENCIES section, a lock that names no bundler — diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a7ce3bf4a..e7c7223dd 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2183,7 +2183,7 @@ wire is skipped, neither file changes for it, and the warning says why and what | `redirect_gem_declared_more_than_once` | the Gemfile declares it more than once. Merge the declarations into one. | | `redirect_gem_declaration_not_visible` | the lock lists it as a direct dependency, but it is declared where the scan cannot edit: an `eval_gemfile`d file, a loop, a gemspec. Declare it with a literal `gem ""` line in the Gemfile, in place of any other `gem` call that declares it (a gemspec's development dependency stays), or patch it with `--mode agent`. Vendored mode refuses it for the same reason. | | `redirect_gem_dependency_not_locked` | the Gemfile declares it and the lock's `DEPENDENCIES` does not list it. Run `bundle lock` and re-run. | -| `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. Also a Gemfile with more than one top-level `source` line: Bundler 2.2 to 2.7 lock all its gems in one `GEM` section that names every source, where no gem can be given the patch source alone, and `bundle lock` writes the same lock again. Keep one top-level `source` and move each other one into a `source "" do … end` block around the gems that come from it (Bundler's own deprecation warning asks for the same), then run `bundle lock` and re-run; or use `--mode agent`. | +| `redirect_gem_lock_unconvergeable` | the lock cannot be brought in line with the Gemfile: it has no `BUNDLED WITH` section to say which layout its Bundler accepts, or a Bundler < 2.2 lock lists its sources in an order the Gemfile's `source` lines do not explain. Run `bundle lock` with your current Bundler and re-run. Also a Gemfile with more than one top-level `source` line: Bundler 2.2 to 2.7 lock all its gems in one `GEM` section that names every source, which hosted mode does not rewrite, and `bundle lock` writes the same lock again. Keep the source that serves the gem as the one top-level `source` and move each other one into a `source "" do … end` block around the gems that come from it (Bundler's own deprecation warning asks for the same), then run `bundle lock` and re-run; or use `--mode agent`. A Bundler 2.2 release before 2.2.25 keeps the one section even then, so run that `bundle lock` with a later Bundler; the warning says so when the lock was written by one. | | `redirect_gem_platform_unsupported` | the lock holds a platform-specific build of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) that the patch has no patched build for. The warning names the builds the lock holds, the ones that are missing, and what the patch registry serves. See "Precompiled platform gems" below. | `--mode agent` can still patch a gem hosted mode skips. `--mode vendored` can too, unless it