diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc..b30418b7d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1867,7 +1867,13 @@ worse, lets a warm cache silently serve unpatched bytes): * `vendor --revert` restores the originals (fragments that no longer match — a user re-resolved — are left alone with a `vendor_lock_entry_drifted` warning; the drift-kept artifact and entry stay, every backend alike — gem included as of v5.0, where a MISSING `Gemfile`/`Gemfile.lock` instead - warns `vendor_lockfile_missing` and still removes the artifact; composer / maven / nuget, whose + warns `vendor_lockfile_missing` and still removes the artifact, and where a fragment that cannot + be restored once neither `Gemfile` nor `Gemfile.lock` names the `.socket/vendor/gem/` dir, + or a vendored copy of the gem under another patch uuid, in any spelling — the gem was dropped + with `bundle remove`, or moved to another release — is not drift: it warns + `vendor_lock_entry_removed`, both files stay as the user left them, and the artifact and entry + are removed, so `vendor --revert` / `rollback` / `remove` / `scan --prune` clean up after it (a + file of the two that cannot be read fails the revert, which keeps both); composer / maven / nuget, whose whole-file wiring cannot tell a converged fragment from a drifted one, keep the artifact exactly while the live `composer.lock` / `pom.xml` / `nuget.config` still names its `.socket/vendor//` dir — a file that no longer references it is warned about and the diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 0c654c0f7..ee128ceaa 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2228,6 +2228,134 @@ fn gem_vendor_drops_positional_constraints() { } } +/// #2325: after the project drops a vendored gem (`bundle remove`) or moves +/// it to another release, nothing bundler reads names the vendored copy any +/// more. `vendor --check` reports the dead entry, and each undo command +/// then cleans it up: the copy and its ledger record go, the user's +/// Gemfile and Gemfile.lock stay byte for byte, a frozen install still +/// passes, and `vendor --check` is green again. +#[test] +#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { + // How the project drops the gem, and the command that cleans up. + let cases: [(&str, &[&str]); 4] = [ + ("remove", &["vendor", "--revert"]), + ("remove", &["rollback"]), + ("remove", &["remove", "--yes"]), + ("upgrade", &["vendor", "--revert"]), + ]; + for (how, undo) in cases { + let what = format!("{how}, then `{}`", undo.join(" ")); + let Some((_tmp, proj, _bundler, purl)) = staged_rack_project("dropped gem") else { + return; + }; + let cwd = proj.to_str().unwrap(); + let (code, stdout, stderr) = + run_socket(&proj, &["vendor", "--json", "--offline", "--cwd", cwd]); + assert_eq!(code, 0, "{what}: vendor failed.\n{stdout}\n{stderr}"); + let uuid_dir = proj.join(".socket/vendor/gem").join(UUID); + assert!(uuid_dir.is_dir(), "{what}: vendored copy written"); + + // The user's edit, with real bundler. + let edit = match how { + // Bundler <= 2.1 edits only the Gemfile on `remove`; the + // install that follows re-locks, as it does for such a user. + "remove" => { + let remove = bundle(&proj, &["remove", DEP], false); + assert!( + remove.status.success(), + "{what}: `bundle remove` (test premise):\n{}", + String::from_utf8_lossy(&remove.stderr) + ); + bundle(&proj, &["install"], false) + } + _ => { + let version = purl.rsplit('@').next().unwrap(); + let other = if version == "3.1.8" { "3.1.9" } else { "3.1.8" }; + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\n\ngem \"rack\", \"{other}\"\n"), + ) + .unwrap(); + bundle(&proj, &["install"], false) + } + }; + assert!( + edit.status.success(), + "{what}: the user's bundler command (test premise):\n{}", + String::from_utf8_lossy(&edit.stderr) + ); + let gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); + let lock = std::fs::read(proj.join("Gemfile.lock")).unwrap(); + for file in [&gemfile, &lock] { + assert!( + !String::from_utf8_lossy(file).contains(".socket/vendor"), + "{what}: bundler left no reference to the vendored copy (test premise)" + ); + } + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + assert!( + code == 1 && format!("{stdout}{stderr}").contains("wiring missing"), + "{what}: vendor --check reports the dead entry.\n{stdout}\n{stderr}" + ); + + // The clean-up. + let mut args: Vec<&str> = undo.to_vec(); + if undo[0] != "vendor" { + args.push(&purl); + } + args.extend(["--json", "--cwd", cwd]); + let (code, stdout, stderr) = run_socket(&proj, &args); + assert_eq!( + code, 0, + "{what}: failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{what}: {env}"); + let all = format!("{stdout}{stderr}"); + assert!( + !all.contains("drift"), + "{what}: a dropped gem is not reported as drift:\n{all}" + ); + + assert!(!uuid_dir.exists(), "{what}: the dead copy is removed"); + let state = proj.join(".socket/vendor/state.json"); + assert!( + !state.exists() || !std::fs::read_to_string(&state).unwrap().contains(UUID), + "{what}: the ledger record is dropped" + ); + assert_eq!( + std::fs::read(proj.join("Gemfile")).unwrap(), + gemfile, + "{what}: the user's Gemfile is left alone" + ); + assert_eq!( + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + lock, + "{what}: the user's Gemfile.lock is left alone" + ); + let install = bundle(&proj, &["install"], true); + assert!( + install.status.success(), + "{what}: a frozen install passes after the clean-up:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + // `remove` drops the manifest's patch too, so the audit has nothing + // left to hold the project to. The other two keep that patch, which + // the audit then reports as not vendored: no longer a dead entry. + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + let audit = format!("{stdout}{stderr}"); + assert!( + !audit.contains("wiring missing") && !audit.contains(UUID), + "{what}: vendor --check no longer reports the dead entry:\n{audit}" + ); + if undo[0] == "remove" { + assert_eq!(code, 0, "{what}: vendor --check is green again:\n{audit}"); + } + } +} + /// #1821: vendoring over a CRLF Gemfile keeps every line CRLF (the rewired /// `gem` line used to end in a bare LF), a real frozen install accepts the /// result, and revert restores the Gemfile byte for byte. diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 339dbf08f..1209e7156 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -114,6 +114,7 @@ use crate::patch::path_safety::is_safe_single_segment; use crate::patch::redirect::gem_line_tail_blocks_edit; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; use crate::utils::line_endings::{self, to_lf, LineEndings}; +use crate::utils::path_spelling::{canonical_path_text, PathNeedle}; use crate::utils::purl::{build_gem_purl, parse_gem_purl, purl_qualifier}; use super::common::{ @@ -2140,7 +2141,10 @@ async fn materialise_patched_copy( /// A fragment that no longer looks like what vendor wrote — a hand edit, a /// `bundle update`, a newer vendor run — gets a `vendor_lock_entry_drifted` /// warning, and then neither file is written: the Gemfile and the lock are -/// reverted together or not at all (#988). +/// reverted together or not at all (#988). When neither file names the copy +/// dir any more (`bundle remove`, a move to another release), such a +/// fragment warns `vendor_lock_entry_removed` instead: neither file is +/// written then either, and the copy is removed (#2325). pub async fn revert_gem(entry: &VendorEntry, project_root: &Path, dry_run: bool) -> RevertOutcome { revert_gem_opts(entry, project_root, RevertOpts::new(dry_run)).await } @@ -2219,7 +2223,26 @@ pub async fn revert_gem_opts( version: version.into_owned(), }; let mut files = RevertFiles::new(project_root); + // Whether either file still names the entry's copy dir, or a copy of + // this gem under another patch uuid (a re-vendor that was interrupted, + // a merge that kept an older ledger: this entry may hold the only + // pre-vendor originals of that wiring), in any spelling and any case. + // Read before any record is reverted, so that only the user's own edits + // count. A file that cannot be read may name one. + let needle = PathNeedle::keep(&uuid_dir_rel); + let mut referenced = false; + for name in [GEMFILE_LOCK, GEMFILE] { + referenced |= match files.text(name).await { + Ok(Some(file)) => { + needle.found_in(file.text()) + || names_a_vendored_copy_of(file.text(), &own.name, &own.version) + } + Ok(None) => false, + Err(_) => true, + }; + } let mut drifted = false; + let mut removed = false; for w in entry.wiring.iter().rev() { let restored = match w.kind.as_str() { LOCK_WIRING_KIND => revert_lock_record(&mut files, w, &own).await, @@ -2236,6 +2259,26 @@ pub async fn revert_gem_opts( let key = w.key_label(); match restored { Ok(RecordRevert::Done) => {} + // REMOVED, not drift (#2325): the user dropped the gem (`bundle + // remove`) or moved it to another release, and bundler took + // every fragment that routed through the copy out with it. With + // neither file naming the copy dir any more there is nothing to + // restore and nothing of the user's to protect, so the revert + // converges: the pair is theirs and stays as found, and the copy + // goes. + Ok(RecordRevert::Drifted) if !referenced => { + removed = true; + warnings.push(VendorWarning::new( + super::LOCK_ENTRY_REMOVED_CODE, + format!( + "{} no longer carries what vendor wrote for {key}, and neither \ + {GEMFILE} nor {GEMFILE_LOCK} names a vendored copy of the gem \ + any more (it was removed from the project, moved to another \ + release or pointed at another source); nothing to restore", + w.file + ), + )); + } Ok(RecordRevert::Drifted) => { drifted = true; warnings.push(VendorWarning::new( @@ -2270,10 +2313,11 @@ pub async fn revert_gem_opts( warnings, error: None, }; - // All-or-nothing: a drifted record leaves every file as found. A record - // of a kind this build cannot read still lets the known ones restore - // (forward compatibility); its warning keeps the artifact below. - if !drifted && !opts.dry_run { + // All-or-nothing: a drifted record, or one with nothing left to + // restore, leaves every file as found. A record of a kind this build + // cannot read still lets the known ones restore (forward + // compatibility); its warning keeps the artifact below. + if !drifted && !removed && !opts.dry_run { if let Err(e) = files.write_changed().await { return RevertOutcome { success: false, @@ -2294,6 +2338,27 @@ pub async fn revert_gem_opts( .await } +/// Whether a line of `text` (a Gemfile or a Gemfile.lock) names a +/// socket-patch copy of the gem `name` at `version` under any patch uuid: +/// a path below `.socket/vendor/gem/` with a `-` segment +/// (the copy dir, or a platform copy `--`), in any +/// spelling and any ASCII case. Errs towards `true`: the caller keeps an +/// artifact and a ledger entry while it holds. +fn names_a_vendored_copy_of(text: &str, name: &str, version: &str) -> bool { + let vendor_dir = PathNeedle::keep(".socket/vendor/gem"); + let segment = format!("/{name}-{version}").to_ascii_lowercase(); + text.split('\n') + .filter(|line| vendor_dir.found_in(line)) + .any(|line| { + let line = canonical_path_text(line).to_ascii_lowercase(); + line.match_indices(&segment).any(|(at, _)| { + // `rack-3.2.6` is not `rack-3.2.60` or `rack-3.2.6.1`. + !line[at + segment.len()..] + .starts_with(|c: char| c.is_ascii_alphanumeric() || c == '.') + }) + }) +} + // ── Gemfile editing ────────────────────────────────────────────────────────── /// The planned Gemfile edit. @@ -6339,6 +6404,254 @@ mod tests { } } + /// What `bundle remove rack` and a move to rack 3.2.7 leave of the + /// [`GEMFILE_DIRECT`] / [`LOCK_DIRECT`] pair: `(what, Gemfile, lock)`. + fn dropped_gem_pairs() -> [(&'static str, &'static str, &'static str); 2] { + [ + ( + "bundle remove", + "source \"https://rubygems.org\"\n\ngem \"puma\"\n", + "GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n nio4r (~> 2.0)\n\nPLATFORMS\n arm64-darwin-23\n ruby\n\nDEPENDENCIES\n puma\n\nBUNDLED WITH\n 2.5.22\n", + ), + ( + "upgrade", + "source \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"rack\", \"3.2.7\"\n", + "GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n nio4r (~> 2.0)\n rack (3.2.7)\n\nPLATFORMS\n arm64-darwin-23\n ruby\n\nDEPENDENCIES\n puma\n rack (= 3.2.7)\n\nBUNDLED WITH\n 2.5.22\n", + ), + ] + } + + /// Vendor rack into a fresh [`GEMFILE_DIRECT`] project, then leave the + /// pair as the user's `gemfile` and `lock`. + async fn vendored_then_edited( + gemfile: &str, + lock: &str, + ) -> (tempfile::TempDir, PathBuf, VendorEntry) { + let (tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let (result, entry, _w) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + tokio::fs::write(root.join(GEMFILE), gemfile).await.unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), lock) + .await + .unwrap(); + (tmp, root, entry.unwrap()) + } + + /// The pair as it stands on disk. + async fn read_pair(root: &Path) -> (String, String) { + ( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) + .await + .unwrap(), + ) + } + + /// #2325: the user dropped the vendored gem (`bundle remove`) or moved + /// it to another release, so neither file names the copy any more. That + /// is not drift: there is nothing to restore, the pair is the user's + /// and stays byte-identical, and the copy goes so the caller can drop + /// the ledger record. + #[tokio::test] + async fn revert_of_a_gem_the_project_dropped_removes_the_copy() { + for (what, gemfile, lock) in dropped_gem_pairs() { + let (_tmp, root, entry) = vendored_then_edited(gemfile, lock).await; + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{what}: {:?}", outcome.error); + assert!(!outcome.drift_skipped(), "{what}: {:?}", outcome.warnings); + assert!( + outcome.lock_entry_removed(), + "{what}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{what}"); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()), + "{what}: the user's pair is left alone" + ); + assert!( + !root.join(format!(".socket/vendor/gem/{UUID}")).exists(), + "{what}: the copy nothing references is removed" + ); + } + } + + /// #2325: a dry run and a `--preserve-state` revert of a dropped gem + /// report it the same way, and neither deletes the copy. + #[tokio::test] + async fn revert_of_a_dropped_gem_keeps_the_copy_on_a_dry_run_and_under_keep_artifact() { + for (what, gemfile, lock) in dropped_gem_pairs() { + for (mode, opts) in [ + ("dry run", RevertOpts::new(true)), + ( + "keep artifact", + RevertOpts { + keep_artifact: true, + ..RevertOpts::new(false) + }, + ), + ] { + let (_tmp, root, entry) = vendored_then_edited(gemfile, lock).await; + let outcome = revert_gem_opts(&entry, &root, opts).await; + assert!(outcome.success, "{what}, {mode}: {:?}", outcome.error); + assert!( + !outcome.drift_skipped() && outcome.lock_entry_removed(), + "{what}, {mode}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{what}, {mode}"); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()), + "{what}, {mode}" + ); + assert!(root.join(copy_rel()).exists(), "{what}, {mode}"); + } + } + } + + /// A record that cannot be restored stays drift while either file still + /// names the copy, in any spelling: bundler may still load the gem from + /// it, so the copy and both files are kept as found. + #[tokio::test] + async fn revert_of_a_dropped_gem_is_drift_while_a_file_names_the_copy() { + let (_, gemfile, lock) = dropped_gem_pairs()[0]; + let copy = copy_rel(); + let cases = [ + ( + "a Gemfile comment", + format!("{gemfile}# gem \"rack\", path: \"{copy}\"\n"), + lock.to_string(), + ), + ( + "a Gemfile path spelled with backslashes in another case", + format!( + "{gemfile}gem \"rack\", path: '{}'\n", + copy.replace('/', "\\").to_ascii_uppercase() + ), + lock.to_string(), + ), + ( + "a lock PATH section of another gem", + gemfile.to_string(), + format!("PATH\n remote: {copy}\n specs:\n rackup (1.0.0)\n\n{lock}"), + ), + ]; + for (what, gemfile, lock) in cases { + let (_tmp, root, entry) = vendored_then_edited(&gemfile, &lock).await; + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{what}: {:?}", outcome.error); + assert!(outcome.drift_skipped(), "{what}: {:?}", outcome.warnings); + assert!( + !outcome.lock_entry_removed(), + "{what}: {:?}", + outcome.warnings + ); + assert!(outcome.kept_artifact, "{what}"); + assert_eq!(read_pair(&root).await, (gemfile, lock), "{what}"); + assert!(root.join(copy_rel()).exists(), "{what}"); + } + } + + /// The files route the gem through a copy under ANOTHER patch uuid (a + /// re-vendor that was interrupted, a merge that kept an older ledger): + /// the project is still vendored and this entry may hold the only + /// pre-vendor originals, so it is drift, not a dropped gem. A copy of + /// another gem, or of another release, under that uuid is no such + /// reference. + #[tokio::test] + async fn revert_keeps_an_entry_whose_gem_is_wired_to_another_uuid() { + const OTHER: &str = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + let (tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let (result, entry, _w) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.unwrap(); + let (gemfile, lock) = read_pair(&root).await; + let (gemfile, lock) = (gemfile.replace(UUID, OTHER), lock.replace(UUID, OTHER)); + assert!(gemfile.contains(OTHER) && lock.contains(OTHER)); + tokio::fs::write(root.join(GEMFILE), &gemfile) + .await + .unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), &lock) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.drift_skipped(), "{:?}", outcome.warnings); + assert!(!outcome.lock_entry_removed(), "{:?}", outcome.warnings); + assert!(outcome.kept_artifact); + assert_eq!(read_pair(&root).await, (gemfile, lock)); + assert!(root.join(copy_rel()).exists()); + drop(tmp); + + let other = format!(".socket/vendor/gem/{OTHER}"); + for (line, names) in [ + (format!(" remote: {other}/rack-3.2.6"), true), + (format!("gem 'rack', path: '{other}/rack-3.2.6/'"), true), + (format!(" remote: {other}/rack-3.2.6-x86_64-linux"), true), + ( + format!( + "gem 'rack', path: '{}\\RACK-3.2.6'", + other.replace('/', "\\") + ), + true, + ), + (format!(" remote: {other}/rack-3.2.60"), false), + (format!(" remote: {other}/rack-3.2.6.1"), false), + (format!(" remote: {other}/rack-test-3.2.6"), false), + (format!(" remote: {other}/rackup-3.2.6"), false), + (" remote: vendor/forks/rack-3.2.6".to_string(), false), + ] { + assert_eq!( + names_a_vendored_copy_of(&line, "rack", "3.2.6"), + names, + "{line}" + ); + } + } + + /// #2325 with a CHECKSUMS section: `bundle remove` drops the gem's + /// checksum line with its spec, so the checksum record has nothing to + /// restore either. + #[tokio::test] + async fn revert_of_a_dropped_gem_with_checksums_removes_the_copy() { + let (_tmp, root, installed, blobs, record) = + fixture_318(SPIKE_GEMFILE_CHECKSUMS, SPIKE_LOCK_CHECKSUMS_BEFORE).await; + let (result, entry, _w) = + unwrap_done(run_vendor_318(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.unwrap(); + assert!( + entry + .wiring + .iter() + .any(|w| w.kind == LOCK_CHECKSUM_WIRING_KIND), + "the fixture records a checksum line" + ); + let gemfile = "source \"https://rubygems.org\"\n"; + let lock = "GEM\n remote: https://rubygems.org/\n specs:\n\nPLATFORMS\n aarch64-linux\n ruby\n\nDEPENDENCIES\n\nCHECKSUMS\n\nBUNDLED WITH\n 2.7.2\n"; + tokio::fs::write(root.join(GEMFILE), gemfile).await.unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), lock) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(!outcome.drift_skipped(), "{:?}", outcome.warnings); + assert!(outcome.lock_entry_removed(), "{:?}", outcome.warnings); + assert!(!outcome.kept_artifact); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()) + ); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + } + /// The user already put the gem back on the registry by hand, with a /// different constraint than the original: the Gemfile no longer routes /// through the copy, so that record has converged and the lock is