diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a19a36417..f5aff2608 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -423,7 +423,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, 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 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, as `rollback` selects its pin: without the patch record's qualifiers such as `?platform=ruby`, so a shell passes it on whole; 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. diff --git a/crates/socket-patch-cli/src/commands/list.rs b/crates/socket-patch-cli/src/commands/list.rs index d4d9f2b69..5a3d30274 100644 --- a/crates/socket-patch-cli/src/commands/list.rs +++ b/crates/socket-patch-cli/src/commands/list.rs @@ -1088,7 +1088,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed { more; `socket-patch remove {}` removes that entry alone", pin.files.join(", "), pin.purl, - pin.purl + crate::ui::shell_word(&pin.purl) ) } else { format!( @@ -1097,7 +1097,7 @@ async fn list_project(args: &ListArgs, browsing: bool) -> Listed { uv_metadata.join(", "), pin.purl, pin.files.join(", "), - pin.purl + crate::ui::shell_word(&pin.purl) ) }; if args.common.json { diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 4cbed5e85..19972dc6d 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -351,18 +351,26 @@ async fn patched_in_other_scope( /// `rollback`'s pointer at the scope that still holds a patched copy: a /// rollback of just that purl, naming `--cwd` when the run used one (the record lives in that -/// project's manifest). +/// project's manifest). The command names the release without the record's +/// qualifiers (`?platform=ruby`, `?artifact_id=...`): the record was kept +/// with its whole variant group, a base purl selects that group, and a `?` +/// is a glob character to the shell. The purl and the directory are quoted +/// where a shell would otherwise read them as more than one word. fn patched_in_other_scope_warning(purl: &str, path: &Path, common: &GlobalArgs) -> String { + let word = crate::ui::shell_word(strip_purl_qualifiers(purl)); let (scope, mut command) = if common.is_global() { - ("the project", format!("socket-patch rollback {purl}")) + ("the project", format!("socket-patch rollback {word}")) } else { ( "the global install", - format!("socket-patch rollback {purl} -g"), + format!("socket-patch rollback {word} -g"), ) }; if common.cwd != Path::new(".") { - command.push_str(&format!(" --cwd {}", common.cwd.display())); + command.push_str(&format!( + " --cwd {}", + crate::ui::shell_word(&common.cwd.to_string_lossy()) + )); } format!( "{purl}: its copy in {scope} ({}) is still patched or could not be \ @@ -4496,6 +4504,52 @@ mod tests { use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use std::collections::HashMap; + /// The command this warning tells the user to run is one they paste. + /// A record's purl can carry qualifiers (`?platform=ruby`, + /// `?artifact_id=...`), and `?` is a glob character: the command names + /// the release, which selects the variant group the run kept. What is + /// left that a shell reads specially (`%40`, a space in `--cwd`) is + /// quoted (#2182). + #[test] + fn other_scope_warning_prints_a_command_a_shell_reads_as_written() { + let quoted = |word: &str| { + if cfg!(windows) { + format!("\"{word}\"") + } else { + format!("'{word}'") + } + }; + let purl = "pkg:gem/rack@3.1.8?platform=ruby"; + let path = Path::new("/gems/rack-3.1.8"); + let local = crate::args::GlobalArgs::default(); + let warning = patched_in_other_scope_warning(purl, path, &local); + assert!( + warning.contains("run `socket-patch rollback pkg:gem/rack@3.1.8 -g` to"), + "{warning}" + ); + // The message's own naming of the record stays its full purl. + assert!( + warning.starts_with(&format!("{purl}: its copy in")), + "{warning}" + ); + + let scoped = "pkg:npm/%40scope/a@1.0.0"; + let global = crate::args::GlobalArgs { + global: true, + cwd: PathBuf::from("my app"), + ..crate::args::GlobalArgs::default() + }; + let warning = patched_in_other_scope_warning(scoped, path, &global); + assert!( + warning.contains(&format!( + "run `socket-patch rollback {} --cwd {}` to", + quoted(scoped), + quoted("my app") + )), + "{warning}" + ); + } + // The legacy path-taking delegation shape, kept for the unit tests below // (`remove` now threads its already-loaded manifest and ledger straight // into `rollback_patches_inner`; this wrapper reads them from disk). The diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index 923d813b1..1b388fcf9 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -396,12 +396,13 @@ async fn keep_patched_cargo_copies( prunable.retain(|p| !kept.contains(p)); kept.into_iter() .map(|purl| { + let word = crate::ui::shell_word(&purl); ( "cargo_cache_patch_kept", format!( "kept {purl}: the project no longer resolves it, but its copy in the \ shared Cargo registry cache is still patched (or could not be \ - read to tell); run `socket-patch rollback {purl}` (with `--global` \ + read to tell); run `socket-patch rollback {word}` (with `--global` \ when a `cargo vendor` dir hides the registry cache) to restore \ that copy and drop the entry" ), @@ -435,12 +436,13 @@ async fn keep_patched_pypi_copies( prunable.retain(|p| !kept.contains(p)); kept.into_iter() .map(|purl| { + let word = crate::ui::shell_word(&purl); ( "pypi_installed_patch_kept", format!( "kept {purl}: the scan no longer reports it as one of the project's \ packages, but an installed copy is still patched (or could not be \ - read to tell); run `socket-patch rollback {purl}` (with `--global` \ + read to tell); run `socket-patch rollback {word}` (with `--global` \ when the copy is in another interpreter or a tool's environment) \ to restore that copy and drop the entry" ), diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index dbdbdfe91..50d0d5c8a 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -141,7 +141,10 @@ fn mirror_pins_not_moved( `socket-patch rollback {}` and then this command again", c.purl, mirror_sources.base(), - c.purl + // As `rollback` selects a hosted pin: no qualifiers. + crate::ui::shell_word(socket_patch_core::utils::purl::strip_purl_qualifiers( + &c.purl + )) ), )) }) @@ -3277,23 +3280,32 @@ fn format_gem_hold_note( if dry_run { return Some(note); } - // The one gem's own purl, when exactly one confirmed pin carries its - // name; else the shape of one, for the user to fill in. + // The one gem's own pin, when the confirmed pins of its name are one + // release; else the shape of one, for the user to fill in. A pin is + // named as `rollback` selects it, without the record's qualifiers + // (`?platform=ruby` on every gem record): with them the command + // matches no hosted pin, and under bash's `nullglob` the unquoted `?` + // drops the argument, leaving the bare `rollback` this note must not + // give. let purl = one.and_then(|name| { let prefix = format!("pkg:gem/{name}@"); - let mut pins = confirmed + let mut pins: Vec<&str> = confirmed .iter() - .map(|(purl, _)| purl.as_str()) - .filter(|purl| purl.starts_with(&prefix)); - match (pins.next(), pins.next()) { - (Some(purl), None) => Some(purl), + .map(|(purl, _)| socket_patch_core::utils::purl::strip_purl_qualifiers(purl)) + .filter(|purl| purl.starts_with(&prefix)) + .collect(); + pins.sort_unstable(); + pins.dedup(); + match pins.as_slice() { + [purl] => Some(crate::ui::shell_word(purl)), _ => None, } }); + let placeholder = || "pkg:gem/@".to_string(); let (move_one, target, update_arg) = match (one, purl) { (Some(name), Some(purl)) => ("it", purl, name), - (Some(name), None) => ("it", "pkg:gem/@", name), - (None, _) => ("one", "pkg:gem/@", ""), + (Some(name), None) => ("it", placeholder(), name), + (None, _) => ("one", placeholder(), ""), }; let again = if command == "scan" { "then `socket-patch scan` again" @@ -5938,6 +5950,42 @@ mod tests { `socket-patch scan` again." ) ); + // A gem record's purl carries `?platform=ruby`. The note names the + // pin as `rollback` selects it, without the qualifier: with it the + // command matches no hosted pin, and its `?` is a glob character + // that zsh refuses and bash under `nullglob` drops, leaving a bare + // `rollback` (#2182). + let qualified = [ + pin("pkg:gem/rack@3.1.8?platform=ruby"), + pin("pkg:gem/nokogiri@1.16.0?platform=x86_64-linux"), + ]; + for command in ["scan", "get"] { + let note = + super::format_gem_hold_note(&edits[..1], &qualified, command, false).unwrap(); + assert!( + note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"), + "{note}" + ); + assert!(!note.contains('?'), "{note}"); + } + // Two records of the one release (a ruby and a platform build) are + // one pin, so the note still names it. + let builds = [ + pin("pkg:gem/rack@3.1.8?platform=ruby"), + pin("pkg:gem/rack@3.1.8?platform=x86_64-linux"), + ]; + let note = super::format_gem_hold_note(&edits[..1], &builds, "scan", false).unwrap(); + assert!( + note.contains("run `socket-patch rollback pkg:gem/rack@3.1.8`, then"), + "{note}" + ); + // Two versions of it are two pins: the user fills in which. + let versions = [pin("pkg:gem/rack@3.1.8"), pin("pkg:gem/rack@2.2.8")]; + let note = super::format_gem_hold_note(&edits[..1], &versions, "scan", false).unwrap(); + assert!( + note.contains("run `socket-patch rollback pkg:gem/@`, then"), + "{note}" + ); // No bare `socket-patch rollback` anywhere: it unwinds every patch. for edits in [&edits[..], &edits[..1]] { for confirmed in [&confirmed[..], &[]] { diff --git a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs index 24bc86af1..f86d4bc18 100644 --- a/crates/socket-patch-cli/src/commands/scan/withdrawn.rs +++ b/crates/socket-patch-cli/src/commands/scan/withdrawn.rs @@ -246,7 +246,9 @@ pub(super) async fn sweep( "{} is pinned to patch {}, which is no longer published \ ({status}), but it was not restored: {message}; re-run, or run \ `socket-patch rollback {}`", - pin.purl, pin.uuid, pin.purl + pin.purl, + pin.uuid, + crate::ui::shell_word(&pin.purl) ), ); } 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 201ee5f4c..e429489d7 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -6345,6 +6345,73 @@ async fn release_upstream_1_1_0(fx: &RedirectFixture) { } } +/// Serve the patch record's purl the way the patch service spells a gem +/// record's: with its `?platform=ruby` qualifier, on every route that +/// carries it (the package a batch result is filed under stays bare). Each +/// route answers what the fixture's own does, respelled, and outranks it. +async fn serve_record_purl_with_platform(fx: &RedirectFixture) { + let api = fx._server.uri(); + let bare = format!("\"purl\":\"{PURL}\""); + let qualified = format!("\"purl\":\"{PURL}?platform=ruby\""); + let client = reqwest::Client::new(); + let post = |route: &str| client.post(format!("{api}{route}")).body("{}"); + let get = |route: &str| client.get(format!("{api}{route}")); + let batch = format!("/v0/orgs/{ORG}/patches/batch"); + let by_package = format!("/v0/orgs/{ORG}/patches/by-package/{DEP}"); + let reference = format!("/v0/orgs/{ORG}/patches/package"); + let view = format!("/v0/orgs/{ORG}/patches/view/{UUID}"); + for (verb, route, request, keep_first) in [ + ("POST", batch.as_str(), post(&batch), true), + ("GET", by_package.as_str(), get(&by_package), false), + ("POST", reference.as_str(), post(&reference), false), + ("GET", view.as_str(), get(&view), false), + ] { + let body = request + .send() + .await + .expect("fixture API reachable") + .text() + .await + .expect("fixture API body"); + assert!(body.contains(&bare), "{route} carries the purl: {body}"); + let respelled = if keep_first { + let (head, tail) = body.split_once(&bare).expect("checked above"); + format!("{head}{bare}{}", tail.replace(&bare, &qualified)) + } else { + body.replace(&bare, &qualified) + }; + assert!(respelled.contains(&qualified), "{route}: {respelled}"); + let matcher = if route == by_package { + Mock::given(method(verb)).and(path_regex(format!( + "^/v0/orgs/{ORG}/patches/by-package/.+$" + ))) + } else { + Mock::given(method(verb)).and(path(route)) + }; + matcher + .respond_with(ResponseTemplate::new(200).set_body_raw(respelled, "application/json")) + .with_priority(1) + .mount(&fx._server) + .await; + } +} + +/// The words a bash with `nullglob` set reads `command` as: a word that +/// holds an unquoted glob character and matches no file is dropped. +fn bash_nullglob_words(cwd: &Path, command: &str) -> Vec { + let out = Command::new("bash") + .args(["-O", "nullglob", "-c", &format!("printf '%s\\n' {command}")]) + .current_dir(cwd) + .output() + .expect("bash runs"); + assert!(out.status.success(), "bash reads `{command}`: {out:?}"); + String::from_utf8(out.stdout) + .expect("utf8 words") + .lines() + .map(str::to_owned) + .collect() +} + /// A hosted gem's only source is its patch's registry, which serves one /// version, so the gem leaves `bundle outdated` and `bundle update` cannot /// move it (#2070). The scan has to say so, and what it says has to be true @@ -6352,6 +6419,10 @@ async fn release_upstream_1_1_0(fx: &RedirectFixture) { /// lists the gem before the scan and not after, `bundle update` leaves the /// scanned lock at the patched version, and the way past the hold the scan /// names (`rollback`, then `bundle update `) does move the gem. +/// +/// The `rollback` it names is run as printed, through a shell (#2182): the +/// record's purl carries `?platform=ruby`, which selects no hosted pin and +/// which a shell globs, so the command names the pin without it. #[tokio::test(flavor = "multi_thread")] #[ignore = "host capstone: shells out to a real ruby/gem/bundler (>= 1.17); \ the unpinned `test` job skips it, an e2e job with a pinned toolchain runs it via --ignored"] @@ -6430,6 +6501,7 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { // The scan, in human output: it names the gem it now holds and the way // past the hold. + serve_record_purl_with_platform(&fx).await; let (code, stdout, stderr) = run_socket( &fx.proj, &[ @@ -6477,8 +6549,47 @@ async fn gem_hosted_scan_says_the_gem_is_held_at_its_version() { ); // And the way past it works: roll back, then `bundle update `. + // The rollback is the command the note printed, as a shell reads it. std::fs::write(&lock_path, &scanned_lock).unwrap(); - rollback(); + let printed = stdout + .lines() + .find(|line| line.starts_with("Bundler now takes ")) + .and_then(|line| { + line.split('`') + .find(|span| span.starts_with("socket-patch rollback ")) + }) + .expect("the scan's hold line names a rollback"); + let words = bash_nullglob_words(&fx.proj, printed); + assert_eq!( + words, + ["socket-patch", "rollback", PURL], + "a shell passes the printed command on whole" + ); + let mut argv: Vec<&str> = words[1..].iter().map(String::as_str).collect(); + argv.extend([ + "--json", + "--cwd", + cwd, + "--api-url", + &api, + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &api, + ]); + let (code, stdout, stderr) = + run_socket_env(&fx.proj, &argv, &[("SOCKET_RUBYGEMS_URL", &upstream)]); + assert_eq!( + code, 0, + "`{printed}`:\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + String::from_utf8_lossy(&std::fs::read(&lock_path).unwrap()), + String::from_utf8_lossy(&fx.pristine_lock), + "`{printed}` hands the lock back byte for byte" + ); let (updated, update) = bundle_cold(&["update", DEP]); assert!(updated, "`bundle update {DEP}` after rollback:\n{update}"); assert!(