From 17202d8317b021e3fcfed2cdfcebe5f79f5381f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:23:03 +0000 Subject: [PATCH 1/8] Start: vendored gem refusals name a remedy Refs #2091. Empty commit that opens the draft pull request; the tests and the fix follow. Assisted-by: Claude Code:claude-fable-5-2 From 4926aec7c3baec703fc0b62b902f7a2de11349a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:29:48 +0000 Subject: [PATCH 2/8] Test that vendored gem refusals name a remedy Refs #2091. The group-block, native-extension and platform-build refusals must each name a mode that can patch the gem, and never one that refuses it too. These fail until the next commit. Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/vendor/gem.rs | 39 ++++++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0f83bbcc4..1fa2f48a7 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -3919,6 +3919,25 @@ mod tests { ); } + /// #2091: a refusal that another mode does not share says so. `detail` + /// names `socket-patch scan --mode ` for exactly the modes in + /// `modes`, so it never sends the user to a mode that refuses the gem + /// as well. + fn assert_names_other_modes(detail: &str, modes: &[&str]) { + for mode in ["hosted", "agent"] { + let named = detail.contains(&format!("--mode {mode}")); + assert_eq!( + named, + modes.contains(&mode), + "`--mode {mode}` named={named}: {detail}" + ); + } + assert!( + detail.contains("`socket-patch scan --mode "), + "the remedy is a command the user can run: {detail}" + ); + } + #[tokio::test] async fn test_refuses_native_extensions() { let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; @@ -3939,6 +3958,7 @@ mod tests { unwrap_refused(run_vendor(&root, &blobs, &installed, &record, false).await); assert_eq!(code, "native_extensions_unsupported"); assert!(detail.contains("native extensions")); + assert_names_other_modes(&detail, &["hosted", "agent"]); assert!(!root.join(".socket").exists()); // Neither file touched. assert_eq!( @@ -3960,9 +3980,11 @@ mod tests { let platform_dir = installed.parent().unwrap().join("rack-3.2.6-x86_64-linux"); tokio::fs::rename(&installed, &platform_dir).await.unwrap(); - let (code, _d) = + let (code, detail) = unwrap_refused(run_vendor(&root, &blobs, &platform_dir, &record, false).await); assert_eq!(code, "platform_gem_unsupported"); + // Hosted mode refuses a precompiled build too, so it is not named. + assert_names_other_modes(&detail, &["agent"]); assert!(!root.join(".socket").exists()); } @@ -3978,8 +4000,10 @@ mod tests { let odd_dir = installed.parent().unwrap().join("random-unrelated"); tokio::fs::rename(&installed, &odd_dir).await.unwrap(); - let (code, _d) = unwrap_refused(run_vendor(&root, &blobs, &odd_dir, &record, false).await); + let (code, detail) = + unwrap_refused(run_vendor(&root, &blobs, &odd_dir, &record, false).await); assert_eq!(code, "platform_gem_unsupported"); + assert_names_other_modes(&detail, &["agent"]); assert!(!root.join(".socket").exists()); } @@ -3999,6 +4023,7 @@ mod tests { detail.contains("x86_64-linux"), "refusal names the offending platform: {detail}" ); + assert_names_other_modes(&detail, &["agent"]); assert!(!root.join(".socket").exists(), "refusal must write nothing"); } @@ -4042,6 +4067,12 @@ mod tests { unwrap_refused(run_vendor(&root, &blobs, &installed, &record, false).await); assert_eq!(code, "gemfile_declaration_not_editable"); assert!(detail.contains("indented"), "{detail}"); + // #2091: both ways out are named, the first with this gem's name. + assert!( + detail.contains("`gem \"rack\", group: :test`"), + "names the top-level `group:` form: {detail}" + ); + assert_names_other_modes(&detail, &["hosted"]); assert!(!root.join(".socket").exists()); assert_eq!( tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), @@ -7084,8 +7115,9 @@ mod tests { )), ) .await; - let (code, _) = unwrap_refused(outcome); + let (code, detail) = unwrap_refused(outcome); assert_eq!(code, "native_extensions_unsupported"); + assert_names_other_modes(&detail, &["hosted", "agent"]); } /// `--offline` + `--vendor-source=service` refuses without any network. @@ -9729,6 +9761,7 @@ mod tests { let (code, detail) = refusal.expect("an indented declaration is not editable"); assert_eq!(code, "gemfile_declaration_not_editable"); assert!(detail.contains("indented"), "{detail}"); + assert_names_other_modes(&detail, &["hosted"]); // A preflight: the hosted pair is never written, even though the // caller's options are a wet run. assert_eq!(std::fs::read_to_string(dir.join(GEMFILE)).unwrap(), gemfile); From ede5101288161bd7c5fb25c18edb232c76f0126b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:32:40 +0000 Subject: [PATCH 3/8] Name a remedy in vendored gem refusals MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Vendored mode refuses a gem declared inside a block, a gem with native extensions and a precompiled platform build. Each error gave the cause and no next step, so a stock Rails Gemfile failed 5 of 7 gems with nothing to act on. Each refusal now names a mode that can patch the gem: hosted mode for a block (with the top-level `group:` form when the block is a plain `group … do`), hosted or agent mode for native extensions, and agent mode alone for a platform build, which hosted mode refuses too. Fixes #2091 Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_redirect_gem_build.rs | 8 ++ crates/socket-patch-core/src/vendor/gem.rs | 135 +++++++++++++++++- docs/ecosystems.md | 17 ++- 3 files changed, 154 insertions(+), 6 deletions(-) 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 bfa6545c0..df416c469 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -3673,6 +3673,14 @@ fn vendor_eject_keeps_the_hosted_group_pin(fx: &RedirectFixture, dry_run: bool) events[0]["errorCode"], "gemfile_declaration_not_editable", "{label}: {env}" ); + // #2091: the refusal says how to get out of it. The gem is declared in + // a `group :development do` block, which one top-level option replaces. + let detail = events[0]["error"].as_str().unwrap_or_default(); + assert!( + detail.contains(&format!("`gem \"{DEP}\", group: :development`")) + && detail.contains("`socket-patch scan --mode hosted`"), + "{label}: the refusal names both remedies: {env}" + ); assert_eq!(env["error"]["code"], "eject_refused", "{label}: {env}"); assert!( !stdout.contains("eject_planned") && !stdout.contains("eject_rolled_back"), diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 1fa2f48a7..b8d4fcdee 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -392,7 +392,7 @@ async fn gem_prelude( return Err(refused( "platform_gem_unsupported", format!( - "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably" + "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably. {PLATFORM_GEM_REMEDY}" ), )); } @@ -412,7 +412,7 @@ async fn gem_prelude( return Err(refused( "platform_gem_unsupported", format!( - "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably)" + "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably). {PLATFORM_GEM_REMEDY}" ), )); } @@ -489,7 +489,7 @@ async fn gem_prelude( return Err(refused( "native_extensions_unsupported", format!( - "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems" + "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems. {NATIVE_EXTENSIONS_REMEDY}" ), )); } @@ -1045,7 +1045,7 @@ pub(super) async fn gem_service_copy( "native_extensions_unsupported", format!( "the served stub gemspec for {name} declares native extensions; bundler does \ - not build extensions for path-sourced gems" + not build extensions for path-sourced gems. {NATIVE_EXTENSIONS_REMEDY}" ), )); } @@ -1338,6 +1338,68 @@ enum GemfilePlan { Append { block: String }, } +/// The way out of a native-extension refusal (#2091): the two modes that +/// compile the extension. See "Ruby gems: native extensions" in +/// `docs/ecosystems.md`. +const NATIVE_EXTENSIONS_REMEDY: &str = "Patch it with `socket-patch scan --mode hosted` or \ + `socket-patch scan --mode agent`, which build the extension"; + +/// The way out of a platform-build refusal (#2091). Agent mode only: hosted +/// mode refuses a precompiled build as well +/// (`redirect_gem_platform_unsupported`). +const PLATFORM_GEM_REMEDY: &str = + "Patch it where it is installed with `socket-patch scan --mode agent`"; + +/// The `group:` option that stands for the `group … do` block around the +/// indented declaration at `lines[idx]`, for the refusal's remedy: +/// `group: :test`, or `group: [:development, :test]`. +/// +/// `None` unless the nearest less-indented line above is a `group` call +/// whose arguments are all plain symbols and which opens the block on that +/// line. A `source … do`, `platforms … do` or conditional block, a nested +/// block, and a `group` with options (`optional: true`) have no one-option +/// spelling that is sure to mean the same, so the remedy names none. +fn enclosing_group_option(lines: &[&str], idx: usize) -> Option { + let indent = |line: &str| line.len() - line.trim_start().len(); + let own = indent(lines[idx]); + let header = lines[..idx].iter().rev().find(|line| { + let t = line.trim(); + !t.is_empty() && !t.starts_with('#') && indent(line) < own + })?; + // A block that is itself inside a block is not the whole story. + if indent(header) != 0 { + return None; + } + let args = header + .trim_end() + .strip_prefix("group")? + .strip_suffix("do")? + .trim(); + let args = args + .strip_prefix('(') + .and_then(|a| a.strip_suffix(')')) + .unwrap_or(args); + let mut groups = Vec::new(); + for arg in args.split(',') { + let arg = arg.trim(); + let ident = arg.strip_prefix(':')?; + let mut chars = ident.chars(); + let plain = chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_'); + if !plain { + return None; + } + groups.push(arg); + } + match groups.as_slice() { + [] => None, + [one] => Some(format!("group: {one}")), + many => Some(format!("group: [{}]", many.join(", "))), + } +} + /// Decide how to edit the Gemfile, or explain why it cannot be edited. /// /// Deliberately conservative: only a single, top-level, statically-parseable @@ -1411,8 +1473,14 @@ fn plan_gemfile_edit( let cr = if lines[idx].ends_with('\r') { "\r" } else { "" }; let rest = rest.strip_suffix('\r').unwrap_or(&rest); if !top_level { + let top_level_form = match enclosing_group_option(&lines, idx) { + Some(option) => format!("declare it at the top level as `gem \"{name}\", {option}`"), + None => "declare it on a top-level line".to_string(), + }; return Err(format!( - "the `gem \"{name}\"` declaration is indented (inside a group/conditional block)" + "the `gem \"{name}\"` declaration is indented (inside a group/conditional block); \ + {top_level_form}, or use hosted mode for it (`socket-patch scan --mode hosted`), \ + which patches a gem declared inside a block" )); } if paren { @@ -3919,6 +3987,63 @@ mod tests { ); } + /// #2091: the remedy spells the `group:` option of the block around the + /// declaration, and names none when one option would not mean the same. + #[test] + fn enclosing_group_option_spells_only_a_plain_group_block() { + let option = |gemfile: &str| { + let lines: Vec<&str> = gemfile.split('\n').collect(); + let idx = lines + .iter() + .position(|l| l.trim_start().starts_with("gem \"rack\"")) + .unwrap(); + enclosing_group_option(&lines, idx) + }; + for (gemfile, want) in [ + ( + "group :test do\n gem \"rack\"\nend\n", + Some("group: :test"), + ), + // CRLF, a comment and a sibling between the header and the gem. + ( + "group :test do\r\n gem \"puma\"\r\n\r\n # web\r\n gem \"rack\"\r\nend\r\n", + Some("group: :test"), + ), + ( + "group :development, :test do\n\tgem \"rack\"\nend\n", + Some("group: [:development, :test]"), + ), + ( + "group(:test) do\n gem \"rack\"\nend\n", + Some("group: :test"), + ), + // No single option is sure to mean the same as these. + ( + "group :test, optional: true do\n gem \"rack\"\nend\n", + None, + ), + ("group \"test\" do\n gem \"rack\"\nend\n", None), + ("group :test do |g|\n gem \"rack\"\nend\n", None), + ("platforms :mri do\n gem \"rack\"\nend\n", None), + ("if ENV[\"CI\"]\n gem \"rack\"\nend\n", None), + ( + "source \"https://gems.example\" do\n gem \"rack\"\nend\n", + None, + ), + ( + "group :test do\n platforms :mri do\n gem \"rack\"\n end\nend\n", + None, + ), + ( + "platforms :mri do\n group :test do\n gem \"rack\"\n end\nend\n", + None, + ), + (" gem \"rack\"\n", None), + ] { + assert_eq!(option(gemfile).as_deref(), want, "{gemfile:?}"); + } + } + /// #2091: a refusal that another mode does not share says so. `detail` /// names `socket-patch scan --mode ` for exactly the modes in /// `modes`, so it never sends the user to a mode that refuses the gem diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 317516802..6005219fd 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1995,6 +1995,21 @@ A shared gem home also holds gem versions this project doesn't use: the gems Rub mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` event with `vendor_gem_version_not_locked` and doesn't download its patch. The run exits 0. +## Ruby gems: gems vendored mode refuses + +Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing +for a path-sourced gem. It refuses a gem that doesn't fit and changes nothing for it; the +other gems of the run are still vendored, and the run exits 1. Each error names the way out: + +| Code | The gem | What to do | +|---|---|---| +| `gemfile_declaration_not_editable` | is declared inside a block: `group :test do`, `platforms … do`, a conditional. Every Rails Gemfile declares its development and test gems this way. | Declare it at the top level with the `group:` option (`gem "capybara", group: :test`), or run `socket-patch scan --mode hosted`, which patches a gem inside a block. | +| `native_extensions_unsupported` | builds a native extension (puma, bootsnap). | Run `socket-patch scan --mode hosted` or `socket-patch scan --mode agent`. Both build the extension. | +| `platform_gem_unsupported` | is installed as a precompiled platform build (`nokogiri-1.18.3-x86_64-linux-gnu`). | Run `socket-patch scan --mode agent`. Hosted mode refuses a precompiled build too. | + +A hosted scan run after the vendored one patches the gems it can and leaves the vendored gems as +they are. + ## Ruby gems: native extensions Some gem fixes change only what a native extension is built from: its C sources @@ -2007,7 +2022,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A precompiled platform gem (`x86_64-linux`) is refused with `redirect_gem_platform_unsupported`. | -| Vendored | Refused with `native_extensions_unsupported`: Bundler builds no extensions for path-sourced gems. | +| Vendored | Refused with `native_extensions_unsupported`: Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for the gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 080e1060dad71b5133d54cc294e5a1ccfe0dbf77 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:59:34 +0000 Subject: [PATCH 4/8] Fit each gem refusal's remedy to its cause Review of the first cut found remedies that could mislead: - A gem inside a source, git, github or path block was sent to hosted mode, which refuses it too. The enclosing blocks are now read with formats::gem::ruby::block_stack and agent mode is named there. - The suggested top-level line dropped the declaration's version and options. The remedy now names only the group: option to add. - A gem that is hosted already (the takeover and eject preflight) was told to use hosted mode. It is now told it can stay there. - `socket-patch scan --mode hosted` was quoted as the fix for one gem, though a whole-project hosted scan moves the vendored patches of other ecosystems. The remedies name the mode for the gem, as hosted mode's own refusals do, and the docs say how to patch one gem. Refs #2091 Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_redirect_gem_build.rs | 9 +- crates/socket-patch-core/src/vendor/gem.rs | 233 ++++++++++++------ docs/ecosystems.md | 22 +- 3 files changed, 169 insertions(+), 95 deletions(-) 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 df416c469..7513fca58 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -3674,12 +3674,13 @@ fn vendor_eject_keeps_the_hosted_group_pin(fx: &RedirectFixture, dry_run: bool) "{label}: {env}" ); // #2091: the refusal says how to get out of it. The gem is declared in - // a `group :development do` block, which one top-level option replaces. + // a `group :development do` block, which one top-level option replaces, + // and it is hosted already, so hosted mode is the mode to keep. let detail = events[0]["error"].as_str().unwrap_or_default(); assert!( - detail.contains(&format!("`gem \"{DEP}\", group: :development`")) - && detail.contains("`socket-patch scan --mode hosted`"), - "{label}: the refusal names both remedies: {env}" + detail.contains("move it to the top level with the option `group: :development`") + && detail.contains(&format!("or keep {DEP} in hosted mode")), + "{label}: the refusal names both ways out: {env}" ); assert_eq!(env["error"]["code"], "eject_refused", "{label}: {env}"); assert!( diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index b8d4fcdee..d6282c45f 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -305,7 +305,7 @@ pub async fn gem_vendor_target_preflight( .await .ok()?, }; - plan_gemfile_edit(&gemfile_text, &name, &version, ©_rel) + plan_gemfile_edit_for(&gemfile_text, &name, &version, ©_rel, true) .and_then(|plan| refuse_append_of_direct_dependency(plan, &lock_text, &name)) .and_then(|plan| { let after = apply_gemfile_plan(&gemfile_text, &plan); @@ -392,7 +392,8 @@ async fn gem_prelude( return Err(refused( "platform_gem_unsupported", format!( - "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably. {PLATFORM_GEM_REMEDY}" + "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably. {}", + platform_gem_remedy(&name) ), )); } @@ -412,7 +413,8 @@ async fn gem_prelude( return Err(refused( "platform_gem_unsupported", format!( - "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably). {PLATFORM_GEM_REMEDY}" + "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably). {}", + platform_gem_remedy(&name) ), )); } @@ -489,7 +491,8 @@ async fn gem_prelude( return Err(refused( "native_extensions_unsupported", format!( - "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems. {NATIVE_EXTENSIONS_REMEDY}" + "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems. {}", + native_extensions_remedy(&name) ), )); } @@ -1045,7 +1048,8 @@ pub(super) async fn gem_service_copy( "native_extensions_unsupported", format!( "the served stub gemspec for {name} declares native extensions; bundler does \ - not build extensions for path-sourced gems. {NATIVE_EXTENSIONS_REMEDY}" + not build extensions for path-sourced gems. {}", + native_extensions_remedy(&name) ), )); } @@ -1339,39 +1343,66 @@ enum GemfilePlan { } /// The way out of a native-extension refusal (#2091): the two modes that -/// compile the extension. See "Ruby gems: native extensions" in -/// `docs/ecosystems.md`. -const NATIVE_EXTENSIONS_REMEDY: &str = "Patch it with `socket-patch scan --mode hosted` or \ - `socket-patch scan --mode agent`, which build the extension"; +/// compile the extension ("Ruby gems: native extensions" in +/// `docs/ecosystems.md`). Worded as hosted mode words its own refusals +/// ("patch with `--mode vendored` or `--mode agent`"): it names the +/// mode for this gem, not a whole-project command. +fn native_extensions_remedy(name: &str) -> String { + format!("Patch {name} with `--mode hosted` or `--mode agent`, which build the extension") +} /// The way out of a platform-build refusal (#2091). Agent mode only: hosted /// mode refuses a precompiled build as well /// (`redirect_gem_platform_unsupported`). -const PLATFORM_GEM_REMEDY: &str = - "Patch it where it is installed with `socket-patch scan --mode agent`"; +fn platform_gem_remedy(name: &str) -> String { + format!( + "Patch {name} with `--mode agent`, which patches a precompiled gem where it is installed" + ) +} -/// The `group:` option that stands for the `group … do` block around the -/// indented declaration at `lines[idx]`, for the refusal's remedy: -/// `group: :test`, or `group: [:development, :test]`. +/// The way out of an indented-declaration refusal (#2091), for the +/// declaration on the line that starts at byte `line_start` of `text`. /// -/// `None` unless the nearest less-indented line above is a `group` call -/// whose arguments are all plain symbols and which opens the block on that -/// line. A `source … do`, `platforms … do` or conditional block, a nested -/// block, and a `group` with options (`optional: true`) have no one-option -/// spelling that is sure to mean the same, so the remedy names none. -fn enclosing_group_option(lines: &[&str], idx: usize) -> Option { - let indent = |line: &str| line.len() - line.trim_start().len(); - let own = indent(lines[idx]); - let header = lines[..idx].iter().rev().find(|line| { - let t = line.trim(); - !t.is_empty() && !t.starts_with('#') && indent(line) < own - })?; - // A block that is itself inside a block is not the whole story. - if indent(header) != 0 { - return None; +/// - Inside a `source` / `git` / `github` / `path` block, hosted mode +/// refuses the gem as well (`redirect_gem_source_option`), so agent mode +/// is the one named. +/// - Otherwise the top level is a way out, and so is hosted mode, which +/// edits a declaration where it is. When exactly one block is open and it +/// is a plain `group … do`, the `group:` option that replaces it is +/// spelled out ([`group_option`]). `hosted` is the takeover and eject +/// preflight, where the gem is in hosted mode already. +fn indented_declaration_remedy(text: &str, line_start: usize, name: &str, hosted: bool) -> String { + let frames = crate::formats::gem::ruby::block_stack(text, line_start); + if frames.iter().any(|frame| frame.source.is_some()) { + return format!("patch {name} with `--mode agent`"); + } + let top_level = match frames.as_slice() { + [] => "write it without indentation".to_string(), + [frame] if frame.line == frame.opener => { + let header = text[frame.line..].lines().next().unwrap_or_default(); + match group_option(header) { + Some(option) => format!("move it to the top level with the option `{option}`"), + None => "move it to the top level".to_string(), + } + } + _ => "move it to the top level".to_string(), + }; + if hosted { + format!("{top_level} to vendor it, or keep {name} in hosted mode") + } else { + format!("{top_level}, or patch {name} with `--mode hosted`") } +} + +/// The `group:` option that stands for the block `header` opens: +/// `group: :test` for `group :test do`, `group: [:development, :test]` for +/// `group :development, :test do`. `None` unless the line is a `group` call +/// whose arguments are all plain symbols: a `group` with options +/// (`optional: true`), a block parameter or a string name has no one-option +/// spelling that is sure to mean the same. +fn group_option(header: &str) -> Option { let args = header - .trim_end() + .trim() .strip_prefix("group")? .strip_suffix("do")? .trim(); @@ -1382,8 +1413,7 @@ fn enclosing_group_option(lines: &[&str], idx: usize) -> Option { let mut groups = Vec::new(); for arg in args.split(',') { let arg = arg.trim(); - let ident = arg.strip_prefix(':')?; - let mut chars = ident.chars(); + let mut chars = arg.strip_prefix(':')?.chars(); let plain = chars .next() .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') @@ -1393,11 +1423,10 @@ fn enclosing_group_option(lines: &[&str], idx: usize) -> Option { } groups.push(arg); } - match groups.as_slice() { - [] => None, - [one] => Some(format!("group: {one}")), - many => Some(format!("group: [{}]", many.join(", "))), - } + Some(match groups.as_slice() { + [one] => format!("group: {one}"), + many => format!("group: [{}]", many.join(", ")), + }) } /// Decide how to edit the Gemfile, or explain why it cannot be edited. @@ -1415,6 +1444,19 @@ fn plan_gemfile_edit( name: &str, version: &str, rel: &str, +) -> Result { + plan_gemfile_edit_for(text, name, version, rel, false) +} + +/// [`plan_gemfile_edit`], with `hosted` set when the gem is in hosted mode +/// already (the takeover and eject preflight): a refusal then does not +/// offer hosted mode as if it were news. +fn plan_gemfile_edit_for( + text: &str, + name: &str, + version: &str, + rel: &str, + hosted: bool, ) -> Result { let lines: Vec<&str> = text.split('\n').collect(); // (line idx, top-level?, paren-call?, quote, rest-after-name) @@ -1473,14 +1515,11 @@ fn plan_gemfile_edit( let cr = if lines[idx].ends_with('\r') { "\r" } else { "" }; let rest = rest.strip_suffix('\r').unwrap_or(&rest); if !top_level { - let top_level_form = match enclosing_group_option(&lines, idx) { - Some(option) => format!("declare it at the top level as `gem \"{name}\", {option}`"), - None => "declare it on a top-level line".to_string(), - }; + let line_start: usize = lines[..idx].iter().map(|line| line.len() + 1).sum(); + let remedy = indented_declaration_remedy(text, line_start, name, hosted); return Err(format!( "the `gem \"{name}\"` declaration is indented (inside a group/conditional block); \ - {top_level_form}, or use hosted mode for it (`socket-patch scan --mode hosted`), \ - which patches a gem declared inside a block" + {remedy}" )); } if paren { @@ -3987,80 +4026,107 @@ mod tests { ); } - /// #2091: the remedy spells the `group:` option of the block around the - /// declaration, and names none when one option would not mean the same. + /// #2091: the remedy of an indented declaration names only ways out + /// that work for the block it sits in, and spells the `group:` option + /// only where one option means the same as the block. #[test] - fn enclosing_group_option_spells_only_a_plain_group_block() { - let option = |gemfile: &str| { - let lines: Vec<&str> = gemfile.split('\n').collect(); - let idx = lines - .iter() - .position(|l| l.trim_start().starts_with("gem \"rack\"")) - .unwrap(); - enclosing_group_option(&lines, idx) + fn indented_declaration_remedy_fits_the_enclosing_block() { + let remedy = |gemfile: &str, hosted: bool| { + let at = gemfile.find("gem \"rack\"").unwrap(); + let line_start = gemfile[..at].rfind('\n').map_or(0, |i| i + 1); + indented_declaration_remedy(gemfile, line_start, "rack", hosted) }; - for (gemfile, want) in [ + let hosted_too = ", or patch rack with `--mode hosted`"; + for (gemfile, top_level) in [ ( - "group :test do\n gem \"rack\"\nend\n", - Some("group: :test"), + "group :test do\n gem \"rack\", \"~> 3.1\", require: false\nend\n", + "move it to the top level with the option `group: :test`", ), // CRLF, a comment and a sibling between the header and the gem. ( "group :test do\r\n gem \"puma\"\r\n\r\n # web\r\n gem \"rack\"\r\nend\r\n", - Some("group: :test"), + "move it to the top level with the option `group: :test`", ), ( "group :development, :test do\n\tgem \"rack\"\nend\n", - Some("group: [:development, :test]"), + "move it to the top level with the option `group: [:development, :test]`", ), ( "group(:test) do\n gem \"rack\"\nend\n", - Some("group: :test"), + "move it to the top level with the option `group: :test`", ), // No single option is sure to mean the same as these. ( "group :test, optional: true do\n gem \"rack\"\nend\n", - None, + "move it to the top level", ), - ("group \"test\" do\n gem \"rack\"\nend\n", None), - ("group :test do |g|\n gem \"rack\"\nend\n", None), - ("platforms :mri do\n gem \"rack\"\nend\n", None), - ("if ENV[\"CI\"]\n gem \"rack\"\nend\n", None), ( - "source \"https://gems.example\" do\n gem \"rack\"\nend\n", - None, + "group \"test\" do\n gem \"rack\"\nend\n", + "move it to the top level", ), ( - "group :test do\n platforms :mri do\n gem \"rack\"\n end\nend\n", - None, + "platforms :mri do\n gem \"rack\"\nend\n", + "move it to the top level", + ), + ( + "if ENV[\"CI\"]\n gem \"rack\"\nend\n", + "move it to the top level", + ), + // Two blocks are open, however the inner one is indented. + ( + "group :test do\nplatforms :mri do\n gem \"rack\"\nend\nend\n", + "move it to the top level", ), ( "platforms :mri do\n group :test do\n gem \"rack\"\n end\nend\n", - None, + "move it to the top level", + ), + // A closed block above is not the one around the gem. + ( + "group :test do\n gem \"puma\"\nend\n gem \"rack\"\n", + "write it without indentation", ), - (" gem \"rack\"\n", None), ] { - assert_eq!(option(gemfile).as_deref(), want, "{gemfile:?}"); + assert_eq!( + remedy(gemfile, false), + format!("{top_level}{hosted_too}"), + "{gemfile:?}" + ); + assert_eq!( + remedy(gemfile, true), + format!("{top_level} to vendor it, or keep rack in hosted mode"), + "{gemfile:?}" + ); + } + // Hosted mode refuses a gem inside a source-selecting block too + // (`redirect_gem_source_option`), so it is never named there. + for gemfile in [ + "source \"https://gems.example\" do\n gem \"rack\"\nend\n", + "git \"https://git.example/rack.git\" do\n gem \"rack\"\nend\n", + "group :test do\n source \"https://gems.example\" do\n gem \"rack\"\n end\nend\n", + ] { + for hosted in [false, true] { + assert_eq!( + remedy(gemfile, hosted), + "patch rack with `--mode agent`", + "{gemfile:?}" + ); + } } } /// #2091: a refusal that another mode does not share says so. `detail` - /// names `socket-patch scan --mode ` for exactly the modes in - /// `modes`, so it never sends the user to a mode that refuses the gem - /// as well. + /// names `--mode ` for exactly the modes in `modes`, so it never + /// sends the user to a mode that refuses the gem as well. fn assert_names_other_modes(detail: &str, modes: &[&str]) { for mode in ["hosted", "agent"] { - let named = detail.contains(&format!("--mode {mode}")); + let named = detail.contains(&format!("`--mode {mode}`")); assert_eq!( named, modes.contains(&mode), "`--mode {mode}` named={named}: {detail}" ); } - assert!( - detail.contains("`socket-patch scan --mode "), - "the remedy is a command the user can run: {detail}" - ); } #[tokio::test] @@ -4192,9 +4258,9 @@ mod tests { unwrap_refused(run_vendor(&root, &blobs, &installed, &record, false).await); assert_eq!(code, "gemfile_declaration_not_editable"); assert!(detail.contains("indented"), "{detail}"); - // #2091: both ways out are named, the first with this gem's name. + // #2091: both ways out are named, the first with the block's option. assert!( - detail.contains("`gem \"rack\", group: :test`"), + detail.contains("move it to the top level with the option `group: :test`"), "names the top-level `group:` form: {detail}" ); assert_names_other_modes(&detail, &["hosted"]); @@ -9886,7 +9952,10 @@ mod tests { let (code, detail) = refusal.expect("an indented declaration is not editable"); assert_eq!(code, "gemfile_declaration_not_editable"); assert!(detail.contains("indented"), "{detail}"); - assert_names_other_modes(&detail, &["hosted"]); + // #2091: the gem is hosted already, so hosted mode is not offered + // as a mode to switch to. + assert!(detail.contains("keep rails in hosted mode"), "{detail}"); + assert_names_other_modes(&detail, &[]); // A preflight: the hosted pair is never written, even though the // caller's options are a wet run. assert_eq!(std::fs::read_to_string(dir.join(GEMFILE)).unwrap(), gemfile); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6005219fd..a3ec4348b 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1998,17 +1998,21 @@ mode warns `redirect_gem_version_not_locked`, vendored mode reports a `skipped` ## Ruby gems: gems vendored mode refuses Vendored mode rewrites one top-level `gem` line to a `path:` source, and Bundler builds nothing -for a path-sourced gem. It refuses a gem that doesn't fit and changes nothing for it; the -other gems of the run are still vendored, and the run exits 1. Each error names the way out: +for a path-sourced gem. It refuses a gem that doesn't fit and changes nothing for it; the other +gems of the run are still vendored, and the run exits 1. These three refusals name another mode +that can patch the gem: -| Code | The gem | What to do | +| Code | The gem | What the error offers | |---|---|---| -| `gemfile_declaration_not_editable` | is declared inside a block: `group :test do`, `platforms … do`, a conditional. Every Rails Gemfile declares its development and test gems this way. | Declare it at the top level with the `group:` option (`gem "capybara", group: :test`), or run `socket-patch scan --mode hosted`, which patches a gem inside a block. | -| `native_extensions_unsupported` | builds a native extension (puma, bootsnap). | Run `socket-patch scan --mode hosted` or `socket-patch scan --mode agent`. Both build the extension. | -| `platform_gem_unsupported` | is installed as a precompiled platform build (`nokogiri-1.18.3-x86_64-linux-gnu`). | Run `socket-patch scan --mode agent`. Hosted mode refuses a precompiled build too. | - -A hosted scan run after the vendored one patches the gems it can and leaves the vendored gems as -they are. +| `gemfile_declaration_not_editable` ("is indented") | is declared inside a block: `group :test do`, `platforms … do`, a conditional. Every Rails Gemfile declares its development and test gems this way. | Move the declaration to the top level (for a plain `group` block the error spells the option that replaces it, `group: :test`), or patch the gem with `--mode hosted`, which edits a declaration where it is. Inside a `source`, `git`, `github` or `path` block hosted mode refuses the gem too, and the error names `--mode agent`. | +| `native_extensions_unsupported` | builds a native extension (puma, bootsnap). | `--mode hosted` or `--mode agent`. Both build the extension. | +| `platform_gem_unsupported` | is installed as a precompiled platform build (`nokogiri-1.18.3-x86_64-linux-gnu`). | `--mode agent`. Hosted mode refuses a precompiled build too. | + +To patch one gem in another mode, name it: `socket-patch get --mode hosted`. A whole-project +`scan --mode hosted` leaves vendored gems as they are, but it moves the vendored patches of the +other ecosystems (npm, PyPI, Cargo, Go, Composer, Gradle) to hosted mode. Once a project holds +patches of two modes, a `scan` with no `--mode` stops and asks which mode to use, so pass `--mode` +on later runs. ## Ruby gems: native extensions From bd5e8933dee390dd293ebf13177300a666de0d6b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:03:07 +0000 Subject: [PATCH 5/8] Drop needless borrows in gem remedies clippy::needless_borrow on the four remedy calls. Refs #2091 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/vendor/gem.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index d6282c45f..559cc034a 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -393,7 +393,7 @@ async fn gem_prelude( "platform_gem_unsupported", format!( "`{name}@{version}` is a platform-specific gem build (`platform={platform}`); precompiled platform gems cannot be vendored portably. {}", - platform_gem_remedy(&name) + platform_gem_remedy(name) ), )); } @@ -414,7 +414,7 @@ async fn gem_prelude( "platform_gem_unsupported", format!( "installed dir `{dir_name}` is not the portable `{leaf}` gem (platform-specific or unexpected gem builds cannot be vendored portably). {}", - platform_gem_remedy(&name) + platform_gem_remedy(name) ), )); } @@ -492,7 +492,7 @@ async fn gem_prelude( "native_extensions_unsupported", format!( "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems. {}", - native_extensions_remedy(&name) + native_extensions_remedy(name) ), )); } @@ -1049,7 +1049,7 @@ pub(super) async fn gem_service_copy( format!( "the served stub gemspec for {name} declares native extensions; bundler does \ not build extensions for path-sourced gems. {}", - native_extensions_remedy(&name) + native_extensions_remedy(name) ), )); } From 6ebb0340321bf3a28f9f5ce2ea65045cde5092b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:09:18 +0000 Subject: [PATCH 6/8] Word the hosted remedy for an eject too The vendor eject of a hosted gem reaches the indented-declaration refusal through the backend, not the takeover preflight, so the preflight-only "keep it in hosted mode" wording missed it (the e2e eject tests failed). One wording now serves every caller: "leave to hosted mode (`--mode hosted`)", true whether or not the gem is hosted already. Refs #2091 Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_redirect_gem_build.rs | 4 +- crates/socket-patch-core/src/vendor/gem.rs | 62 ++++++------------- 2 files changed, 21 insertions(+), 45 deletions(-) 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 7513fca58..7c1cb7bc1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -3675,11 +3675,11 @@ fn vendor_eject_keeps_the_hosted_group_pin(fx: &RedirectFixture, dry_run: bool) ); // #2091: the refusal says how to get out of it. The gem is declared in // a `group :development do` block, which one top-level option replaces, - // and it is hosted already, so hosted mode is the mode to keep. + // and it is hosted already, so hosted mode is the mode to leave it to. let detail = events[0]["error"].as_str().unwrap_or_default(); assert!( detail.contains("move it to the top level with the option `group: :development`") - && detail.contains(&format!("or keep {DEP} in hosted mode")), + && detail.contains(&format!("or leave {DEP} to hosted mode (`--mode hosted`)")), "{label}: the refusal names both ways out: {env}" ); assert_eq!(env["error"]["code"], "eject_refused", "{label}: {env}"); diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 559cc034a..d5e0c436b 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -305,7 +305,7 @@ pub async fn gem_vendor_target_preflight( .await .ok()?, }; - plan_gemfile_edit_for(&gemfile_text, &name, &version, ©_rel, true) + plan_gemfile_edit(&gemfile_text, &name, &version, ©_rel) .and_then(|plan| refuse_append_of_direct_dependency(plan, &lock_text, &name)) .and_then(|plan| { let after = apply_gemfile_plan(&gemfile_text, &plan); @@ -1369,9 +1369,10 @@ fn platform_gem_remedy(name: &str) -> String { /// - Otherwise the top level is a way out, and so is hosted mode, which /// edits a declaration where it is. When exactly one block is open and it /// is a plain `group … do`, the `group:` option that replaces it is -/// spelled out ([`group_option`]). `hosted` is the takeover and eject -/// preflight, where the gem is in hosted mode already. -fn indented_declaration_remedy(text: &str, line_start: usize, name: &str, hosted: bool) -> String { +/// spelled out ([`group_option`]). The takeover and eject of a hosted gem +/// raise this refusal too, so hosted mode is worded as the mode to leave +/// the gem to, which reads true whether or not it is hosted already. +fn indented_declaration_remedy(text: &str, line_start: usize, name: &str) -> String { let frames = crate::formats::gem::ruby::block_stack(text, line_start); if frames.iter().any(|frame| frame.source.is_some()) { return format!("patch {name} with `--mode agent`"); @@ -1387,11 +1388,7 @@ fn indented_declaration_remedy(text: &str, line_start: usize, name: &str, hosted } _ => "move it to the top level".to_string(), }; - if hosted { - format!("{top_level} to vendor it, or keep {name} in hosted mode") - } else { - format!("{top_level}, or patch {name} with `--mode hosted`") - } + format!("{top_level}, or leave {name} to hosted mode (`--mode hosted`)") } /// The `group:` option that stands for the block `header` opens: @@ -1444,19 +1441,6 @@ fn plan_gemfile_edit( name: &str, version: &str, rel: &str, -) -> Result { - plan_gemfile_edit_for(text, name, version, rel, false) -} - -/// [`plan_gemfile_edit`], with `hosted` set when the gem is in hosted mode -/// already (the takeover and eject preflight): a refusal then does not -/// offer hosted mode as if it were news. -fn plan_gemfile_edit_for( - text: &str, - name: &str, - version: &str, - rel: &str, - hosted: bool, ) -> Result { let lines: Vec<&str> = text.split('\n').collect(); // (line idx, top-level?, paren-call?, quote, rest-after-name) @@ -1516,7 +1500,7 @@ fn plan_gemfile_edit_for( let rest = rest.strip_suffix('\r').unwrap_or(&rest); if !top_level { let line_start: usize = lines[..idx].iter().map(|line| line.len() + 1).sum(); - let remedy = indented_declaration_remedy(text, line_start, name, hosted); + let remedy = indented_declaration_remedy(text, line_start, name); return Err(format!( "the `gem \"{name}\"` declaration is indented (inside a group/conditional block); \ {remedy}" @@ -4031,12 +4015,12 @@ mod tests { /// only where one option means the same as the block. #[test] fn indented_declaration_remedy_fits_the_enclosing_block() { - let remedy = |gemfile: &str, hosted: bool| { + let remedy = |gemfile: &str| { let at = gemfile.find("gem \"rack\"").unwrap(); let line_start = gemfile[..at].rfind('\n').map_or(0, |i| i + 1); - indented_declaration_remedy(gemfile, line_start, "rack", hosted) + indented_declaration_remedy(gemfile, line_start, "rack") }; - let hosted_too = ", or patch rack with `--mode hosted`"; + let hosted_too = ", or leave rack to hosted mode (`--mode hosted`)"; for (gemfile, top_level) in [ ( "group :test do\n gem \"rack\", \"~> 3.1\", require: false\nend\n", @@ -4088,15 +4072,10 @@ mod tests { ), ] { assert_eq!( - remedy(gemfile, false), + remedy(gemfile), format!("{top_level}{hosted_too}"), "{gemfile:?}" ); - assert_eq!( - remedy(gemfile, true), - format!("{top_level} to vendor it, or keep rack in hosted mode"), - "{gemfile:?}" - ); } // Hosted mode refuses a gem inside a source-selecting block too // (`redirect_gem_source_option`), so it is never named there. @@ -4105,13 +4084,11 @@ mod tests { "git \"https://git.example/rack.git\" do\n gem \"rack\"\nend\n", "group :test do\n source \"https://gems.example\" do\n gem \"rack\"\n end\nend\n", ] { - for hosted in [false, true] { - assert_eq!( - remedy(gemfile, hosted), - "patch rack with `--mode agent`", - "{gemfile:?}" - ); - } + assert_eq!( + remedy(gemfile), + "patch rack with `--mode agent`", + "{gemfile:?}" + ); } } @@ -9952,10 +9929,9 @@ mod tests { let (code, detail) = refusal.expect("an indented declaration is not editable"); assert_eq!(code, "gemfile_declaration_not_editable"); assert!(detail.contains("indented"), "{detail}"); - // #2091: the gem is hosted already, so hosted mode is not offered - // as a mode to switch to. - assert!(detail.contains("keep rails in hosted mode"), "{detail}"); - assert_names_other_modes(&detail, &[]); + // #2091: the gem is hosted already; the remedy reads true for it. + assert!(detail.contains("leave rails to hosted mode"), "{detail}"); + assert_names_other_modes(&detail, &["hosted"]); // A preflight: the hosted pair is never written, even though the // caller's options are a wet run. assert_eq!(std::fs::read_to_string(dir.join(GEMFILE)).unwrap(), gemfile); From 2dc24834a96a24530fe51852eb730f69e1c3c2d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:21:06 +0000 Subject: [PATCH 7/8] Skip hosted in native remedy for source gems Bugbot: the native-extension refusal is raised before the Gemfile plan, so a native gem inside a source, git, github or path block, or with one of the source options, was still sent to hosted mode, which refuses it (redirect_gem_source_option). The remedy now names agent mode alone for such a declaration. Refs #2091 Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/vendor/gem.rs | 114 +++++++++++++++++++-- docs/ecosystems.md | 2 +- 2 files changed, 109 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index d5e0c436b..00b802b9b 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -492,7 +492,7 @@ async fn gem_prelude( "native_extensions_unsupported", format!( "{leaf}.gemspec declares native extensions; bundler does not build extensions for path-sourced gems. {}", - native_extensions_remedy(name) + native_extensions_remedy(name, !declaration_selects_source(&gemfile_text, name)) ), )); } @@ -1049,7 +1049,9 @@ pub(super) async fn gem_service_copy( format!( "the served stub gemspec for {name} declares native extensions; bundler does \ not build extensions for path-sourced gems. {}", - native_extensions_remedy(name) + // The Gemfile plan passed before the service was asked, so + // the declaration is one hosted mode can edit too. + native_extensions_remedy(name, true) ), )); } @@ -1342,13 +1344,60 @@ enum GemfilePlan { Append { block: String }, } -/// The way out of a native-extension refusal (#2091): the two modes that +/// The way out of a native-extension refusal (#2091): the modes that /// compile the extension ("Ruby gems: native extensions" in /// `docs/ecosystems.md`). Worded as hosted mode words its own refusals /// ("patch with `--mode vendored` or `--mode agent`"): it names the -/// mode for this gem, not a whole-project command. -fn native_extensions_remedy(name: &str) -> String { - format!("Patch {name} with `--mode hosted` or `--mode agent`, which build the extension") +/// mode for this gem, not a whole-project command. `hosted` is false when +/// hosted mode would refuse the gem's declaration as well +/// ([`declaration_selects_source`]), and agent mode alone is named. +fn native_extensions_remedy(name: &str, hosted: bool) -> String { + let modes = if hosted { + "`--mode hosted` or `--mode agent`, which build" + } else { + "`--mode agent`, which builds" + }; + format!("Patch {name} with {modes} the extension") +} + +/// Whether a `gem ""` declaration of the Gemfile `text` picks the +/// gem's source: it sits inside a `source` / `git` / `github` / `path` +/// block, or carries one of the source options. Hosted mode refuses such a +/// gem (`redirect_gem_source_option`), so a remedy must not name it. +/// Errs towards `true`: a mode left out of a remedy costs less than one +/// that refuses. +fn declaration_selects_source(text: &str, name: &str) -> bool { + const SOURCE_OPTIONS: [&str; 6] = ["source", "git", "github", "path", "gist", "bitbucket"]; + let mut line_start = 0; + for line in text.split('\n') { + let start = line_start; + line_start += line.len() + 1; + let trimmed = line.trim_start(); + if trimmed.starts_with('#') { + continue; + } + let Some(decl) = gem_declaration(trimmed, name) else { + continue; + }; + if crate::formats::gem::ruby::block_stack(text, start) + .iter() + .any(|frame| frame.source.is_some()) + { + return true; + } + let code = decl.rest.split('#').next().unwrap_or(""); + let names_source = code + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == ':')) + .any(|word| { + // `git: "…"` and the hash-rocket `:git => "…"`. + let key = word.strip_suffix(':').or_else(|| word.strip_prefix(':')); + key.is_some_and(|key| SOURCE_OPTIONS.contains(&key)) + }); + if names_source { + return true; + } + } + false } /// The way out of a platform-build refusal (#2091). Agent mode only: hosted @@ -4141,6 +4190,59 @@ mod tests { ); } + /// #2091 (review): hosted mode refuses a gem whose declaration picks + /// its source, so the native-extension remedy names agent mode alone + /// for it. + #[tokio::test] + async fn test_native_extension_remedy_skips_hosted_for_a_source_selecting_declaration() { + for gemfile in [ + "source \"https://rubygems.org\"\n\nsource \"https://gems.example\" do\n gem \"rack\", \"~> 3.1\"\nend\n", + "source \"https://rubygems.org\"\n\ngem \"rack\", git: \"https://git.example/rack.git\"\n", + "source \"https://rubygems.org\"\n\ngem \"rack\", \"~> 3.1\", :source => \"https://gems.example\"\n", + ] { + let (_tmp, root, installed, blobs, record) = fixture(gemfile, LOCK_DIRECT).await; + let spec = installed + .parent() + .unwrap() + .parent() + .unwrap() + .join("specifications/rack-3.2.6.gemspec"); + tokio::fs::write( + &spec, + "Gem::Specification.new do |s|\n s.name = \"rack\"\n s.extensions = [\"ext/rack/extconf.rb\"]\nend\n", + ) + .await + .unwrap(); + let (code, detail) = + unwrap_refused(run_vendor(&root, &blobs, &installed, &record, false).await); + assert_eq!(code, "native_extensions_unsupported", "{gemfile:?}"); + assert_names_other_modes(&detail, &["agent"]); + } + } + + #[test] + fn declaration_selects_source_reads_blocks_and_options() { + for (gemfile, want) in [ + ("gem \"rack\"\n", false), + ("gem \"rack\", \"~> 3.1\", require: false, group: :test\n", false), + ("group :test do\n gem \"rack\"\nend\n", false), + // Another gem's source is not this gem's. + ("gem \"puma\", git: \"https://git.example/puma.git\"\ngem \"rack\"\n", false), + ("gem \"rack\" # path: \"../rack\"\n", false), + ("gem \"rack\", path: \"../rack\"\n", true), + ("gem \"rack\", github: \"rack/rack\"\r\n", true), + ("gem \"rack\", :git => \"https://git.example/rack.git\"\n", true), + ("gem \"rack\", source: \"https://gems.example\"\n", true), + ("path \"components\" do\n gem \"rack\"\nend\n", true), + ( + "group :test do\n source \"https://gems.example\" do\n gem \"rack\"\n end\nend\n", + true, + ), + ] { + assert_eq!(declaration_selects_source(gemfile, "rack"), want, "{gemfile:?}"); + } + } + #[tokio::test] async fn test_refuses_platform_suffixed_dir() { let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a3ec4348b..5815fe9b6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2005,7 +2005,7 @@ that can patch the gem: | Code | The gem | What the error offers | |---|---|---| | `gemfile_declaration_not_editable` ("is indented") | is declared inside a block: `group :test do`, `platforms … do`, a conditional. Every Rails Gemfile declares its development and test gems this way. | Move the declaration to the top level (for a plain `group` block the error spells the option that replaces it, `group: :test`), or patch the gem with `--mode hosted`, which edits a declaration where it is. Inside a `source`, `git`, `github` or `path` block hosted mode refuses the gem too, and the error names `--mode agent`. | -| `native_extensions_unsupported` | builds a native extension (puma, bootsnap). | `--mode hosted` or `--mode agent`. Both build the extension. | +| `native_extensions_unsupported` | builds a native extension (puma, bootsnap). | `--mode hosted` or `--mode agent`. Both build the extension. Only `--mode agent` when the declaration picks the gem's source (a `source`, `git`, `github` or `path` block or option), which hosted mode refuses. | | `platform_gem_unsupported` | is installed as a precompiled platform build (`nokogiri-1.18.3-x86_64-linux-gnu`). | `--mode agent`. Hosted mode refuses a precompiled build too. | To patch one gem in another mode, name it: `socket-patch get --mode hosted`. A whole-project From 5de08b62f28900709813a77c5a70a802c02adc00 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:20:03 +0000 Subject: [PATCH 8/8] Read gem source options with the shared reader declaration_selects_source kept its own list of source keys, which left out `gitlab:` and custom `git_source` keys that hosted mode refuses (redirect_gem_source_option). For such a gem with a native extension the remedy named `--mode hosted`, a mode that refuses it as well. Use gemfile::source_option, the reader hosted mode refuses with. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011f9aeNxATwEfTmV9fd2wYR --- crates/socket-patch-core/src/vendor/gem.rs | 24 +++++++++------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 00b802b9b..30881a61c 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -1362,12 +1362,13 @@ fn native_extensions_remedy(name: &str, hosted: bool) -> String { /// Whether a `gem ""` declaration of the Gemfile `text` picks the /// gem's source: it sits inside a `source` / `git` / `github` / `path` -/// block, or carries one of the source options. Hosted mode refuses such a -/// gem (`redirect_gem_source_option`), so a remedy must not name it. -/// Errs towards `true`: a mode left out of a remedy costs less than one -/// that refuses. +/// block, or carries a source option, read by the shared +/// [`gemfile::source_option`] that hosted mode refuses with (so `gitlab:` +/// and custom `git_source` keys count too). Hosted mode refuses such a gem +/// (`redirect_gem_source_option`), so a remedy must not name it. Errs +/// towards `true`: a mode left out of a remedy costs less than one that +/// refuses. fn declaration_selects_source(text: &str, name: &str) -> bool { - const SOURCE_OPTIONS: [&str; 6] = ["source", "git", "github", "path", "gist", "bitbucket"]; let mut line_start = 0; for line in text.split('\n') { let start = line_start; @@ -1385,15 +1386,7 @@ fn declaration_selects_source(text: &str, name: &str) -> bool { { return true; } - let code = decl.rest.split('#').next().unwrap_or(""); - let names_source = code - .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == ':')) - .any(|word| { - // `git: "…"` and the hash-rocket `:git => "…"`. - let key = word.strip_suffix(':').or_else(|| word.strip_prefix(':')); - key.is_some_and(|key| SOURCE_OPTIONS.contains(&key)) - }); - if names_source { + if gemfile::source_option(decl.rest).is_some() { return true; } } @@ -4233,6 +4226,9 @@ mod tests { ("gem \"rack\", github: \"rack/rack\"\r\n", true), ("gem \"rack\", :git => \"https://git.example/rack.git\"\n", true), ("gem \"rack\", source: \"https://gems.example\"\n", true), + // Hosted mode refuses every source key, not only the built-in ones. + ("gem \"rack\", gitlab: \"rack/rack\"\n", true), + ("gem \"rack\", \"~> 3.1\", forge: \"rack/rack\"\n", true), ("path \"components\" do\n gem \"rack\"\nend\n", true), ( "group :test do\n source \"https://gems.example\" do\n gem \"rack\"\n end\nend\n",