diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 653ae7abc..a93140f54 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -3519,11 +3519,10 @@ impl OtherProjectCopy { } } -/// The gems of `unresolved` (the manifest keys with no copy to patch and -/// none in the lock inventory) that are another project's: a Bundler lock -/// was read, it does not name them as platform builds either, and -/// `rollback`'s resolver finds -/// a copy of them where this run's (`all_packages`, the copies `apply` +/// The gems of `unresolved` (the manifest keys with no copy to patch that +/// the project's locks do not resolve, [`lockfile_resolved`]) that are +/// another project's: a Bundler lock was read, and `rollback`'s resolver +/// finds a copy of them where this run's (`all_packages`, the copies `apply` /// writes) found none, so each sits in a `gem env` home Bundler does not /// load the project's gems from. The detail holds for a copy an earlier /// release patched and for one nothing ever touched. @@ -3535,7 +3534,7 @@ async fn other_project_gem_copies( if common.is_global() { return Vec::new(); } - let mut candidates: Vec = unresolved + let candidates: Vec = unresolved .iter() .filter(|purl| { Ecosystem::from_purl(purl) == Some(Ecosystem::Gem) @@ -3554,19 +3553,6 @@ async fn other_project_gem_copies( if !ctx.gem_lock_read().await { return Vec::new(); } - // The lock names a gem it holds only as precompiled platform builds, - // though the lock inventory behind `unresolved` leaves it out: that - // gem is the project's, and stays not installed. - let platform_only: HashSet = ctx - .gem_platform_only_purls() - .await - .iter() - .map(|purl| PurlKey::new(purl)) - .collect(); - candidates.retain(|purl| !platform_only.contains(&PurlKey::new(purl))); - if candidates.is_empty() { - return Vec::new(); - } let mut found = crate::ecosystem_dispatch::find_all_packages_for_rollback( &partition_purls(&candidates, None), &common.crawler_options(), @@ -5442,8 +5428,7 @@ async fn lockfile_resolved(common: &GlobalArgs, unmatched: &[String]) -> HashSet return HashSet::new(); } let ctx = crate::commands::context::ProjectContext::new(common); - let entries = &ctx.locks().await.entries; - let lock_purls: HashSet = entries.iter().map(|e| PurlKey::new(&e.purl)).collect(); + let lock_purls = ctx.lock_resolved().await; unmatched .iter() .filter(|p| lock_resolution_is_calm(p) && lock_purls.contains(&PurlKey::new(p))) diff --git a/crates/socket-patch-cli/src/commands/context.rs b/crates/socket-patch-cli/src/commands/context.rs index c0ad7a59c..2abfe461f 100644 --- a/crates/socket-patch-cli/src/commands/context.rs +++ b/crates/socket-patch-cli/src/commands/context.rs @@ -14,9 +14,11 @@ //! under that lock instead of trusting a pre-lock snapshot, and an embedded //! `--vex` after the writes loads its own inputs. +use std::collections::HashSet; use std::path::PathBuf; use socket_patch_core::ledgers::{Ledgers, LoadedLedgers}; +use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::vendor::lock_inventory::{ DiskSnapshot, LockfileEntry, ProjectView, ReadSet, UnsupportedNpmLayout, }; @@ -99,6 +101,23 @@ impl<'a> ProjectContext<'a> { .await } + /// The releases the project's locks resolve: every entry of + /// [`Self::locks`], and the gems of + /// [`Self::gem_platform_only_purls`], which that inventory leaves out + /// though the lock names them. What is in here and not installed was + /// left out by the package manager on this host, not lost. + pub(crate) async fn lock_resolved(&self) -> HashSet { + let locks = self.locks().await; + let platform_gems = self.gem_platform_only_purls().await; + locks + .entries + .iter() + .map(|entry| entry.purl.as_str()) + .chain(platform_gems.iter().map(String::as_str)) + .map(PurlKey::new) + .collect() + } + /// Whether bundler loads a lock in the project that socket-patch read /// (`gem_lock_read_in`), through the same snapshot as [`Self::locks`]. pub(crate) async fn gem_lock_read(&self) -> bool { diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index ec21a6c1c..95de49c82 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -390,12 +390,8 @@ async fn keep_project_entries(common: &GlobalArgs, prunable: &mut Vec) { crate::ecosystem_dispatch::crawl_ecosystems_for_name(&project.crawler_options(), None) .await; let ctx = crate::commands::context::ProjectContext::new(&project); - let locked = &ctx.locks().await.entries; - let accounted: HashSet = installed - .iter() - .map(|pkg| PurlKey::new(&pkg.purl)) - .chain(locked.iter().map(|entry| PurlKey::new(&entry.purl))) - .collect(); + let mut accounted = ctx.lock_resolved().await; + accounted.extend(installed.iter().map(|pkg| PurlKey::new(&pkg.purl))); prunable.retain(|purl| !accounted.contains(&PurlKey::new(purl))); } diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 6a8f0792d..fdc161a54 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -3002,7 +3002,7 @@ fn omission_lines(failed: &[FailedPatch], verbose: bool) -> Vec { "Warning: omitting {} packages from VEX: {} ({reason}): {}{}", purls.len(), omission_phrase(reason), - crate::ui::folded(&crate::ui::package_names(&purls), NAMES_SHOWN), + crate::ui::folded(&crate::ui::build_names(&purls), NAMES_SHOWN), if purls.len() > NAMES_SHOWN { " (--verbose lists them all)" } else { @@ -3397,6 +3397,21 @@ mod tests { (package_not_found)", ] ); + // The platform builds of one gem are told apart (#2452). + let builds = ["arm64-darwin", "ruby", "x86_64-linux-musl", "x86_64-darwin"].map(|p| { + failed( + &format!("pkg:gem/nokogiri@1.19.7?platform={p}"), + "package_not_found", + ) + }); + assert_eq!( + omission_lines(&builds, false), + [ + "Warning: omitting 4 packages from VEX: the package is not installed \ + (package_not_found): nokogiri@1.19.7 (arm64-darwin), nokogiri@1.19.7 (ruby), \ + nokogiri@1.19.7 (x86_64-linux-musl) and 1 more (--verbose lists them all)" + ] + ); let verbose = omission_lines(&patches, true); assert_eq!(verbose.len(), 85); assert_eq!( diff --git a/crates/socket-patch-cli/src/ui/mod.rs b/crates/socket-patch-cli/src/ui/mod.rs index c04662c60..d7513eb31 100644 --- a/crates/socket-patch-cli/src/ui/mod.rs +++ b/crates/socket-patch-cli/src/ui/mod.rs @@ -32,9 +32,9 @@ pub(crate) use prompt::confirm; pub use prompt::{select_from, select_one, SelectError}; pub(crate) use status::StatusLine; pub(crate) use text::{ - agent_next_steps, folded, manifest_error_message, next_steps, next_steps_installed, - package_names, plural, printable, sentence_case, shell_word, short_uuid, sweep_failure, - truncate, worst_and_ids, + agent_next_steps, build_names, folded, manifest_error_message, next_steps, + next_steps_installed, package_names, plural, printable, sentence_case, shell_word, short_uuid, + sweep_failure, truncate, worst_and_ids, }; /// [`text::no_patches_message`] for this run: the manifest path is named diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index eb67e05ec..c8be2e887 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -71,6 +71,33 @@ pub fn package_names(purls: &[&str]) -> Vec { .collect() } +/// [`package_names`] for a listing with one entry per patch record, where +/// the platform builds of one gem release are entries of their own: a name +/// that would repeat carries its build, `nokogiri@1.19.7 (arm64-darwin)`. +pub fn build_names(purls: &[&str]) -> Vec { + use socket_patch_core::crawlers::types::Ecosystem; + use socket_patch_core::utils::purl::purl_qualifier; + let names = package_names(purls); + let mut listed: std::collections::HashMap<&str, usize> = std::collections::HashMap::new(); + for name in &names { + *listed.entry(name).or_default() += 1; + } + let repeats = |name: &str| listed.get(name).is_some_and(|count| *count > 1); + let is_gem = |purl: &str| Ecosystem::from_purl(purl) == Some(Ecosystem::Gem); + names + .iter() + .zip(purls) + .map(|(name, purl)| { + let build = purl_qualifier(purl, "platform") + .filter(|platform| is_gem(purl) && !platform.is_empty()); + match build { + Some(platform) if repeats(name) => format!("{name} ({platform})"), + _ => name.clone(), + } + }) + .collect() +} + /// `items` for a sentence, the first `shown` of them named: `a, b, c and /// 5 more`. pub fn folded(items: &[String], shown: usize) -> String { @@ -362,6 +389,38 @@ mod tests { assert!(package_names(&[]).is_empty()); } + /// The builds of one gem release are told apart; a name that is + /// listed once stays as it is. + #[test] + fn builds_of_one_release_are_named_with_their_platform() { + assert_eq!( + build_names(&[ + "pkg:gem/nokogiri@1.19.7?platform=arm64-darwin", + "pkg:gem/nokogiri@1.19.7?platform=ruby", + "pkg:gem/rack@3.2.9?platform=ruby", + ]), + [ + "nokogiri@1.19.7 (arm64-darwin)", + "nokogiri@1.19.7 (ruby)", + "rack@3.2.9" + ] + ); + // Named by purl beside another ecosystem, and still told apart. + assert_eq!( + build_names(&[ + "pkg:gem/ffi@1.17.0?platform=x86_64-linux-gnu", + "pkg:gem/ffi@1.17.0", + "pkg:npm/b@2.0.0", + ]), + [ + "pkg:gem/ffi@1.17.0 (x86_64-linux-gnu)", + "pkg:gem/ffi@1.17.0", + "pkg:npm/b@2.0.0" + ] + ); + assert_eq!(build_names(&["pkg:npm/a@1.0.0"]), ["a@1.0.0"]); + } + /// One rule for the severity and the ids of a set of advisories, /// wherever a patch is named in a line: the `list` row, `show`'s /// title and the patch menu. diff --git a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs index bf5739974..603e46be1 100644 --- a/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs +++ b/crates/socket-patch-cli/tests/apply/in_process_gem_fallback_home.rs @@ -505,8 +505,10 @@ fn gem_with_no_copy_anywhere_and_no_lock_entry_still_fails() { /// A gem the lock holds only as a precompiled platform build is the /// project's, though the lock inventory leaves it out. With the path /// still empty and a copy of the version in the `gem env` home, it is not -/// another project's gem: it stays the not-installed failure it was, and -/// nothing tells the user to roll back a patch the project needs. +/// another project's gem, and nothing tells the user to roll back a patch +/// the project needs. The lock resolves the gem, so it is the calm +/// lockfile-only skip of a gem `bundle install` has not installed yet +/// (#2452), as under a lock with a `ruby` entry. #[test] fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { let fx = build_fixture( @@ -528,11 +530,16 @@ fn gem_the_lock_holds_as_a_platform_build_is_not_another_projects() { find_other_project_skip(&env).is_none(), "the gem is the project's.\nenvelope: {env}" ); + let skip = find_event(&env, "skipped", NOT_INSTALLED) + .unwrap_or_else(|| panic!("the gem must be reported as {NOT_INSTALLED}.\nenvelope: {env}")); assert!( - find_event(&env, "skipped", NOT_INSTALLED).is_some(), + skip["reason"] + .as_str() + .unwrap_or_default() + .contains("lockfile-only"), "envelope: {env}" ); - assert_eq!(code, 1, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); assert!(!stdout.contains("rollback"), "envelope: {env}"); assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); } @@ -636,6 +643,146 @@ fn explicit_path_with_nothing_installed_is_a_calm_skip_under_a_lock() { assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); } +/// A `Gemfile.lock` that names the fixture's gem only by its precompiled +/// platform builds, with no `ruby` entry: what Bundler 2.5 and 2.6 write, +/// and Bundler 4 after `bundle lock --remove-platform ruby`. +fn write_platform_only_lock(fx: &Fixture) { + std::fs::write( + fx.project.path().join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n rack (3.1.0-arm64-darwin)\n \ + rack (3.1.0-x86_64-linux)\n\n\ + PLATFORMS\n arm64-darwin\n x86_64-linux\n\nDEPENDENCIES\n rack\n\n\ + BUNDLED WITH\n 2.6.9\n", + ) + .unwrap(); +} + +/// Replace the fixture's manifest with one record per purl of `purls`. +/// The first carries the fixture's patch; each later one patches its own +/// build's bytes, as the platform builds of one release differ. +fn write_records(fx: &Fixture, purls: &[&str]) { + let root = fx.project.path(); + let records: serde_json::Map = purls + .iter() + .enumerate() + .map(|(i, purl)| { + let mut before = ORIGINAL.to_vec(); + if i > 0 { + before.extend_from_slice(format!("# build {i}\n").as_bytes()); + } + let after = [before.as_slice(), MARKER].concat(); + stage_blob(root, &git_sha256(&after), &after); + let record = patch_record( + &format!("66616c6c-6261-4b63-8368-6f6d6500000{i}"), + one_file("lib/rack.rb", &before, &after), + ); + (purl.to_string(), record) + }) + .collect(); + write_manifest(root, serde_json::Value::Object(records)); +} + +const DARWIN_PURL: &str = "pkg:gem/rack@3.1.0?platform=arm64-darwin"; +const LINUX_PURL: &str = "pkg:gem/rack@3.1.0?platform=x86_64-linux"; +const MUSL_PURL: &str = "pkg:gem/rack@3.1.0?platform=x86_64-linux-musl"; + +/// #2452: the fresh clone again, with a lock that names the gem only by +/// its platform builds and a portable manifest (`scan --all-releases`) +/// that records a patch per build. The lock resolves the gem, so the +/// records are the same calm lockfile-only skip as under a lock with a +/// `ruby` entry, never the all-miss failure. +#[test] +fn nothing_installed_is_a_calm_skip_under_a_platform_only_lock() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_platform_only_lock(&fx); + write_records(&fx, &[DARWIN_PURL, LINUX_PURL, MUSL_PURL]); + + let (code, stdout, stderr) = run_apply(&fx, &["--json"]); + let env = parse_env(&stdout); + assert_eq!(code, 0, "envelope: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "envelope: {env}"); + let events = env["events"].as_array().expect("events"); + for purl in [DARWIN_PURL, LINUX_PURL, MUSL_PURL] { + let skip = events + .iter() + .find(|e| e["purl"] == purl) + .unwrap_or_else(|| panic!("no event for {purl}.\nenvelope: {env}")); + assert_eq!(skip["action"], "skipped", "envelope: {env}"); + assert_eq!(skip["errorCode"], NOT_INSTALLED, "envelope: {env}"); + assert!( + skip["reason"] + .as_str() + .unwrap_or_default() + .contains("lockfile-only"), + "envelope: {env}" + ); + } + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert!( + stderr.contains( + "Note: 3 manifest patches target packages not installed on this host \ + (resolved by the project lockfile; skipped):" + ), + "stderr={stderr}" + ); + assert!( + !stderr.contains("had no matching installed package") && !stderr.contains("Error:"), + "stderr={stderr}" + ); + assert_eq!(std::fs::read(&fx.home_file).unwrap(), ORIGINAL); +} + +/// #2452: one build is installed and patched, and the records of the +/// other builds get the note, not the "no matching installed package" +/// warning: the lock resolves the gem whether or not it has a `ruby` +/// entry. +#[test] +fn other_builds_of_an_installed_gem_are_a_note_under_a_platform_only_lock() { + let fx = build_fixture( + Store::ExplicitEmpty, + Home::Installed, + ORIGINAL, + QUALIFIED_PURL, + ); + write_platform_only_lock(&fx); + write_records(&fx, &[LINUX_PURL, DARWIN_PURL, MUSL_PURL]); + // The build this host installed, in the project's bundle path. + let store = fx.bundle_path.as_ref().unwrap(); + let installed = store.join("gems/rack-3.1.0-x86_64-linux/lib/rack.rb"); + std::fs::create_dir_all(installed.parent().unwrap()).unwrap(); + std::fs::write(&installed, ORIGINAL).unwrap(); + std::fs::create_dir_all(store.join("specifications")).unwrap(); + + let (code, stdout, stderr) = run_apply(&fx, &[]); + assert_eq!(code, 0, "stdout={stdout}\nstderr={stderr}"); + assert_eq!( + std::fs::read(&installed).unwrap(), + patched_bytes(), + "stdout={stdout}\nstderr={stderr}" + ); + assert!( + stderr.contains( + "Note: 2 manifest patches target packages not installed on this host \ + (resolved by the project lockfile; skipped):" + ), + "stdout={stdout}\nstderr={stderr}" + ); + for purl in [DARWIN_PURL, MUSL_PURL] { + assert!(stderr.contains(&format!(" - {purl}")), "stderr={stderr}"); + } + assert!( + !stderr.contains("had no matching installed package"), + "stderr={stderr}" + ); +} + /// A default gem only ever lives in the system home, and Bundler loads it /// from there under any path: it is still patched. #[test] diff --git a/crates/socket-patch-cli/tests/in_process_scan.rs b/crates/socket-patch-cli/tests/in_process_scan.rs index 987cc5f3d..16deff555 100644 --- a/crates/socket-patch-cli/tests/in_process_scan.rs +++ b/crates/socket-patch-cli/tests/in_process_scan.rs @@ -876,6 +876,64 @@ async fn scan_global_prune_keeps_the_projects_entries() { assert_eq!(blob_count(&project), 4, "the kept records keep their blobs"); } +/// The project's Bundler lock names a gem only by its precompiled +/// platform builds (no `ruby` entry). The lock still resolves that gem, so +/// a global prune keeps its records like any other lockfile-listed entry +/// of the project (#2452). +#[tokio::test] +#[serial] +async fn scan_global_prune_keeps_a_gem_the_project_locks_only_as_platform_builds() { + let server = MockServer::start().await; + mock_batch_empty(&server).await; + + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("project"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write( + project.join("Gemfile"), + "source 'https://rubygems.org'\ngem 'socket-fixture-gem', '1.19.7'\n", + ) + .unwrap(); + std::fs::write( + project.join("Gemfile.lock"), + "GEM\n remote: https://rubygems.org/\n specs:\n \ + socket-fixture-gem (1.19.7-arm64-darwin)\n socket-fixture-gem (1.19.7-x86_64-linux-gnu)\n\n\ + PLATFORMS\n arm64-darwin\n x86_64-linux\n\nDEPENDENCIES\n socket-fixture-gem (= 1.19.7)\n\n\ + BUNDLED WITH\n 2.6.9\n", + ) + .unwrap(); + write_record_with_blobs( + &project, + &[ + "pkg:gem/socket-fixture-gem@1.19.7?platform=arm64-darwin", + "pkg:gem/socket-fixture-gem@1.19.7?platform=x86_64-linux-gnu", + "pkg:gem/socket-fixture-gone@1.0.0", + ], + ); + let global_root = tmp.path().join("global/lib"); + write_npm_package(&global_root, "global-pkg", "2.0.0"); + let global = global_root.join("node_modules"); + + for dry_run in [true, false] { + let mut args = default_args(&project); + args.common.api_url = Some(server.uri()); + args.common.global_prefix = Some(global.clone()); + args.common.dry_run = dry_run; + args.prune = true; + assert_eq!(run_scrubbed(args).await, 0); + } + + assert_eq!( + manifest_purls(&project), + [ + "pkg:gem/socket-fixture-gem@1.19.7?platform=arm64-darwin", + "pkg:gem/socket-fixture-gem@1.19.7?platform=x86_64-linux-gnu", + ], + "a global prune keeps the builds the project's lock names" + ); + assert_eq!(blob_count(&project), 4, "the kept records keep their blobs"); +} + /// A prune whose manifest rewrite fails has pruned nothing: the manifest on /// disk still names every entry, so their blobs must survive the sweep. #[cfg(unix)]