diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 95045cd462..3678099309 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -511,7 +511,7 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What is reported.* - Each refreshed materialization is a `redirect_gem_install_refreshed` note in the JSON `warnings[]`; a human run prints one progress line per kind instead (`Replaced the installed copy of 2 gems with the patched build: …`). A replaced cache-dir archive is listed with the files to commit. -- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; no delete list for a copy that was only left alone); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. +- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; no delete list for a copy that was only left alone); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one; where `bundle install` would not replace the copy, the list starts with the gem directory itself, holds only the files that are still there, and the human warning's command is `rm -rf … && bundle install`: after a refresh that was tried and failed, a copy whose native extension a Ruby the run asked builds into another gem home (one in the tree of an earlier Ruby, `vendor/bundle/ruby/3.2.0`), for which the re-run named is one "with the Ruby that installed the gem first on `PATH`", and a gem directory whose gemspec is gone, for which no re-run is named); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 0f508d5ec8..f23b3f4d8c 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -159,7 +159,7 @@ impl Policy { return Err(Why::Disabled); } if !self.shared && !resolves_inside(&self.root, path) { - return Err(Why::Failed( + return Err(Why::OutOfTree( match direction { Direction::Patched => { "it is outside the project directory; `--gem-refresh-shared` refreshes \ @@ -193,6 +193,9 @@ pub(crate) enum Why { Disabled, /// The refresh was tried, or could not be. Failed(String), + /// The copy resolves outside the project directory and was left alone + /// for it: no refresh was tried. + OutOfTree(String), /// Nothing says which build the copy holds: the sha256 of the wanted /// gem could not be had, for this reason. It is not known to be stale, /// and not known not to be. @@ -383,6 +386,74 @@ fn files_to_remove(gem: &StaleGem) -> Vec { files } +/// Whether no gem home lists the gem dir `/gems/`: neither +/// `specifications/.gemspec` nor the default gem's entry under +/// `specifications/default/` is there. Only "not found" says so. +fn gemspec_is_gone(gem_dir: &Path) -> bool { + let Some(spec) = home_spec(gem_dir) else { + return false; + }; + let default = spec.parent().zip(spec.file_name()); + let Some(default) = default.map(|(specs, name)| specs.join("default").join(name)) else { + return false; + }; + [spec, default].iter().all(|path| { + matches!(std::fs::metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + }) +} + +/// Why `bundle install` cannot be counted on to replace a copy once its +/// gemspec and archive are removed (#2242). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Outlives { + /// A Ruby the run asked installs this gem somewhere else than the + /// copy's gem home (the tree of an earlier Ruby, + /// `vendor/bundle/ruby/3.2.0`). `bundle install` + /// installs into the gem home of the Ruby that runs it, so the gem dir + /// would stay behind with no gemspec. + ForeignRuby, + /// The gemspec is gone already: the gem dir is what is left of an + /// install, and nothing puts a gem back over it. + NoGemspec, +} + +/// Whether the remedy for `gem`'s installed copy has to remove the gem +/// dir itself, and why. Only a copy a refresh failed on, never one left +/// alone (a shared home, a path outside the project, +/// `--no-gem-install-refresh`) or patched in place. +fn outlives_reinstall(gem: &StaleGem, why: Option<&Why>) -> Option { + let (Some((dir, _)), false, Some(Why::Failed(reason))) = (&gem.installed, gem.in_place, why) + else { + return None; + }; + if gemspec_is_gone(dir) { + Some(Outlives::NoGemspec) + } else if reason.contains(socket_patch_core::patch::gem_ext::OWNED_BY_ANOTHER_RUBY) { + Some(Outlives::ForeignRuby) + } else { + None + } +} + +/// What the remedy for a copy left for `why` removes, and whether a gem +/// dir is among it: [`files_to_remove`], behind the gem dir where +/// `bundle install` would not replace it ([`outlives_reinstall`]). Such a +/// remedy names only what is on disk: it is offered again after the old +/// one removed the files. +fn remedy_paths(gem: &StaleGem, why: Option<&Why>) -> (Vec, bool) { + let files = files_to_remove(gem); + let (Some(_), Some((dir, _))) = (outlives_reinstall(gem, why), &gem.installed) else { + return (files, false); + }; + let mut paths = vec![dir.clone()]; + paths.extend( + files + .into_iter() + .filter(|path| std::fs::symlink_metadata(path).is_ok()), + ); + (paths, true) +} + /// What the upstream archive beside an in-place patch does once the lock /// pins the patched gem. const IN_PLACE_REINSTALL: &str = "`bundle pristine` and `bundle install --redownload` reinstall \ @@ -399,12 +470,23 @@ fn display_list(paths: &[PathBuf]) -> String { /// How a refresh that did not happen is retried. An unwind can't be: its /// first run removed the wiring a second one would look for. -fn retry_hint(direction: Direction, why: Option<&Why>) -> &'static str { +/// +/// `outlives` is why the copies the hint is for outlive a reinstall, when +/// every one of them does: a gem dir with no gemspec fails a re-run the +/// same way, and a copy no Ruby owns needs its Ruby found first. +fn retry_hint(direction: Direction, why: Option<&Why>, outlives: Option) -> &'static str { match (why, direction) { + (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::NoGemspec) => "", + (Some(Why::Failed(_)), Direction::Patched) if outlives == Some(Outlives::ForeignRuby) => { + "Re-run `socket-patch scan` with the Ruby that installed the gem first on `PATH` \ + to retry, or " + } (Some(Why::Disabled), Direction::Patched) => { "Re-run without `--no-gem-install-refresh`, or " } - (Some(Why::Failed(_)), Direction::Patched) => "Re-run `socket-patch scan` to retry, or ", + (Some(Why::Failed(_) | Why::OutOfTree(_)), Direction::Patched) => { + "Re-run `socket-patch scan` to retry, or " + } _ => "", } } @@ -434,12 +516,18 @@ fn shell_word(path: &Path) -> String { } /// The `rm -f … && bundle install` that makes Bundler fetch again the gems -/// `files` belong to. -fn reinstall_command(files: &[PathBuf]) -> String { +/// `files` belong to; `rm -rf` where a gem dir is among them +/// ([`remedy_paths`]). +fn reinstall_command(files: &[PathBuf], with_dirs: bool) -> String { let words: Vec = files.iter().map(|path| shell_word(path)).collect(); - format!("rm -f {} && bundle install", words.join(" ")) + let rm = if with_dirs { "rm -rf" } else { "rm -f" }; + format!("{rm} {} && bundle install", words.join(" ")) } +/// Why a remedy removes a gem dir, after the remedy. +const GEM_DIR_REMOVED: &str = "The gem directory is removed too: `bundle install` does not \ + replace a copy that has no gemspec or is in the gem home of another Ruby"; + /// `action` after `hint` (which ends mid-sentence), or as a sentence of /// its own when there is none. fn after_hint(hint: &str, action: &str) -> String { @@ -452,7 +540,9 @@ fn after_hint(hint: &str, action: &str) -> String { fn reason(why: Option<&Why>) -> String { match why { - Some(Why::Failed(reason) | Why::Unverified(reason)) => format!(" ({reason})"), + Some(Why::Failed(reason) | Why::OutOfTree(reason) | Why::Unverified(reason)) => { + format!(" ({reason})") + } Some(Why::Disabled) => " (`--no-gem-install-refresh` is set)".to_string(), _ => String::new(), } @@ -473,7 +563,11 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh dir.display(), archive.display() ); - return if !project_local && !matches!(why, Some(Why::Disabled | Why::Failed(_))) { + return if !project_local + && !matches!( + why, + Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_)) + ) { format!( "{held}. {IN_PLACE_REINSTALL}. Other projects may load that shared gem home, so \ it was left alone. Install the {wanted} gem for this project only with \ @@ -485,7 +579,7 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh "{held}, which was not replaced{}. {IN_PLACE_REINSTALL}. {}", reason(why), after_hint( - retry_hint(direction, why), + retry_hint(direction, why, None), &format!( "remove {} and run `bundle install`", display_list(&files_to_remove(gem)) @@ -509,35 +603,47 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh ) ), ), - Some((dir, false)) if !matches!(why, Some(Why::Disabled | Why::Failed(_))) => format!( - "{purl} {switched}, but the shared gem home still holds its {stale} install at \ + Some((dir, false)) + if !matches!( + why, + Some(Why::Disabled | Why::Failed(_) | Why::OutOfTree(_)) + ) => + { + format!( + "{purl} {switched}, but the shared gem home still holds its {stale} install at \ {}, and {reuse}. Other projects may load that gem home, so it was left alone. \ Install the {wanted} gem for this project only with `{LOCAL_PATH_REMEDY}`, or {}", - dir.display(), - match direction { - Direction::Patched => { - "re-run with `--gem-refresh-shared` to replace the shared copy".to_string() + dir.display(), + match direction { + Direction::Patched => { + "re-run with `--gem-refresh-shared` to replace the shared copy".to_string() + } + Direction::Upstream => format!( + "replace the shared copy: remove {} and run `bundle install` ({})", + display_list(&files_to_remove(gem)), + other_projects_cost(1) + ), } - Direction::Upstream => format!( - "replace the shared copy: remove {} and run `bundle install` ({})", - display_list(&files_to_remove(gem)), - other_projects_cost(1) + ) + } + Some((dir, _)) => { + let (paths, with_dir) = remedy_paths(gem, why); + format!( + "{purl} {switched}, but its {stale} install at {} was not refreshed{}, and \ + {reuse}. {}{}", + dir.display(), + reason(why), + after_hint( + retry_hint(direction, why, outlives_reinstall(gem, why)), + &format!("remove {} and run `bundle install`", display_list(&paths)) ), - } - ), - Some((dir, _)) => format!( - "{purl} {switched}, but its {stale} install at {} was not refreshed{}, and \ - {reuse}. {}", - dir.display(), - reason(why), - after_hint( - retry_hint(direction, why), - &format!( - "remove {} and run `bundle install`", - display_list(&files_to_remove(gem)) - ) - ), - ), + if with_dir { + format!(". {GEM_DIR_REMOVED}") + } else { + String::new() + }, + ) + } None => format!( "{purl} {switched}, but Bundler's cache dir still holds its {stale} archive at \ {}, which was not replaced{}. Bundler installs from that dir before it fetches, \ @@ -548,7 +654,7 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh .display(), reason(why), after_hint( - retry_hint(direction, why), + retry_hint(direction, why, None), "delete it and run `bundle cache`" ), ), @@ -811,14 +917,29 @@ pub(crate) fn report( Direction::Upstream => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`. To \ replace the shared {copies}, run `{}`; {}.", - reinstall_command(&shared_files), + reinstall_command(&shared_files, false), other_projects_cost(shared_gems) ), }); } for (why, gems) in &local { - let files: Vec = gems.iter().flat_map(|gem| files_to_remove(gem)).collect(); - let reinstall = format!("run `{}`", reinstall_command(&files)); + let (mut files, mut with_dirs) = (Vec::new(), false); + for gem in gems { + let (paths, with_dir) = remedy_paths(gem, Some(why)); + files.extend(paths); + with_dirs |= with_dir; + } + // The hint of a copy that outlives a reinstall, when all do, for + // the same reason: else a plain re-run still does something. + let outlives = gems + .iter() + .map(|gem| outlives_reinstall(gem, Some(why))) + .reduce(|all, one| if all == one { all } else { None }) + .flatten(); + let mut reinstall = format!("run `{}`", reinstall_command(&files, with_dirs)); + if with_dirs { + reinstall.push_str(&format!(". {GEM_DIR_REMOVED}")); + } let names = labels(gems.iter().map(|gem| gem.purl.as_str())); bullets.push(match why { Why::Unverified(_) => format!( @@ -829,7 +950,7 @@ pub(crate) fn report( _ => format!( "Not refreshed{}: {names}. {}.", reason(Some(why)), - after_hint(retry_hint(direction, Some(why)), &reinstall), + after_hint(retry_hint(direction, Some(why), outlives), &reinstall), ), }); } @@ -1683,10 +1804,14 @@ mod tests { } } - /// `/gems/-1.0.0` created on disk, as a stale gem. + /// `/gems/-1.0.0` created on disk with its + /// `specifications` entry, as a stale gem. fn installed(name: &str, home: &Path, project_local: bool) -> StaleGem { let dir = home.join("gems").join(format!("{name}-1.0.0")); std::fs::create_dir_all(&dir).unwrap(); + let specs = home.join("specifications"); + std::fs::create_dir_all(&specs).unwrap(); + std::fs::write(specs.join(format!("{name}-1.0.0.gemspec")), "").unwrap(); StaleGem { purl: format!("pkg:gem/{name}@1.0.0"), leaf: format!("{name}-1.0.0"), @@ -2238,6 +2363,149 @@ mod tests { ); } + /// A pass that left `gem`'s installed copy for `reason`. + fn failed_for(gem: &StaleGem, reason: &str) -> Attempt { + let (dir, _) = gem.installed.clone().unwrap(); + Attempt { + left: BTreeMap::from([(dir, Why::Failed(reason.to_string()))]), + ..Attempt::default() + } + } + + /// #2242: a native gem in the tree of a Ruby that is not on `PATH` + /// (`vendor/bundle/ruby/3.2.0` after an upgrade to Ruby 3.3). + /// `bundle install` installs into the running Ruby's gem home, so an + /// `rm -f` of the gemspec and archive leaves the gem dir where it is, + /// with no gemspec. The remedy removes the gem dir as well, and the + /// retry it names is one that can work. + #[tokio::test] + async fn a_copy_no_ruby_owns_is_removed_with_its_gem_dir() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.2.0"); + let gem = installed("json", &home, true); + let (dir, _) = gem.installed.clone().unwrap(); + let spec = home.join("specifications/json-1.0.0.gemspec"); + let cache = home.join("cache/json-1.0.0.gem"); + std::fs::create_dir_all(home.join("cache")).unwrap(); + std::fs::write(&cache, "").unwrap(); + let reason = "its native extension could not be rebuilt: no Ruby owning this install \ + was found (/opt/ruby-3.3/bin/ruby builds into /p/ruby/3.2.0/extensions/\ + x86_64-linux/3.3.0/json-1.0.0, but the installed extension is /p/ruby/\ + 3.2.0/extensions/x86_64-linux/3.2.0/json-1.0.0 (another Ruby's))"; + let policy = policy(tmp.path(), true, false, false); + let command = format!( + "`rm -rf {} {} {} && bundle install`", + dir.display(), + spec.display(), + cache.display() + ); + + let pass = failed_for(&gem, reason); + let out = report( + Direction::Patched, + std::slice::from_ref(&gem), + &pass, + &policy, + ); + let summary = out.summary.unwrap(); + assert_eq!(summary.bullets.len(), 1); + let bullet = &summary.bullets[0]; + assert!(bullet.contains(&command), "{bullet}"); + assert!( + bullet.contains( + "Re-run `socket-patch scan` with the Ruby that installed the gem first on \ + `PATH` to retry, or run " + ), + "{bullet}" + ); + assert!( + !bullet.contains("Re-run `socket-patch scan` to retry"), + "{bullet}" + ); + let (code, detail) = &out.warnings[0]; + assert_eq!(*code, "redirect_gem_stale_install"); + let removed = format!( + "remove {}, {}, {} and run `bundle install`", + dir.display(), + spec.display(), + cache.display() + ); + assert!(detail.contains(&removed), "{detail}"); + assert!( + !detail.contains("Re-run `socket-patch scan` to retry"), + "{detail}" + ); + + // An unwind names no re-run, and the same paths. + let out = report( + Direction::Upstream, + std::slice::from_ref(&gem), + &pass, + &policy, + ); + let bullet = &out.summary.unwrap().bullets[0]; + assert!(bullet.contains(&format!("Run {command}")), "{bullet}"); + assert!(!bullet.contains("Re-run"), "{bullet}"); + } + + /// #2242: a gem dir whose gemspec is already gone (what the `rm -f` + /// remedy left in another Ruby's tree). A re-run fails the same way + /// and the files of the old remedy are not there to remove: the + /// remedy is the gem dir, and what is still beside it. + #[tokio::test] + async fn a_gem_dir_without_its_gemspec_is_the_thing_to_remove() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("vendor/bundle/ruby/3.2.0"); + let gem = installed("racc", &home, true); + let (dir, _) = gem.installed.clone().unwrap(); + std::fs::remove_file(home.join("specifications/racc-1.0.0.gemspec")).unwrap(); + let reason = "its installed gemspec is unreadable: No such file or directory (os error 2)"; + let policy = policy(tmp.path(), true, false, false); + let pass = failed_for(&gem, reason); + let out = report( + Direction::Patched, + std::slice::from_ref(&gem), + &pass, + &policy, + ); + let summary = out.summary.unwrap(); + let bullet = &summary.bullets[0]; + assert!( + bullet.contains(&format!( + "racc 1.0.0. Run `rm -rf {} && bundle install`", + dir.display() + )), + "{bullet}" + ); + assert!(!bullet.contains("Re-run"), "{bullet}"); + assert!(!bullet.contains(".gemspec"), "{bullet}"); + let (_, detail) = &out.warnings[0]; + assert!( + detail.contains(&format!( + "Remove {} and run `bundle install`", + dir.display() + )), + "{detail}" + ); + assert!(!detail.contains("Re-run"), "{detail}"); + + // A default gem's entry is under `specifications/default/`: the + // copy is installed, and the remedy is the one it was. + std::fs::create_dir_all(home.join("specifications/default")).unwrap(); + std::fs::write(home.join("specifications/default/racc-1.0.0.gemspec"), "").unwrap(); + let out = report( + Direction::Patched, + std::slice::from_ref(&gem), + &pass, + &policy, + ); + let bullet = &out.summary.unwrap().bullets[0]; + assert!( + bullet.contains("Re-run `socket-patch scan` to retry, or run `rm -f "), + "{bullet}" + ); + } + #[test] fn refreshed_gems_are_notes_and_one_progress_line_each_kind() { let pass = Attempt { diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 128d185b08..c7e7065370 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -2320,6 +2320,73 @@ async fn refresh_replaces_a_stale_project_install_and_its_archives() { ); } +/// #2242: what the `rm -f && bundle install` remedy +/// left in the tree of an earlier Ruby (`vendor/bundle/ruby/3.2.0` beside +/// the `ruby/3.3.0` the project now installs into): the unpatched gem dir, +/// with no gemspec and no archive. `bundle install` never replaces it, and +/// a re-scan cannot refresh it. The scan's remedy is then the directory +/// itself, and following it leaves nothing to warn about. +#[tokio::test(flavor = "multi_thread")] +async fn a_gem_dir_left_without_its_gemspec_is_named_as_the_thing_to_remove() { + let server = MockServer::start().await; + let patched = real_gem(PATCHED_LIB); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + // The running Ruby's tree holds the patched gem already. + let home = project_home(&proj); + let current = install_real_gem(&home, PATCHED_LIB); + // The earlier Ruby's tree, after the old remedy. + let old_home = home.with_file_name("3.2.0"); + let leftover = install_real_gem(&old_home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + std::fs::remove_file( + old_home + .join("specifications") + .join(format!("{leaf}.gemspec")), + ) + .unwrap(); + std::fs::remove_file(old_home.join("cache").join(format!("{leaf}.gem"))).unwrap(); + + let uri = server.uri(); + let args = scan_args(&proj, &uri, &[]); + let (code, _, stderr) = common::run_with_env(&proj, &args, &[]); + assert_eq!(code, 0, "{stderr}"); + let command = format!("Run `rm -rf {} && bundle install`", shell_word(&leftover)); + assert!(stderr.contains(&command), "{stderr}"); + assert!( + !stderr.contains("Re-run `socket-patch scan`") && !stderr.contains("rm -f "), + "no retry that fails the same way, no file that is not there:\n{stderr}" + ); + assert_eq!(installed_lib(&leftover), UPSTREAM_LIB, "left as it was"); + + let args = scan_args(&proj, &uri, &["--json"]); + let (code, stdout, stderr) = common::run_with_env(&proj, &args, &[]); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + let stale = stale_warnings(&env); + assert_eq!(stale.len(), 1, "{env}"); + assert!( + stale[0].contains(&format!( + "Remove {} and run `bundle install`", + leftover.display() + )), + "{stale:?}" + ); + + // The remedy's `rm -rf` (its `bundle install` has nothing to install: + // the running Ruby's tree is complete). + std::fs::remove_dir_all(&leftover).unwrap(); + let args = scan_args(&proj, &uri, &[]); + let (code, _, stderr) = common::run_with_env(&proj, &args, &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(!stderr.contains("still unpatched"), "{stderr}"); + assert_eq!(installed_lib(¤t), PATCHED_LIB); +} + /// #2219: the machine that did not run the scan. A teammate pulls the /// hosted `Gemfile` / `Gemfile.lock` onto a checkout whose gems are already /// installed (or CI restores a `vendor/bundle` cache): Bundler keeps the diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 1feac92b5d..f5dab7bf03 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -2400,6 +2400,13 @@ fn home_minor(copy: &GemCopy) -> Option { } } +/// How a candidate Ruby that answered, and builds this gem's extension +/// somewhere else than where the installed one is, ends its line in +/// [`find_ruby`]'s error. The copy is then in a gem home that Ruby does +/// not install into, so a `bundle install` run with it does not replace +/// the copy either: a remedy checks for this. +pub const OWNED_BY_ANOTHER_RUBY: &str = "(another Ruby's)"; + /// Find the Ruby that owns `copy`'s install. Each candidate is asked where /// it builds extensions for the gem home, and what it is /// ([`RubyRun::ExtensionsDir`]), which loads nothing of the gem. `Err` @@ -2454,7 +2461,7 @@ async fn find_ruby( let disowned = match platform { None if installed.iter().any(|d| same_path(d, &extension_dir)) => None, None => Some(format!( - "{} builds into {}, but the installed extension is {} (another Ruby's)", + "{} builds into {}, but the installed extension is {} {OWNED_BY_ANOTHER_RUBY}", ruby.display(), extension_dir.display(), installed @@ -7072,6 +7079,7 @@ mod tests { preflight.candidates = vec![fake_ruby(&other, "q")]; let why = find_fresh_ruby(©, &env, &preflight).await.unwrap_err(); assert!(why.contains("another Ruby's"), "{why}"); + assert!(why.contains(OWNED_BY_ANOTHER_RUBY), "{why}"); } /// A gem with no extension dir, or whose require path leaves the gem diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 4013c7e08d..c9bb31c4d1 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -4143,6 +4143,16 @@ to the patched `gems/nokogiri-1.16.0/`. RubyGems and Bundler load a gem by its `specifications/` entry, so nothing loads that directory, and `socket-patch vex` and `apply --check` don't count it as an installed copy. `bundle clean --force` deletes it. +`bundle install` installs into the gem home of the Ruby that runs it. After a Ruby upgrade +`vendor/bundle` can still hold the tree of the earlier Ruby (`vendor/bundle/ruby/3.2.0` next to +`ruby/3.3.0`), and a gem with a native extension in that tree can only be rebuilt by the Ruby +that installed it. When the scan finds no such Ruby, its warning names the gem directory to +remove as well (`rm -rf && bundle install`), so no unpatched +copy is left behind whichever Ruby runs `bundle install`; to keep the tree, re-run the scan with +that Ruby first on `PATH`. A gem directory that already lost its gemspec, and that the scan +tried and failed to replace, is reported the same way: the warning names the directory to +remove, and no re-run, which could not replace it. + Gems in a gem home **outside** the project (the system gems, `~/.gem`, an rbenv or asdf home) are not touched: another project on the machine may use the same copy. The run prints one warning naming them. Either install the project's gems into the project, where Bundler fetches the patched