diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a14c8e681..2a36e54ef 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2156,7 +2156,16 @@ worse, lets a warm cache silently serve unpatched bytes): 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 + file of the two that cannot be read fails the revert, which keeps both; and where the `Gemfile` + line vendor wrote is still the gem's wiring after the user edited it — it is the gem's one + declaration, pins the vendored version, and its `path:` names this patch's copy, with options + added or taken off, the quotes switched, or the line moved into a `group`, `platforms` or + conditional block — so the revert + takes the `path:` off, puts the pre-vendor version requirement back and keeps the rest of the + line as the user has it, and the managed block of a transitive gem goes whole with an edit of + its line; a line that pins another version, carries a statement modifier or a second + statement, or sits in a `source` / `git` / `github` / `path` block stays drift, as does any + edited line while another line declares the gem too); 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 79487a879..2cf197f9d 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2378,6 +2378,130 @@ fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { } } +/// #2338: the user edits the Gemfile line of a vendored gem (an option +/// added, the line moved into a `group` block, the quotes switched). +/// Bundler takes the edited pair as it is, with the lock unchanged, and +/// `vendor --check` passes. Each undo command then reverts the gem: the +/// line gets its version requirement back, loses the `path:` and keeps the +/// edit, the lock is the pre-vendor one byte for byte, the copy and its +/// ledger record go, and a frozen install passes. +#[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_edited_gemfile_line_is_undone_by_every_undo_command() { + const ORIGINAL_LINE: &str = "gem \"rack\", \"~> 3.1\""; + // The user's edit of a `gem` line, and the command that undoes the + // vendoring. + type Edit = fn(&str) -> String; + let cases: [(&str, Edit, &[&str]); 4] = [ + ( + "require: false added", + |line| format!("{line}, require: false"), + &["vendor", "--revert"], + ), + ( + "moved into a group block", + |line| format!("group :test do\n {line}\nend"), + &["rollback"], + ), + ( + "group: option added", + |line| format!("{line}, group: :web"), + &["remove", "--yes"], + ), + ( + "quotes switched", + |line| line.replace('"', "'"), + &["rollback"], + ), + ]; + for (how, edit, undo) in cases { + let what = format!("{how}, then `{}`", undo.join(" ")); + let Some((_tmp, proj, _bundler, purl)) = staged_rack_project("edited line") else { + return; + }; + let cwd = proj.to_str().unwrap(); + let original_gemfile = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + assert!(original_gemfile.contains(ORIGINAL_LINE), "test premise"); + let original_lock = std::fs::read(proj.join("Gemfile.lock")).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"); + let vendored_lock = std::fs::read(proj.join("Gemfile.lock")).unwrap(); + + // The user's edit: bundler takes the pair as it is. + let wired = std::fs::read_to_string(proj.join("Gemfile")).unwrap(); + let wired_line = wired + .lines() + .find(|l| l.contains("path:")) + .expect("the wired line"); + let edited = wired.replace(wired_line, &edit(wired_line)); + std::fs::write(proj.join("Gemfile"), &edited).unwrap(); + for frozen in [false, true] { + let install = bundle(&proj, &["install"], frozen); + assert!( + install.status.success(), + "{what}: bundler accepts the edited pair (test premise, frozen: {frozen}):\n{}", + String::from_utf8_lossy(&install.stderr) + ); + } + assert_eq!( + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + vendored_lock, + "{what}: the edit leaves the lock as vendor wrote it (test premise)" + ); + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + assert_eq!( + code, 0, + "{what}: vendor --check takes the edited line as wired.\n{stdout}\n{stderr}" + ); + + // The undo. + 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 still-wired line is not reported as drift:\n{all}" + ); + + assert!(!uuid_dir.exists(), "{what}: the 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_to_string(proj.join("Gemfile")).unwrap(), + original_gemfile.replace(ORIGINAL_LINE, &edit(ORIGINAL_LINE)), + "{what}: the requirement is back, the `path:` is gone and the edit is kept" + ); + assert_eq!( + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + original_lock, + "{what}: the lock is the pre-vendor one" + ); + let install = bundle(&proj, &["install"], true); + assert!( + install.status.success(), + "{what}: a frozen install passes after the undo:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + } +} + /// #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 f8652d939..c447475ce 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -4422,24 +4422,34 @@ async fn revert_gemfile_record( return Ok(RecordRevert::Drifted); }; let mut lines: Vec<&str> = text.split('\n').collect(); - let Some(i) = find_wired_gemfile_line(&lines, written) else { - // ALREADY CONVERGED: the pre-vendor line is back (a hand - // restore, a `bundle update` regeneration, an earlier partial - // revert) — not drift, nothing to write. - // Either line ending: a re-checkout may have changed it. - let original = original.strip_suffix('\r').unwrap_or(original); - if lines - .iter() - .any(|l| l.strip_suffix('\r').unwrap_or(l) == original) - { - return Ok(RecordRevert::Done); + let (i, line) = match find_wired_gemfile_line(&lines, written) { + Some(i) => { + if let Some(why) = own.rewrite_refusal(written, original) { + return Err(own.refused(w, why)); + } + (i, restore_gemfile_line(lines[i], written, original)) } - return Ok(gemfile_left_without_our_line(text, written)); + None => match restore_edited_gemfile_line(text, &lines, written, original, own) { + // STILL WIRED, EDITED (#2338): restored around the + // user's edit. + Some(restored) => restored, + None => { + // ALREADY CONVERGED: the pre-vendor line is back (a + // hand restore, a `bundle update` regeneration, an + // earlier partial revert) — not drift, nothing to + // write. Either line ending: a re-checkout may have + // changed it. + let original = original.strip_suffix('\r').unwrap_or(original); + if lines + .iter() + .any(|l| l.strip_suffix('\r').unwrap_or(l) == original) + { + return Ok(RecordRevert::Done); + } + return Ok(gemfile_left_without_our_line(text, written)); + } + }, }; - if let Some(why) = own.rewrite_refusal(written, original) { - return Err(own.refused(w, why)); - } - let line = restore_gemfile_line(lines[i], written, original); lines[i] = &line; lines.join("\n") } @@ -4453,18 +4463,30 @@ async fn revert_gemfile_record( written = line_endings::respell(&written, line_endings::terminator(text)).into(); found = text.find(&*written); } - let Some(at) = found else { - // ALREADY CONVERGED: an Added block's reverted state is its - // absence (the LIVENESS CONTRACT's "key is absent" case) — - // unless an edited copy of it still wires the gem in. - return Ok(gemfile_left_without_our_line(text, &written)); + let block = match found { + Some(at) => at..at + written.len(), + // STILL WIRED, EDITED (#2338): the block goes with the + // user's edit of its line. + None => match own + .block_refusal(&written) + .is_none() + .then(|| edited_managed_block(text, own)) + .flatten() + { + Some(block) => block, + // ALREADY CONVERGED: an Added block's reverted state is + // its absence (the LIVENESS CONTRACT's "key is absent" + // case) — unless an edited copy of it still wires the + // gem in. + None => return Ok(gemfile_left_without_our_line(text, &written)), + }, }; if let Some(why) = own.block_refusal(&written) { return Err(own.refused(w, why)); } let mut out = String::with_capacity(text.len()); - out.push_str(&text[..at]); - out.push_str(&text[at + written.len()..]); + out.push_str(&text[..block.start]); + out.push_str(&text[block.end..]); out } }; @@ -4491,6 +4513,240 @@ fn find_wired_gemfile_line(lines: &[&str], written: &str) -> Option { hits.next().is_none().then_some(i) } +/// The wired declaration of `own`'s gem on a Gemfile line whose code the +/// user edited (#2338), read argument by argument: the one quoted pin of +/// the vendored version, the one `path:` to this patch's copy, and keyword +/// options around them. `None` for a line that is anything else: another +/// pin or a second constraint, a positional argument, a statement modifier, +/// a second statement, a parenthesized call. +struct EditedWiredLine<'l> { + /// The line up to the end of the gem's name: its indentation and + /// `gem ""` as the user spells them. + head: &'l str, + /// The quote the user's line names the gem with. + quote: char, + /// The options beside `path:`, in the line's order, each trimmed. + keywords: Vec<&'l str>, +} + +impl OwnGem<'_> { + fn edited_wired_line<'l>(&self, line: &'l str) -> Option> { + let body = line.strip_suffix('\r').unwrap_or(line); + let decl = self.vendored_declaration(body.trim_start())?; + if !is_one_line(body, false) || gem_line_tail_blocks_edit(decl.rest).is_some() { + return None; + } + let args = gemfile::split_args(gemfile::code_of(decl.rest)?)?; + // The tail opens with the comma after the name. + let (first, args) = args.split_first()?; + if !first.1.trim().is_empty() { + return None; + } + let (mut pins, mut paths, mut keywords) = (0, 0, Vec::new()); + for (i, (_, arg)) in args.iter().enumerate() { + let arg = arg.trim(); + // A bare string is a version constraint: the pin vendor wrote, + // first, and no other. A string with more behind it is the key + // of an option (`"require" => false`). + if let Some((_, value, "")) = quoted_literal(arg) { + let value = value.trim(); + let pinned = value.strip_prefix('=').map_or(value, str::trim_start); + if i != 0 || pinned != self.version { + return None; + } + pins += 1; + } else if let Some(value) = arg.strip_prefix("path:") { + let (_, path, after) = quoted_literal(value.trim_start())?; + if !after.is_empty() || !self.is_copy(path) { + return None; + } + paths += 1; + } else if is_keyword_arg(arg) || outside_strings(arg, "=>") { + keywords.push(arg); + } else { + return None; + } + } + (pins == 1 && paths == 1).then(|| EditedWiredLine { + head: &body[..body.len() - decl.rest.len()], + quote: decl.quote, + keywords, + }) + } + + /// The Gemfile's one line that declares the gem, or that names it in + /// a `gem` call the line grammar cannot read as another gem's + /// declaration. `None` when there is no such line, or more than one. + fn sole_declaration<'l>(&self, lines: &[&'l str]) -> Option<(usize, &'l str)> { + let mut declared = lines.iter().enumerate().filter(|(_, l)| { + let trimmed = l.trim_start(); + match gem_declaration_any(trimmed) { + Some(decl) => decl.name == self.name, + None => gem_call_mentions_name(trimmed, &self.name), + } + }); + let (i, line) = declared.next()?; + declared.next().is_none().then_some((i, *line)) + } +} + +/// Whether `code` holds `pat` outside its string literals. +fn outside_strings(code: &str, pat: &str) -> bool { + let mut quote: Option = None; + let mut escaped = false; + for (i, c) in code.char_indices() { + match quote { + Some(_) if escaped => escaped = false, + Some(_) if c == '\\' => escaped = true, + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == '"' || c == '\'' => quote = Some(c), + None if code[i..].starts_with(pat) => return true, + None => {} + } + } + false +} + +/// The Gemfile's one declaration of `own`'s gem, when the user edited the +/// code of the line vendor wrote and it still wires the gem to this +/// patch's copy at the vendored version (#2338): its index in `lines` and +/// the line to put there. Vendor reads such a line as wired, and so do +/// `vendor --check` and bundler, so the revert does as well, and undoes +/// only what vendor did: +/// +/// - the pin goes back to the `original` line's version constraints; +/// - the `path:` option comes off; +/// - every other option is the user's line's, so one they added stays and +/// one they took off stays off, as do the line's indentation (a move +/// into a `group`, `platforms` or conditional block) and its quotes; +/// - the comment follows [`restore_gemfile_line`]: the original's, unless +/// the user changed the one vendor wrote. +/// +/// `None`, which leaves the line to the drift rule, when the gem is +/// declared more than once, when the line is not one +/// [`EditedWiredLine`], when it now sits in a block that picks its gems' +/// source (`source`, `git`, `github`, `path`: restored there, the gem +/// would resolve from a source the restored lock does not name), or when +/// the restored line would not be a plain declaration vendor could have +/// rewritten. +fn restore_edited_gemfile_line( + text: &str, + lines: &[&str], + written: &str, + original: &str, + own: &OwnGem<'_>, +) -> Option<(usize, String)> { + // The ledger's lines are held to the rule of an unedited restore. + if own.rewrite_refusal(written, original).is_some() { + return None; + } + let (i, live) = own.sole_declaration(lines)?; + let edited = own.edited_wired_line(live)?; + let line_start: usize = lines[..i].iter().map(|l| l.len() + 1).sum(); + if crate::formats::gem::ruby::block_stack(text, line_start) + .iter() + .any(|frame| frame.source.is_some()) + { + return None; + } + + // The original's version constraints: its code up to the keyword + // options the vendored line carried over, less a `;` that ends the + // statement. Anything else behind a `;` is not this declaration's. + let original_body = original.strip_suffix('\r').unwrap_or(original); + let original_decl = gem_declaration(original_body, &own.name)?; + let original_head = &original_body[..original_body.len() - original_decl.rest.len()]; + let original_code = split_line_comment(original_decl.rest).0.trim_end(); + let original_code = original_code + .strip_suffix(';') + .map_or(original_code, str::trim_end); + if outside_strings(original_code, ";") { + return None; + } + let kept = kept_keywords(original_decl.rest); + let constraints = if kept.is_empty() { + original_code + } else { + original_code + .strip_suffix(kept.as_str())? + .trim_end() + .strip_suffix(',')? + .trim_end() + }; + + // The head is the user's. One vendor's rewrite left as it wrote it + // (`gem ""`) goes back to the original's spelling, behind the + // line's indentation; one in other quotes takes the constraints along, + // when they are plain strings that read the same in either. + let written_body = written.strip_suffix('\r').unwrap_or(written); + let written_decl = gem_declaration(written_body, &own.name)?; + let written_head = &written_body[..written_body.len() - written_decl.rest.len()]; + let indent = &edited.head[..edited.head.len() - edited.head.trim_start().len()]; + let mut line = if edited.head.trim_start() == written_head { + format!("{indent}{original_head}{constraints}") + } else if edited.quote != original_decl.quote + && !constraints.contains([edited.quote, '\\', '#']) + { + let constraints = constraints.replace(original_decl.quote, &edited.quote.to_string()); + format!("{}{constraints}", edited.head) + } else { + format!("{}{constraints}", edited.head) + }; + for keyword in &edited.keywords { + line.push_str(", "); + line.push_str(keyword); + } + let (live_code, live_comment) = split_line_comment(live); + let (_, written_comment) = split_line_comment(written); + if live_comment.trim() == written_comment.trim() { + line.push_str(&original_body[split_line_comment(original).0.trim_end().len()..]); + } else { + let live_body = live.strip_suffix('\r').unwrap_or(live); + line.push_str(live_body[live_code.trim_end().len()..].trim_end()); + } + + // What goes back is a declaration vendor could rewrite again: one + // plain call, no source option, nothing computed. + let restored = gem_declaration(line.trim_start(), &own.name)?; + if restored.paren || rest_blocks_edit(restored.rest).is_some() { + return None; + } + let ends_cr = if live.ends_with('\r') == written.ends_with('\r') { + original.ends_with('\r') + } else { + live.ends_with('\r') + }; + if ends_cr { + line.push('\r'); + } + Some((i, line)) +} + +/// The byte range of `own`'s managed block in the Gemfile `text`, when the +/// user edited the declaration between its fences (#2338): the two fence +/// lines around the Gemfile's one declaration of the gem, which still +/// wires it to this patch's copy at the vendored version +/// ([`EditedWiredLine`]). The block is vendor's own text and the gem had +/// no declaration before it, so the whole of it goes, the user's option or +/// comment on that line included. `None` leaves the block to the drift +/// rule. +fn edited_managed_block(text: &str, own: &OwnGem<'_>) -> Option> { + let lines: Vec<&str> = text.split('\n').collect(); + let (i, live) = own.sole_declaration(&lines)?; + own.edited_wired_line(live)?; + let fence = |at: Option, want: &str| { + at.and_then(|at| lines.get(at)) + .is_some_and(|l| l.strip_suffix('\r').unwrap_or(l) == want) + }; + if !fence(i.checked_sub(1), MANAGED_OPEN) || !fence(Some(i + 1), MANAGED_CLOSE) { + return None; + } + let start: usize = lines[..i - 1].iter().map(|l| l.len() + 1).sum(); + let len: usize = lines[i - 1..=i + 1].iter().map(|l| l.len() + 1).sum(); + Some(start..(start + len).min(text.len())) +} + /// What a Gemfile whose recorded wiring (`written`: the rewritten line or /// the managed block) is no longer found verbatim means for the revert. /// Vendor reads a Gemfile that still contains the copy path as wired, so @@ -6775,33 +7031,73 @@ mod tests { } /// The Gemfile still routes the gem through the copy, but in a form - /// revert won't rewrite (an option added to the wired line, or a - /// comment added inside the managed block): drift, and neither file is - /// written, so the user's edit is never dropped and the lock never - /// leaves the Gemfile's `path:` behind. + /// revert won't rewrite: the pin moved off the vendored version, a + /// statement modifier or a second statement on the wired line, the + /// line moved into a block that picks its gems' source, or a line + /// added inside the managed block. Drift, and neither file is written, + /// so the lock never leaves the Gemfile's `path:` behind. #[tokio::test] - async fn revert_still_wired_but_edited_gemfile_writes_neither_file() { + async fn revert_still_wired_but_unreadable_gemfile_writes_neither_file() { let rack_line = format!("gem \"rack\", \"3.2.6\", path: \"{}\"", copy_rel()); + let managed_line = format!("{rack_line}, require: false"); let cases = [ ( GEMFILE_DIRECT, LOCK_DIRECT, - format!("{rack_line}, require: false"), + rack_line.clone(), + rack_line.replace("\"3.2.6\"", "\"3.2.7\""), + ), + ( + GEMFILE_DIRECT, + LOCK_DIRECT, + rack_line.clone(), + format!("{rack_line} if ENV[\"RACK\"]"), + ), + ( + GEMFILE_DIRECT, + LOCK_DIRECT, + rack_line.clone(), + format!("{rack_line}; gem \"base64\""), + ), + ( + GEMFILE_DIRECT, + LOCK_DIRECT, + rack_line.clone(), + format!("{rack_line}, \">= 3\""), + ), + ( + GEMFILE_DIRECT, + LOCK_DIRECT, + rack_line.clone(), + format!("source \"https://gems.example\" do\n {rack_line}\nend"), + ), + ( + GEMFILE_DIRECT, + LOCK_DIRECT, + rack_line.clone(), + format!("{rack_line}, require: false\ngem \"rack\", \"3.2.6\""), + ), + ( + GEMFILE_TRANSITIVE, + LOCK_TRANSITIVE, + managed_line.clone(), + format!("{managed_line}\ngem \"base64\""), ), ( GEMFILE_TRANSITIVE, LOCK_TRANSITIVE, - format!("{rack_line} # managed, keep"), + managed_line.clone(), + format!("{rack_line} if ENV[\"RACK\"]"), ), ]; - for (gemfile, lock, edited_line) in cases { + for (gemfile, lock, wired_line, edited_line) in cases { let (_tmp, root, installed, blobs, record) = fixture(gemfile, lock).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 wired = tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(); - let edited = wired.replace(&rack_line, &edited_line); + let edited = wired.replace(&wired_line, &edited_line); assert_ne!(edited, wired, "{edited_line}"); tokio::fs::write(root.join(GEMFILE), &edited).await.unwrap(); let wired_lock = tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) @@ -6832,6 +7128,306 @@ mod tests { } } + /// Vendor rack into a project with the Gemfile `gemfile` and + /// [`LOCK_DIRECT`] or [`LOCK_TRANSITIVE`], let the user `edit` the wired + /// Gemfile, and revert. Returns the outcome with the pair as left. + async fn revert_after_gemfile_edit( + gemfile: &str, + lock: &str, + edit: impl Fn(&str) -> String, + ) -> (RevertOutcome, String, String) { + let (_tmp, root, installed, blobs, record) = fixture(gemfile, lock).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 wired = tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(); + let edited = edit(&wired); + assert_ne!(edited, wired, "the edit changes the wired Gemfile"); + tokio::fs::write(root.join(GEMFILE), &edited).await.unwrap(); + + // Vendor reads the edited line as wired: the revert has to agree. + let (rerun, rerun_entry, _) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(rerun.success, "{edited}: {:?}", rerun.error); + assert!(rerun_entry.is_none(), "{edited}: in sync, no new entry"); + + let outcome = revert_gem(&entry, &root, false).await; + assert_eq!( + root.join(format!(".socket/vendor/gem/{UUID}")).exists(), + outcome.kept_artifact, + "{edited}" + ); + ( + outcome, + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) + .await + .unwrap(), + ) + } + + /// #2338: the user edited the wired line (an option added, the line + /// moved into a `group` block, the quotes switched). It still pins the + /// vendored version at this patch's copy, so the revert takes the + /// `path:` off, puts the pre-vendor requirement back and keeps the edit. + #[tokio::test] + async fn revert_edited_wired_gemfile_line_restores_the_pair_and_keeps_the_edit() { + let rack_line = format!("gem \"rack\", \"3.2.6\", path: \"{}\"", copy_rel()); + let cases: [(&str, String, &str); 10] = [ + ( + "moved into a conditional block", + format!("if ENV[\"RACK\"]\n {rack_line}\nend"), + "if ENV[\"RACK\"]\n gem \"rack\", \"~> 3.1\"\nend", + ), + ( + "string-keyed option added", + format!("{rack_line}, \"require\" => false"), + "gem \"rack\", \"~> 3.1\", \"require\" => false", + ), + ( + "option added", + format!("{rack_line}, require: false"), + "gem \"rack\", \"~> 3.1\", require: false", + ), + ( + "group option added", + format!("{rack_line}, group: :web"), + "gem \"rack\", \"~> 3.1\", group: :web", + ), + ( + "hash-rocket option and a comment added", + format!("{rack_line}, :require => false # lazy"), + "gem \"rack\", \"~> 3.1\", :require => false # lazy", + ), + ( + "moved into a group block", + format!("group :test do\n {rack_line}\nend"), + "group :test do\n gem \"rack\", \"~> 3.1\"\nend", + ), + ( + "moved into a group block, option added", + format!("group :test do\n\t{rack_line}, require: false\nend"), + "group :test do\n\tgem \"rack\", \"~> 3.1\", require: false\nend", + ), + ( + "quotes switched", + rack_line.replace('"', "'"), + "gem 'rack', '~> 3.1'", + ), + ( + "option moved before path:", + format!( + "gem \"rack\", \"3.2.6\", require: false, path: \"{}\"", + copy_rel() + ), + "gem \"rack\", \"~> 3.1\", require: false", + ), + ( + "spacing changed", + format!("gem \"rack\",\"3.2.6\",path: \"{}\"", copy_rel()), + "gem \"rack\", \"~> 3.1\"", + ), + ]; + for (what, edited_line, restored_line) in cases { + let (outcome, gemfile, lock) = + revert_after_gemfile_edit(GEMFILE_DIRECT, LOCK_DIRECT, |wired| { + wired.replace(&rack_line, &edited_line) + }) + .await; + assert!(outcome.success, "{what}: {:?}", outcome.error); + assert!( + outcome.warnings.is_empty(), + "{what}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{what}"); + assert_eq!( + gemfile, + GEMFILE_DIRECT.replace("gem \"rack\", \"~> 3.1\"", restored_line), + "{what}" + ); + assert_eq!(lock, LOCK_DIRECT, "{what}"); + } + } + + /// #2338: the options and the comment the original line had come back + /// as the user left them on the wired line: an option they took off + /// stays off, one they added stays, and an untouched comment keeps the + /// original's spacing. + #[tokio::test] + async fn revert_edited_wired_gemfile_line_follows_the_users_options() { + let gemfile = "source \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"rack\", \"~> 3.1\", \"< 4\", require: false # web\n"; + let wired_line = format!( + "gem \"rack\", \"3.2.6\", path: \"{}\", require: false # web", + copy_rel() + ); + let path_line = format!("gem \"rack\", \"3.2.6\", path: \"{}\"", copy_rel()); + for (edited_line, restored_line) in [ + ( + format!("{path_line}, require: false, group: :web # web"), + "gem \"rack\", \"~> 3.1\", \"< 4\", require: false, group: :web # web", + ), + ( + format!("{path_line} # web"), + "gem \"rack\", \"~> 3.1\", \"< 4\" # web", + ), + ( + format!("{path_line}, group: :web # edge"), + "gem \"rack\", \"~> 3.1\", \"< 4\", group: :web # edge", + ), + ( + format!("{path_line}, require: false, group: :web"), + "gem \"rack\", \"~> 3.1\", \"< 4\", require: false, group: :web", + ), + ] { + let (outcome, left, lock) = revert_after_gemfile_edit(gemfile, LOCK_DIRECT, |wired| { + assert!(wired.contains(&wired_line), "{wired}"); + wired.replace(&wired_line, &edited_line) + }) + .await; + assert!(outcome.success, "{edited_line}: {:?}", outcome.error); + assert!( + outcome.warnings.is_empty(), + "{edited_line}: {:?}", + outcome.warnings + ); + assert_eq!( + left, + gemfile.replace( + "gem \"rack\", \"~> 3.1\", \"< 4\", require: false # web", + restored_line + ), + "{edited_line}" + ); + assert_eq!(lock, LOCK_DIRECT, "{edited_line}"); + } + } + + /// #2338: what the original line holds beside its constraints does not + /// stand in the way of an edited line's restore: a string-keyed option, + /// a `;` (in a string, or ending the statement), a tab after `gem`, or + /// another gem's line that names this one. + #[tokio::test] + async fn revert_edited_wired_gemfile_line_reads_the_original_as_vendor_did() { + let path = format!("path: \"{}\"", copy_rel()); + for (original_line, wired_line, edit, restored_line) in [ + ( + "gem \"rack\", \"~> 3.1\", \"require\" => false", + format!("gem \"rack\", \"3.2.6\", {path}, \"require\" => false"), + ", group: :web", + "gem \"rack\", \"~> 3.1\", \"require\" => false, group: :web", + ), + ( + "gem \"rack\", \"~> 3.1\", require: \"a;b\"", + format!("gem \"rack\", \"3.2.6\", {path}, require: \"a;b\""), + ", group: :web", + "gem \"rack\", \"~> 3.1\", require: \"a;b\", group: :web", + ), + ( + "gem \"rack\", \"~> 3.1\";", + format!("gem \"rack\", \"3.2.6\", {path}"), + ", require: false", + "gem \"rack\", \"~> 3.1\", require: false", + ), + ( + "gem\t\"rack\", \"~> 3.1\"", + format!("gem \"rack\", \"3.2.6\", {path}"), + ", require: false", + "gem\t\"rack\", \"~> 3.1\", require: false", + ), + ( + "gem \"rack\", \"~> 3.1\"\ngem \"puma-rack\", require: \"rack\"", + format!("gem \"rack\", \"3.2.6\", {path}"), + ", require: false", + "gem \"rack\", \"~> 3.1\", require: false\ngem \"puma-rack\", require: \"rack\"", + ), + ] { + let gemfile = + format!("source \"https://rubygems.org\"\n\ngem \"puma\"\n{original_line}\n"); + let (outcome, left, lock) = revert_after_gemfile_edit(&gemfile, LOCK_DIRECT, |wired| { + assert!(wired.contains(&format!("{wired_line}\n")), "{wired}"); + wired.replace(&wired_line, &format!("{wired_line}{edit}")) + }) + .await; + assert!(outcome.success, "{original_line}: {:?}", outcome.error); + assert!( + outcome.warnings.is_empty(), + "{original_line}: {:?}", + outcome.warnings + ); + assert_eq!( + left, + gemfile.replace(original_line, restored_line), + "{original_line}" + ); + assert_eq!(lock, LOCK_DIRECT, "{original_line}"); + } + } + + /// #2338 in a CRLF Gemfile: the restored line keeps the file's ending. + #[tokio::test] + async fn revert_edited_wired_gemfile_line_keeps_crlf() { + let gemfile = GEMFILE_DIRECT.replace('\n', "\r\n"); + let wired_line = format!("gem \"rack\", \"3.2.6\", path: \"{}\"\r\n", copy_rel()); + let (outcome, left, lock) = revert_after_gemfile_edit(&gemfile, LOCK_DIRECT, |wired| { + assert!(wired.contains(&wired_line), "{wired:?}"); + wired.replace( + &wired_line, + &wired_line.replace("\r\n", ", require: false\r\n"), + ) + }) + .await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!( + left, + gemfile.replace( + "gem \"rack\", \"~> 3.1\"\r\n", + "gem \"rack\", \"~> 3.1\", require: false\r\n" + ) + ); + assert!(all_crlf(&left), "{left:?}"); + assert_eq!(lock, LOCK_DIRECT); + } + + /// #2338: the managed block of a transitive gem is this patch's own + /// text. An option or a comment the user added to its line goes with + /// the block, in either line ending. + #[tokio::test] + async fn revert_edited_managed_block_line_removes_the_block() { + let managed_line = format!( + "gem \"rack\", \"3.2.6\", path: \"{}\", require: false", + copy_rel() + ); + for nl in ["\n", "\r\n"] { + let gemfile = GEMFILE_TRANSITIVE.replace('\n', nl); + for edited_line in [ + format!("{managed_line}, group: :web"), + format!("{managed_line} # managed, keep"), + managed_line.replace(", require: false", " # managed, keep"), + managed_line.replace('"', "'"), + format!(" {managed_line}"), + ] { + let (outcome, left, lock) = + revert_after_gemfile_edit(&gemfile, LOCK_TRANSITIVE, |wired| { + assert!(wired.contains(&managed_line), "{wired}"); + wired.replace(&managed_line, &edited_line) + }) + .await; + assert!(outcome.success, "{edited_line}: {:?}", outcome.error); + assert!( + outcome.warnings.is_empty(), + "{edited_line}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{edited_line}"); + assert_eq!(left, gemfile, "{edited_line}"); + assert_eq!(lock, LOCK_TRANSITIVE, "{edited_line}"); + } + } + } + /// 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] {