diff --git a/crates/socket-patch-core/src/formats/cargo/hosted.rs b/crates/socket-patch-core/src/formats/cargo/hosted.rs index 4545b4013..78f4a5584 100644 --- a/crates/socket-patch-core/src/formats/cargo/hosted.rs +++ b/crates/socket-patch-core/src/formats/cargo/hosted.rs @@ -19,16 +19,35 @@ use super::CargoLock; /// `@`, and the inverse replaces EVERY occurrence of `new`. pub(crate) const CARGO_LOCK_REFERENCE_KIND: &str = "redirect_cargo_lock_reference"; -/// Apply non-overlapping `splices` (ranges into `text`) to `text`. -fn splice(text: &str, mut splices: Vec<(Range, String)>) -> String { - splices.sort_by_key(|(r, _)| std::cmp::Reverse(r.start)); - let mut out = text.to_string(); - for (range, with) in splices { - out.replace_range(range, &with); +/// One replacement of a byte range of a lock's text. +pub(crate) type Splice = (Range, String); + +/// Apply non-overlapping `splices` (ranges into `text`) to `text`, in one +/// pass. Of two insertions at one offset the later one in `splices` comes +/// first in the result. +pub(crate) fn splice(text: &str, mut splices: Vec) -> String { + splices.reverse(); + splices.sort_by_key(|(range, _)| range.start); + let added: usize = splices.iter().map(|(_, with)| with.len()).sum(); + let mut out = String::with_capacity(text.len() + added); + let mut from = 0; + for (range, with) in &splices { + out.push_str(&text[from..range.start]); + out.push_str(with); + from = range.end; } + out.push_str(&text[from..]); out } +/// Whether `value` is the same text inside a TOML basic string as outside +/// it: nothing a `"…"` would end on or read as an escape. +fn spelled_as_it_is(value: &str) -> bool { + !value + .chars() + .any(|c| c == '"' || c == '\\' || c.is_control()) +} + /// Where a line inserted after the one `value` ends sits: just past that /// line's newline, or at `end` (the block's last byte) with the newline to /// prepend when the line ends the text. @@ -85,16 +104,20 @@ impl CargoLock { /// revert is unambiguous) — the entry and the `[metadata]` line — and the /// dependents' references are one `redirect_cargo_lock_reference` edit /// holding the quoted full id, reverted at every occurrence. - pub(crate) fn plan_hosted( + /// + /// The repoint is returned as splices into `content`, none overlapping + /// another, so a rewrite of several crates can hold them against one + /// parse ([`CargoHostedLock`]). + pub(crate) fn plan_hosted_splices( &self, content: &str, crate_name: &str, version: &str, index_url: &str, cksum: &str, - ) -> CargoLockPlan { + ) -> CargoLockSplices { let Some(spans) = self.spans() else { - return CargoLockPlan::NotFound; + return CargoLockOutcome::NotFound; }; // Every block for this name@version. A Cargo.lock may legitimately // hold TWO blocks for one name@version from different sources — after @@ -105,7 +128,7 @@ impl CargoLock { .filter(|&i| self.packages[i].name == crate_name && self.packages[i].version == version) .collect(); let i = match hits.as_slice() { - [] => return CargoLockPlan::NotFound, + [] => return CargoLockOutcome::NotFound, [only] => *only, twins => { // Exactly one twin already at the target index is OURS (a @@ -117,7 +140,7 @@ impl CargoLock { .filter(|&i| self.packages[i].source.as_deref() == Some(index_url)); match (ours.next(), ours.next()) { (Some(i), None) => i, - _ => return CargoLockPlan::Ambiguous, + _ => return CargoLockOutcome::Ambiguous, } } }; @@ -199,6 +222,15 @@ impl CargoLock { edits.push(edit(original, &rebuilt)); splices.push((block_start..block_end, rebuilt)); } + // Two values replaced where they stand, by text a string holds as + // it is: the lock then parses exactly as it did. A line added to + // the block, a `[metadata]` line or a full-id reference (below) + // is more than that. + let mut local = metadata_line.is_none() + && at.source.is_some() + && at.checksum.is_some() + && spelled_as_it_is(index_url) + && spelled_as_it_is(cksum); if let Some((_, line)) = metadata_line { let pinned = format!("\"checksum {crate_name} {version} ({index_url})\" = \"{cksum}\""); if content[line.clone()] != pinned { @@ -235,6 +267,7 @@ impl CargoLock { .cloned() .collect(); if !refs.is_empty() { + local = false; splices.extend(refs.into_iter().map(|r| (r, to.clone()))); edits.push(FileEdit { kind: CARGO_LOCK_REFERENCE_KIND.into(), @@ -246,24 +279,25 @@ impl CargoLock { // a recorded edit would have original == new and grow the ledger // forever. if edits.is_empty() { - return CargoLockPlan::AlreadyRedirected; + return CargoLockOutcome::AlreadyRedirected; } - CargoLockPlan::Rewritten { - content: splice(content, splices), + CargoLockOutcome::Rewritten(RepointSplices { + package: i, + splices, edits, - } + local, + }) } } /// Outcome of the Cargo.lock `[[package]]` plan — distinguishes a re-run /// over an already-redirected block (no edit, no warning) from a genuinely -/// missing package (the caller warns AND skips the dep entirely). +/// missing package (the caller warns AND skips the dep entirely). `R` is +/// the repoint: [`RepointSplices`] from the planner, [`PlannedRepoint`] +/// from a [`CargoHostedLock`]. #[derive(Debug)] -pub(crate) enum CargoLockPlan { - Rewritten { - content: String, - edits: Vec, - }, +pub(crate) enum CargoLockOutcome { + Rewritten(R), AlreadyRedirected, NotFound, /// Several `[[package]]` blocks for the name@version (multi-source twins) @@ -271,3 +305,239 @@ pub(crate) enum CargoLockPlan { /// cannot be decided, so the caller warns AND skips the dep entirely. Ambiguous, } + +impl CargoLockOutcome { + fn map(self, repoint: impl FnOnce(R) -> T) -> CargoLockOutcome { + match self { + CargoLockOutcome::Rewritten(found) => CargoLockOutcome::Rewritten(repoint(found)), + CargoLockOutcome::AlreadyRedirected => CargoLockOutcome::AlreadyRedirected, + CargoLockOutcome::NotFound => CargoLockOutcome::NotFound, + CargoLockOutcome::Ambiguous => CargoLockOutcome::Ambiguous, + } + } +} + +/// What [`CargoLock::plan_hosted_splices`] answers. +pub(crate) type CargoLockSplices = CargoLockOutcome; + +/// What [`CargoHostedLock::plan`] answers. +pub(crate) type CargoLockRepoint<'a> = CargoLockOutcome>; + +/// The repoint of the `package`th block, as splices into the text the model +/// was parsed from, with the edits that record them. +#[derive(Debug)] +pub(crate) struct RepointSplices { + pub(crate) package: usize, + pub(crate) splices: Vec, + pub(crate) edits: Vec, + /// The repoint is the block's `source` and inline `checksum` values + /// replaced where they stand, and nothing else: the lock parses as it + /// did, to the same model but for those two values. `false` when a + /// line is added to the block, or a v1 `[metadata]` line or a full-id + /// reference elsewhere in the lock follows the package. + pub(crate) local: bool, +} + +/// A repoint a [`CargoHostedLock`] planned, holding the lock until it is +/// committed or dropped: no other plan can come between the two, and the +/// edits that record it are given out only as it is made. +#[derive(Debug)] +pub(crate) struct PlannedRepoint<'a> { + lock: &'a mut CargoHostedLock, + repoint: RepointSplices, + source: String, + checksum: String, +} + +impl PlannedRepoint<'_> { + /// Make the repoint part of the lock, and give the edits that record + /// it. + pub(crate) fn commit(self) -> Vec { + let PlannedRepoint { + lock, + repoint, + source, + checksum, + } = self; + let RepointSplices { + package, + splices, + edits, + local, + } = repoint; + lock.pending.extend(splices); + match lock.model.get_mut() { + Some(Some(model)) if local => { + if let Some(found) = model.packages.get_mut(package) { + found.source = Some(source); + found.checksum = Some(checksum); + } + lock.repointed.push(package); + } + _ => lock.parse_again(), + } + edits + } + + /// The edits [`Self::commit`] would give. + #[cfg(test)] + pub(crate) fn edits(&self) -> &[FileEdit] { + &self.repoint.edits + } +} + +/// A project's `Cargo.lock` across one hosted rewrite: its text, and one +/// parse of it for every probe and every plan of the rewrite to read. +/// +/// A committed repoint is kept as splices into that text and applied when +/// the rewrite ends, so a lock in the format cargo has written since 1.41 +/// is parsed once however many crates are repointed (it used to be parsed +/// several times per crate, #761), and not at all by a rewrite that never +/// reads it. +/// +/// [`Self::model`] and [`Self::plan`] answer exactly as a fresh parse of +/// the lock as the rewrite has it so far would. Three rules keep that: +/// +/// * A repoint that only replaces the block's `source` and `checksum` +/// values ([`RepointSplices::local`]) writes the two into the model. +/// The lock parses as it did, and nothing else of the model reads that +/// text. +/// * Any other repoint (a line added to the block, a v1 lock's +/// `[metadata]` line, a full id in another block) is applied to the text +/// at once, and the text is parsed again on its next use. If the lock no +/// longer parses, the crates after it are refused, as they were when +/// every crate parsed the lock. +/// * A plan reads the bytes through the parse's spans, so it is made on a +/// fresh parse when those bytes are no longer the lock's: for a package +/// this rewrite has repointed since the parse, and for a rewrite with a +/// splice that touches a pending one (a full id inside a repointed +/// block). +#[derive(Debug)] +pub(crate) struct CargoHostedLock { + text: String, + /// The parse of `text`, made on first use; `None` inside when the text + /// is not a lock cargo can read. + model: std::cell::OnceCell>, + /// Committed splices into `text`, none overlapping another. + pending: Vec, + /// The packages (by index in the model) repointed since the parse. + repointed: Vec, + /// How often the text was parsed. + #[cfg(test)] + parses: std::cell::Cell, +} + +impl CargoHostedLock { + pub(crate) fn new(text: String) -> Self { + CargoHostedLock { + text, + model: std::cell::OnceCell::new(), + pending: Vec::new(), + repointed: Vec::new(), + #[cfg(test)] + parses: std::cell::Cell::new(0), + } + } + + #[cfg(test)] + pub(crate) fn parses(&self) -> usize { + self.parses.get() + } + + /// The lock as the rewrite has it so far, for the probes; `None` when + /// it is not a lock cargo can read. + pub(crate) fn model(&self) -> Option<&CargoLock> { + self.model + .get_or_init(|| { + #[cfg(test)] + self.parses.set(self.parses.get() + 1); + CargoLock::parse(&self.text).ok() + }) + .as_ref() + } + + /// [`CargoLock::plan_hosted_splices`] for the lock as the rewrite has + /// it so far. A rewrite takes effect with [`PlannedRepoint::commit`], + /// once everything else of the crate is planned. + pub(crate) fn plan( + &mut self, + crate_name: &str, + version: &str, + index_url: &str, + cksum: &str, + ) -> CargoLockRepoint<'_> { + // The package's own bytes are not the ones parsed any more. + if self.has_repointed(crate_name, version) { + self.parse_again(); + } + let on_this_parse = |lock: &CargoHostedLock| match lock.model() { + Some(model) => { + model.plan_hosted_splices(&lock.text, crate_name, version, index_url, cksum) + } + None => CargoLockOutcome::NotFound, + }; + let mut found = on_this_parse(self); + // Nor are the bytes of a block an earlier repoint rebuilt, which + // this one would write a full id into. + let touches_pending = match &found { + CargoLockOutcome::Rewritten(repoint) => !repoint + .splices + .iter() + .all(|(range, _)| self.clear_of_pending(range)), + _ => false, + }; + if touches_pending { + self.parse_again(); + found = on_this_parse(self); + } + found.map(|repoint| PlannedRepoint { + lock: self, + repoint, + source: index_url.to_string(), + checksum: cksum.to_string(), + }) + } + + /// Whether this rewrite has repointed `crate_name@version` since the + /// parse it holds. + fn has_repointed(&self, crate_name: &str, version: &str) -> bool { + let Some(Some(model)) = self.model.get() else { + return false; + }; + self.repointed.iter().any(|&package| { + model + .packages + .get(package) + .is_some_and(|p| p.name == crate_name && p.version == version) + }) + } + + /// Whether `range` neither overlaps nor touches a pending splice (two + /// splices that meet at one byte would depend on the order they are + /// applied in). + fn clear_of_pending(&self, range: &Range) -> bool { + self.pending + .iter() + .all(|(held, _)| range.end < held.start || held.end < range.start) + } + + /// Put the pending splices into the text and drop the parse: the next + /// use parses the text as it is now. + fn parse_again(&mut self) { + self.apply_pending(); + self.model = std::cell::OnceCell::new(); + self.repointed.clear(); + } + + fn apply_pending(&mut self) { + if !self.pending.is_empty() { + self.text = splice(&self.text, std::mem::take(&mut self.pending)); + } + } + + /// The lock's text with every committed repoint in it. + pub(crate) fn into_text(mut self) -> String { + self.apply_pending(); + self.text + } +} diff --git a/crates/socket-patch-core/src/formats/cargo/mod.rs b/crates/socket-patch-core/src/formats/cargo/mod.rs index 356e5742a..bb018ad2d 100644 --- a/crates/socket-patch-core/src/formats/cargo/mod.rs +++ b/crates/socket-patch-core/src/formats/cargo/mod.rs @@ -14,10 +14,11 @@ //! crate (the hosted planner's unpinnable-dependents refusal); //! * [`CargoLock::vendored_in_use`] — whether the lock builds a vendored //! `[patch]` copy ([`CopyClaim`]); -//! * [`CargoLock::plan_hosted`] ([`hosted`]) — the hosted planner's lock -//! splice, at the byte spans [`CargoLock::parse`] records, and the +//! * [`CargoLock::plan_hosted_splices`] ([`hosted`]) — the hosted planner's +//! lock splice, at the byte spans [`CargoLock::parse`] records, and the //! [`CargoLock::is_locked`] / [`CargoLock::locked_versions`] probes the -//! hosted rewriter reads with; +//! hosted rewriter reads with, all through the one parse a +//! [`hosted::CargoHostedLock`] holds for a rewrite; //! * the vendored planner (`vendor::cargo_lock`) edits the same document //! with `toml_edit`; //! @@ -434,6 +435,13 @@ pub struct CargoLock { spans: Option, } +#[cfg(test)] +thread_local! { + /// How often this thread has parsed a lock text ([`CargoLock::parse`]), + /// for the tests that pin how often a rewrite does. + pub(crate) static LOCK_PARSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The byte spans of a [`CargoLock`] parsed from text. #[derive(Debug)] pub(crate) struct LockSpans { @@ -461,6 +469,8 @@ impl CargoLock { /// Parse a lock text, keeping every span the hosted splice edits; /// `Err` when it is not TOML (cargo itself refuses to build from it). pub fn parse(text: &str) -> Result { + #[cfg(test)] + LOCK_PARSES.with(|parses| parses.set(parses.get() + 1)); let doc = Document::parse(text)?; let root = doc.as_table(); let mut packages = Vec::new(); diff --git a/crates/socket-patch-core/src/patch/redirect/cargo_lock_equivalence_tests.rs b/crates/socket-patch-core/src/patch/redirect/cargo_lock_equivalence_tests.rs index 5863631df..e9fa46bc2 100644 --- a/crates/socket-patch-core/src/patch/redirect/cargo_lock_equivalence_tests.rs +++ b/crates/socket-patch-core/src/patch/redirect/cargo_lock_equivalence_tests.rs @@ -1,11 +1,11 @@ //! Seeded and hand-written Cargo.lock sweeps for the hosted splice, which //! edits the byte spans of the lock's one parse ([`CargoLock::parse`] → -//! [`CargoLock::plan_hosted`]). Every plan is pinned per case by +//! [`CargoLock::plan_hosted_splices`]). Every plan is pinned per case by //! `tests/equivalence/cargo_lock_*.golden`, blessed while the previous //! line-grammar planner still ran beside it as an oracle (identical bytes //! and edits wherever that grammar could read the lock). -use crate::formats::cargo::hosted::CargoLockPlan; +use crate::formats::cargo::hosted::{splice, CargoHostedLock, CargoLockOutcome, RepointSplices}; use crate::formats::cargo::CargoLock; use crate::golden::Golden; use crate::patch::redirect::FileEdit; @@ -98,27 +98,133 @@ fn synth_lock(rng: &mut Rng, blocks: usize, v1: bool) -> String { } const INDEX: &str = "sparse+https://socket.example/cargo/index/"; +const OTHER_INDEX: &str = "sparse+https://socket.example/cargo/other-index/"; -fn plan_new(lock: &str, name: &str, version: &str, cksum: &str) -> CargoLockPlan { - CargoLock::parse(lock) - .expect("synthesized locks parse") - .plan_hosted(lock, name, version, INDEX, cksum) +/// A lock whose full ids name packages it holds, which [`synth_lock`] +/// almost never does (its references are all at version `0.1.0`). Each +/// package depends on a few others in the spellings cargo writes. Some +/// are at a hosted index already (a re-run), some are twins of the package +/// before them from another source, and now and then a reference or a +/// `[metadata]` line names an id no block has (a lock edited by hand, which +/// a repoint can turn into one that no longer parses). The v1 shape has a +/// `[root]` and keeps its checksums in `[metadata]`. +fn linked_lock(rng: &mut Rng, blocks: usize, v1: bool) -> String { + let sources = [CRATES_IO, INDEX, OTHER_INDEX]; + let mut packages: Vec<(String, String, Option<&str>)> = Vec::new(); + for i in 0..blocks { + let source = match rng.below(20) { + 0..=13 => Some(CRATES_IO), + 14..=15 => Some(INDEX), + 16 => Some(OTHER_INDEX), + _ => None, + }; + let twin = packages + .last() + .filter(|(_, _, of)| *of != source && rng.chance(12)); + let (name, version) = match twin { + Some((name, version, _)) => (name.clone(), version.clone()), + None => (format!("c{i}"), format!("1.{}.0", rng.below(3))), + }; + packages.push((name, version, source)); + } + let full_id = |name: &str, version: &str, source: &str| format!("{name} {version} ({source})"); + let reference = |rng: &mut Rng, at: usize| -> String { + let (name, version, source) = &packages[at]; + if rng.chance(8) { + // No block has this id: another source than the package's. + return full_id(name, version, sources[rng.below(sources.len())]); + } + match source { + Some(source) if v1 || rng.chance(25) => full_id(name, version, source), + _ if rng.chance(30) => format!("{name} {version}"), + _ => name.clone(), + } + }; + let mut out = String::from("# This file is automatically @generated by Cargo.\n"); + if !v1 { + out.push_str("version = 4\n"); + } else if !packages.is_empty() && rng.chance(40) { + out.push_str("[root]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\n"); + for _ in 0..1 + rng.below(3) { + let at = rng.below(packages.len()); + out.push_str(&format!(" \"{}\",\n", reference(rng, at))); + } + out.push_str("]\n"); + } + let mut metadata: Vec = Vec::new(); + for (i, (name, version, source)) in packages.iter().enumerate() { + out.push_str(&format!( + "\n[[package]]\nname = \"{name}\"\nversion = \"{version}\"\n" + )); + if let Some(source) = source { + out.push_str(&format!("source = \"{source}\"\n")); + let sum = format!("{:016x}", rng.next()); + if v1 { + let key = format!("checksum {}", full_id(name, version, source)); + if !metadata + .iter() + .any(|line| line.starts_with(&format!("\"{key}\""))) + { + metadata.push(format!("\"{key}\" = \"{sum}\"")); + } + } else { + out.push_str(&format!("checksum = \"{sum}\"\n")); + } + } + let count = rng.below(4); + if count > 0 && packages.len() > 1 { + out.push_str("dependencies = [\n"); + for _ in 0..count { + let at = (i + 1 + rng.below(packages.len() - 1)) % packages.len(); + out.push_str(&format!(" \"{}\",\n", reference(rng, at))); + } + out.push_str("]\n"); + } + } + if v1 { + // A line for an id no block has, at the index a repoint may name. + for (name, version, source) in &packages { + if *source == Some(CRATES_IO) && rng.chance(6) { + let key = format!("checksum {}", full_id(name, version, INDEX)); + if !metadata + .iter() + .any(|line| line.starts_with(&format!("\"{key}\""))) + { + metadata.push(format!("\"{key}\" = \"stale\"")); + } + } + } + out.push_str("\n[metadata]\n"); + for line in &metadata { + out.push_str(line); + out.push('\n'); + } + } + out } -/// A plan as comparable data. -fn shape(plan: &CargoLockPlan) -> (String, Option, Vec) { - match plan { - CargoLockPlan::Rewritten { content, edits } => { - ("rewritten".into(), Some(content.clone()), edits.clone()) +/// A plan as comparable data: what it is, the text it leaves, the edits +/// it records. +type Shape = (String, Option, Vec); + +/// One package of `lock` planned for `index` on a fresh parse of it. +fn plan_on(lock: &str, name: &str, version: &str, index: &str, cksum: &str) -> Shape { + let Ok(model) = CargoLock::parse(lock) else { + return ("not-found".into(), None, Vec::new()); + }; + match model.plan_hosted_splices(lock, name, version, index, cksum) { + CargoLockOutcome::Rewritten(RepointSplices { splices, edits, .. }) => { + ("rewritten".into(), Some(splice(lock, splices)), edits) } - CargoLockPlan::AlreadyRedirected => ("already".into(), None, Vec::new()), - CargoLockPlan::NotFound => ("not-found".into(), None, Vec::new()), - CargoLockPlan::Ambiguous => ("ambiguous".into(), None, Vec::new()), + CargoLockOutcome::AlreadyRedirected => ("already".into(), None, Vec::new()), + CargoLockOutcome::NotFound => ("not-found".into(), None, Vec::new()), + CargoLockOutcome::Ambiguous => ("ambiguous".into(), None, Vec::new()), } } fn check(g: &mut Golden, lock: &str, name: &str, version: &str, cksum: &str) -> Option { - let new = shape(&plan_new(lock, name, version, cksum)); + assert!(CargoLock::parse(lock).is_ok(), "synthesized locks parse"); + let new = plan_on(lock, name, version, INDEX, cksum); g.next(&(lock, name, version, cksum), &new); new.1 } @@ -170,8 +276,7 @@ fn span_splice_matches_golden_on_random_locks() { /// Hand-written shapes the generator does not produce: multi-source twins /// (one at the target index, and none), a v1 `[root]` table, a v1 block with /// no source, a source ending the text, and blocks with neither line. -#[test] -fn span_splice_matches_golden_on_hand_written_locks() { +fn hand_written_locks() -> Vec { let crates_io = CRATES_IO; let twins_ours = format!( "version = 3\n\n[[package]]\nname = \"t\"\nversion = \"1.0.0\"\nsource = \"{crates_io}\"\nchecksum = \"aa\"\n\n[[package]]\nname = \"t\"\nversion = \"1.0.0\"\nsource = \"{INDEX}\"\nchecksum = \"bb\"\n" @@ -184,19 +289,24 @@ fn span_splice_matches_golden_on_hand_written_locks() { let source_at_eof = format!("[[package]]\nname = \"e\"\nversion = \"1.0.0\"\nsource = \"{crates_io}\""); let bare = "version = 3\n\n[[package]]\nname = \"b\"\nversion = \"1.0.0\"\n\n[[package]]\nname = \"c\"\nversion = \"1.0.0\"\n".to_string(); + vec![ + twins_ours, + twins_neither, + v1_root, + sourceless_v1, + source_at_eof, + bare, + ] +} + +#[test] +fn span_splice_matches_golden_on_hand_written_locks() { let mut g = Golden::new( "cargo_lock_hand_written", "One package of a hand-written Cargo.lock shape, planned for the hosted index.", ); let mut rng = Rng(0xD1B5_4A32_D192_ED03); - for (_what, lock) in [ - ("twins, one ours", twins_ours), - ("twins, neither ours", twins_neither), - ("v1 [root]", v1_root), - ("v1 sourceless", sourceless_v1), - ("source at EOF", source_at_eof), - ("bare blocks", bare), - ] { + for lock in hand_written_locks() { sweep_lock(&mut g, &lock, &mut rng); } g.finish(); @@ -220,3 +330,266 @@ fn span_splice_matches_golden_on_a_large_lock() { } g.finish(); } + +/// One step of a rewrite: a package, the index it is repointed at, the +/// patched checksum, and whether the plan is committed or dropped. +type Step = (String, String, &'static str, String, bool); + +/// Repoint a run of `steps` packages of `lock` twice over: crate by crate, +/// each planned on a fresh parse of the text the last one left (the +/// rewrite as it was), and through one [`CargoHostedLock`]. Every plan, +/// every answer the rewrite's probes read, and the final text must be the +/// same. Returns how often the [`CargoHostedLock`] parsed. +fn repoint_both_ways(lock: &str, steps: &[Step]) -> usize { + let mut text = lock.to_string(); + let mut held = CargoHostedLock::new(lock.to_string()); + for (at, (name, version, index, cksum, commit)) in steps.iter().enumerate() { + let context = || format!("step {at} ({name}@{version} to {index}) of {steps:?}\n{lock}"); + // What the probes read, before the plan: the package's source and + // the source of each package that depends on it. + let probes = |model: Option<&CargoLock>| { + model.map(|model| { + let own: Vec> = model + .packages() + .iter() + .filter(|p| p.name == *name && p.version == *version) + .map(|p| p.source.clone()) + .collect(); + let dependents: Vec<(String, String, Option)> = model + .dependents(name, version) + .map(|p| (p.name.clone(), p.version.clone(), p.source.clone())) + .collect(); + ( + own, + dependents, + model.is_locked(name, version), + model.locked_versions(name), + ) + }) + }; + let fresh = CargoLock::parse(&text).ok(); + // The whole model, then the probes themselves. + assert_eq!( + held.model().map(CargoLock::packages), + fresh.as_ref().map(CargoLock::packages), + "{}", + context() + ); + assert_eq!( + probes(held.model()), + probes(fresh.as_ref()), + "{}", + context() + ); + + let (kind, content, edits) = plan_on(&text, name, version, index, cksum); + let (got, planned) = match held.plan(name, version, index, cksum) { + CargoLockOutcome::Rewritten(planned) => ("rewritten", Some(planned)), + CargoLockOutcome::AlreadyRedirected => ("already", None), + CargoLockOutcome::NotFound => ("not-found", None), + CargoLockOutcome::Ambiguous => ("ambiguous", None), + }; + assert_eq!(got, kind.as_str(), "{}", context()); + let planned_edits = planned.as_ref().map_or(&[][..], |planned| planned.edits()); + assert_eq!(planned_edits, edits.as_slice(), "{}", context()); + if *commit { + if let Some(content) = content { + text = content; + } + if let Some(planned) = planned { + assert_eq!(planned.commit(), edits, "{}", context()); + } + } + } + let parses = held.parses(); + assert_eq!(held.into_text(), text, "{steps:?}\n{lock}"); + parses +} + +/// A run of repoints over `lock`: its packages in a seeded order with +/// repeats, an absent one, two target indexes (a package repointed to one +/// and then the other is a re-pin) and now and then a plan that is dropped. +fn seeded_steps(lock: &str, rng: &mut Rng) -> Vec { + let all = targets(lock); + (0..1 + rng.below(8)) + .map(|_| { + let (name, version) = match all.get(rng.below(all.len() + 1)) { + Some(found) => found.clone(), + None => ("absent-crate".to_string(), "9.9.9".to_string()), + }; + let index = if rng.chance(75) { INDEX } else { OTHER_INDEX }; + let cksum = format!("{:016x}", rng.next()); + (name, version, index, cksum, !rng.chance(10)) + }) + .collect() +} + +/// The rewrite keeps one parse of a lock and its repoints as splices into +/// that text. Its plans, what its probes read and its final text are those +/// of the crate-by-crate rewrite it replaces, for every order and overlap: +/// a package repointed again, a block holding a full id an earlier repoint +/// rewrites, twins, a block that had no source, a lock ending without a +/// newline, a lock a repoint leaves unreadable. +#[test] +fn a_rewrite_on_one_parse_matches_the_crate_by_crate_rewrite() { + let mut rng = Rng(0x6A09_E667_F3BC_C908); + for _ in 0..600 { + let v1 = rng.chance(50); + let blocks = rng.below(12); + let lock = synth_lock(&mut rng, blocks, v1); + let steps = seeded_steps(&lock, &mut rng); + repoint_both_ways(&lock, &steps); + } + // Full ids that name the lock's own packages: the references a repoint + // rewrites in other blocks, in `[root]` and in `[metadata]`. + let mut references = 0; + for _ in 0..1_500 { + let v1 = rng.chance(50); + let blocks = rng.below(10); + let lock = linked_lock(&mut rng, blocks, v1); + let steps = seeded_steps(&lock, &mut rng); + references += steps + .iter() + .filter(|(name, version, ..)| { + lock.contains(&format!(" \"{name} {version} ({CRATES_IO})\"")) + }) + .count(); + repoint_both_ways(&lock, &steps); + } + assert!( + references > 500, + "the sweep repoints packages other blocks name by full id ({references})" + ); + for lock in hand_written_locks() { + for _ in 0..40 { + let steps = seeded_steps(&lock, &mut rng); + repoint_both_ways(&lock, &steps); + } + } +} + +fn step(name: &str, version: &str, index: &'static str, cksum: &str) -> Step { + (name.into(), version.into(), index, cksum.into(), true) +} + +/// A package planned a second time is planned on the lock as its first +/// repoint left it, also when the second plan's splices are nowhere near +/// the first's. Here the first repoint changes the block alone; the second +/// one, read off the bytes as parsed, would see the block at its old index +/// and rewrite only the stray full id. +#[test] +fn a_package_planned_again_is_read_as_its_first_repoint_left_it() { + let lock = format!( + "version = 4\n\n[[package]]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\n \"p\",\n \"p 1.0.0 ({INDEX})\",\n]\n\n[[package]]\nname = \"p\"\nversion = \"1.0.0\"\nsource = \"{OTHER_INDEX}\"\nchecksum = \"aa\"\n" + ); + let steps = [ + step("p", "1.0.0", INDEX, "bb"), + step("p", "1.0.0", OTHER_INDEX, "aa"), + ]; + assert_eq!(repoint_both_ways(&lock, &steps), 2); +} + +/// A repoint can leave a lock that no longer parses: a v1 lock with a +/// stray `[metadata]` line for the id the repoint gives the package (the +/// key becomes a duplicate), or a block whose `checksum` is a table, which +/// the checksum line added to the block collides with. The crates after it +/// are then refused, as they were when every crate parsed the lock, and +/// none is repointed on a lock cargo cannot read. +#[test] +fn a_lock_a_repoint_leaves_unreadable_refuses_the_crates_after_it() { + let stray_metadata = format!( + "[[package]]\nname = \"p\"\nversion = \"1.0.0\"\nsource = \"{CRATES_IO}\"\n\n[[package]]\nname = \"q\"\nversion = \"2.0.0\"\nsource = \"{CRATES_IO}\"\n\n[metadata]\n\"checksum p 1.0.0 ({CRATES_IO})\" = \"aa\"\n\"checksum p 1.0.0 ({INDEX})\" = \"stale\"\n\"checksum q 2.0.0 ({CRATES_IO})\" = \"cc\"\n" + ); + let checksum_table = format!( + "version = 3\n\n[[package]]\nname = \"p\"\nversion = \"1.0.0\"\nsource = \"{CRATES_IO}\"\n\n[package.checksum]\nx = 1\n\n[[package]]\nname = \"q\"\nversion = \"2.0.0\"\nsource = \"{CRATES_IO}\"\nchecksum = \"cc\"\n" + ); + for lock in [stray_metadata, checksum_table] { + let mut held = CargoHostedLock::new(lock.clone()); + let CargoLockOutcome::Rewritten(planned) = held.plan("p", "1.0.0", INDEX, "bb") else { + panic!("the first crate is repointed\n{lock}"); + }; + assert!(!planned.commit().is_empty()); + assert!(held.model().is_none(), "the lock no longer parses\n{lock}"); + assert!( + matches!( + held.plan("q", "2.0.0", INDEX, "dd"), + CargoLockOutcome::NotFound + ), + "{lock}" + ); + repoint_both_ways( + &lock, + &[ + step("p", "1.0.0", INDEX, "bb"), + step("q", "2.0.0", INDEX, "dd"), + ], + ); + } +} + +/// A lock of `count` crates with inline checksums, each depending on the +/// next: the shape cargo has written since 1.41. +fn chain_lock(count: usize) -> String { + let mut lock = String::from("version = 4\n"); + for i in 0..count { + lock.push_str(&format!( + "\n[[package]]\nname = \"crate-{i}\"\nversion = \"1.0.{i}\"\nsource = \"{CRATES_IO}\"\n\ + checksum = \"{i:064x}\"\ndependencies = [\n \"crate-{}\",\n]\n", + (i + 1) % count + )); + } + lock +} + +fn chain_step(i: usize, index: &'static str) -> Step { + ( + format!("crate-{i}"), + format!("1.0.{i}"), + index, + format!("{:064x}", i + 1000), + true, + ) +} + +/// What the one parse is for (#761): however many packages a rewrite +/// repoints, and whatever it finds already repointed or absent on the +/// way, it parses the lock once, where each package used to cost several +/// parses. A lock nothing reads is not parsed at all. +#[test] +fn a_rewrite_parses_the_lock_once() { + let lock = chain_lock(200); + let steps: Vec = (0..200).step_by(7).map(|i| chain_step(i, INDEX)).collect(); + assert_eq!(repoint_both_ways(&lock, &steps), 1); + + // A re-run that adds patches: crates already at their index and + // crates to repoint, in turn, with an absent one among them. + let (kind, redirected, _) = plan_on(&lock, "crate-3", "1.0.3", INDEX, "aa"); + assert_eq!(kind, "rewritten"); + let redirected = redirected.unwrap(); + let mixed = vec![ + chain_step(10, INDEX), + ("crate-3".into(), "1.0.3".into(), INDEX, "aa".into(), true), + chain_step(20, INDEX), + ( + "absent-crate".into(), + "9.9.9".into(), + INDEX, + "bb".into(), + true, + ), + ("crate-3".into(), "1.0.3".into(), INDEX, "aa".into(), true), + chain_step(30, INDEX), + ]; + assert_eq!(repoint_both_ways(&redirected, &mixed), 1); + + // A package planned again reads the bytes its first repoint left: one + // more parse, and no more than that for the packages after it. + let mut again = steps.clone(); + again.insert(3, again[0].clone()); + assert_eq!(repoint_both_ways(&lock, &again), 2); + let mut repinned = steps.clone(); + repinned.insert(3, chain_step(0, OTHER_INDEX)); + assert_eq!(repoint_both_ways(&lock, &repinned), 2); + + assert_eq!(CargoHostedLock::new(lock).parses(), 0); +} diff --git a/crates/socket-patch-core/src/patch/redirect/cargo_rewrite_order_tests.rs b/crates/socket-patch-core/src/patch/redirect/cargo_rewrite_order_tests.rs new file mode 100644 index 000000000..1ff36def5 --- /dev/null +++ b/crates/socket-patch-core/src/patch/redirect/cargo_rewrite_order_tests.rs @@ -0,0 +1,234 @@ +//! Rewrites of several crates in one run where a later crate's refusal +//! depends on what an earlier one did to `Cargo.lock`. The lock is parsed +//! once per rewrite ([`CargoHostedLock`]); these pin that each crate still +//! sees the lock as the crates before it left it, as it did when every +//! crate parsed the lock afresh. +//! +//! [`CargoHostedLock`]: crate::formats::cargo::hosted::CargoHostedLock + +use std::collections::BTreeMap; + +use super::{ + rewrite_cargo, rewrite_registry_redirect, DepOverride, Integrity, RegistryOverride, + RegistryOverrideIdentifiers, RewriteResult, +}; +use crate::formats::cargo::LOCK_PARSES; + +const UUID_A: &str = "9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f"; +const UUID_B: &str = "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; +const UUID_C: &str = "2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"; +const UUID_D: &str = "3c4d5e6f-7a8b-4c9d-8e1f-2a3b4c5d6e7f"; +const CRATES_IO: &str = "registry+https://github.com/rust-lang/crates.io-index"; + +fn socket_index(uuid: &str) -> String { + format!("sparse+https://patch.test/cargo/{uuid}/index/") +} + +fn patch_of(name: &str, version: &str, uuid: &str, index_url: String) -> DepOverride { + DepOverride { + ecosystem: "cargo".into(), + name: name.into(), + namespace: None, + version: version.into(), + token: "tok".into(), + patch_uuid: uuid.into(), + artifact_url: format!("https://patch.test/{name}-{version}.crate"), + registry_override: Some(RegistryOverride { + kind: "cargo-sparse".into(), + index_url, + identifiers: RegistryOverrideIdentifiers { + name: name.into(), + version: version.into(), + cargo_cksum_sha256: Some("e".repeat(64)), + ..Default::default() + }, + }), + integrity: Integrity::default(), + } +} + +fn project(manifest: &str, lock: &str) -> BTreeMap { + let mut files = BTreeMap::new(); + files.insert("Cargo.toml".to_string(), manifest.to_string()); + files.insert("Cargo.lock".to_string(), lock.to_string()); + files +} + +fn codes(result: &RewriteResult) -> Vec<&str> { + result.warnings.iter().map(|w| w.code.as_str()).collect() +} + +/// A crate vendored before any lock existed leaves a block with no +/// `source`, which a hosted pin gives one. A crate that block depends on +/// is then held by a registry package the pin cannot reach, and the +/// refusal says so: the block is read with the source the first repoint +/// gave it, not as the path package it was parsed as. +#[test] +fn a_dependent_repointed_earlier_in_the_run_is_read_with_its_new_source() { + let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\ + [dependencies]\nouter = \"1.0.0\"\ninner = \"1.0.0\"\n"; + let lock = format!( + "# This file is automatically @generated by Cargo.\nversion = 3\n\n\ + [[package]]\nname = \"app\"\nversion = \"0.1.0\"\n\ + dependencies = [\n \"inner\",\n \"outer\",\n]\n\n\ + [[package]]\nname = \"inner\"\nversion = \"1.0.0\"\nsource = \"{CRATES_IO}\"\n\ + checksum = \"{}\"\n\n\ + [[package]]\nname = \"outer\"\nversion = \"1.0.0\"\n\ + dependencies = [\n \"inner\",\n]\n", + "a".repeat(64) + ); + let result = rewrite_registry_redirect( + &project(manifest, &lock), + &[ + patch_of("outer", "1.0.0", UUID_A, socket_index(UUID_A)), + patch_of("inner", "1.0.0", UUID_B, socket_index(UUID_B)), + ], + ); + assert_eq!( + codes(&result), + ["redirect_cargo_transitive_dependents"], + "{:?}", + result.warnings + ); + let detail = &result.warnings[0].detail; + assert!( + detail.contains("outer 1.0.0 (registry)") && !detail.contains("path package"), + "{detail}" + ); + assert_eq!( + result.confirmed_cargo_uuids.iter().collect::>(), + [UUID_A] + ); + let rewritten = &result.files["Cargo.lock"]; + assert!( + rewritten.contains(&format!( + "name = \"outer\"\nversion = \"1.0.0\"\nsource = \"{}\"", + socket_index(UUID_A) + )), + "{rewritten}" + ); + assert!( + rewritten.contains(&format!( + "name = \"inner\"\nversion = \"1.0.0\"\nsource = \"{CRATES_IO}\"" + )), + "{rewritten}" + ); +} + +/// The same crate named by two patches, with index URLs that are not a +/// Socket per-patch index by their shape. The second is refused as an +/// override: it reads the lock entry at the registry the first one put it +/// on, which is no longer crates.io. +#[test] +fn a_second_patch_of_one_crate_reads_the_source_the_first_one_wrote() { + let manifest = "[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n\ + [dependencies]\nserde = \"1.0.190\"\n"; + let lock = format!( + "# This file is automatically @generated by Cargo.\nversion = 3\n\n\ + [[package]]\nname = \"app\"\nversion = \"0.1.0\"\n\ + dependencies = [\n \"serde\",\n]\n\n\ + [[package]]\nname = \"serde\"\nversion = \"1.0.190\"\nsource = \"{CRATES_IO}\"\n\ + checksum = \"{}\"\n", + "a".repeat(64) + ); + let first = "sparse+https://patch.test/cargo/first/".to_string(); + let second = "sparse+https://patch.test/cargo/second/".to_string(); + let result = rewrite_registry_redirect( + &project(manifest, &lock), + &[ + patch_of("serde", "1.0.190", UUID_A, first.clone()), + patch_of("serde", "1.0.190", UUID_B, second.clone()), + ], + ); + assert_eq!( + codes(&result), + ["redirect_cargo_dep_overridden"], + "{:?}", + result.warnings + ); + assert_eq!( + result.confirmed_cargo_uuids.iter().collect::>(), + [UUID_A] + ); + let rewritten = &result.files["Cargo.lock"]; + assert!( + rewritten.contains(&format!("source = \"{first}\"")) && !rewritten.contains(&second), + "{rewritten}" + ); + assert!( + result.files["Cargo.toml"].contains(&format!("socket-patch-{UUID_A}")) + && !result.files["Cargo.toml"].contains(UUID_B), + "{}", + result.files["Cargo.toml"] + ); +} + +/// What the one parse is for (#761), through the Cargo rewrite itself: the +/// lock is parsed once however many crates are repointed, and not at all +/// by a rewrite that refuses before it reads the lock. The Cargo leg is +/// called directly: the whole rewrite runs each ecosystem on a thread of +/// its own, and the count is this thread's. +#[test] +fn the_rewrite_parses_the_lock_once() { + let crates = [ + ("alpha", UUID_A), + ("beta", UUID_B), + ("delta", UUID_C), + ("gamma", UUID_D), + ]; + let mut manifest = + String::from("[package]\nname = \"app\"\nversion = \"0.1.0\"\n\n[dependencies]\n"); + let mut lock = String::from( + "# This file is automatically @generated by Cargo.\nversion = 3\n\n\ + [[package]]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\n", + ); + for (name, _) in crates { + manifest.push_str(&format!("{name} = \"1.0.0\"\n")); + lock.push_str(&format!(" \"{name}\",\n")); + } + lock.push_str("]\n"); + for (name, _) in crates { + lock.push_str(&format!( + "\n[[package]]\nname = \"{name}\"\nversion = \"1.0.0\"\nsource = \"{CRATES_IO}\"\n\ + checksum = \"{}\"\n", + "a".repeat(64) + )); + } + let files = project(&manifest, &lock); + let patches: Vec = crates + .iter() + .map(|(name, uuid)| patch_of(name, "1.0.0", uuid, socket_index(uuid))) + .collect(); + + let before = LOCK_PARSES.get(); + let mut result = RewriteResult::default(); + rewrite_cargo(&files, &patches, &mut result); + let parses = LOCK_PARSES.get() - before; + assert_eq!(codes(&result), [""; 0], "{:?}", result.warnings); + assert_eq!(result.confirmed_cargo_uuids.len(), crates.len()); + for (_, uuid) in crates { + assert!( + result.files["Cargo.lock"].contains(&socket_index(uuid)), + "{}", + result.files["Cargo.lock"] + ); + } + assert_eq!(parses, 1, "one parse for {} repoints", crates.len()); + + // No checksum for the patched crate: refused before the lock is read. + let mut unusable = patch_of("alpha", "1.0.0", UUID_A, socket_index(UUID_A)); + if let Some(registry) = unusable.registry_override.as_mut() { + registry.identifiers.cargo_cksum_sha256 = None; + } + let before = LOCK_PARSES.get(); + let mut result = RewriteResult::default(); + rewrite_cargo(&files, &[unusable], &mut result); + let parses = LOCK_PARSES.get() - before; + assert_eq!( + codes(&result), + ["redirect_cargo_missing_cksum"], + "{:?}", + result.warnings + ); + assert_eq!(parses, 0, "a rewrite that never reads the lock"); +} diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index 3a4963e48..ebcc01a76 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -38,6 +38,8 @@ pub use bun_binary::{preflight_bun_binary, rewrite_bun_binary}; #[cfg(test)] mod cargo_lock_equivalence_tests; #[cfg(test)] +mod cargo_rewrite_order_tests; +#[cfg(test)] mod composer_equivalence_tests; pub(crate) mod generation; #[cfg(test)] @@ -58,9 +60,9 @@ mod pipenv_pylock_tests; pub mod presence; // The pnpm hosted planner lives with the format's model. use crate::crawlers::maven_selection::{MavenSelection, Verdict}; -use crate::formats::cargo::hosted::CargoLockPlan; #[cfg(test)] use crate::formats::cargo::hosted::CARGO_LOCK_REFERENCE_KIND; +use crate::formats::cargo::hosted::{CargoHostedLock, CargoLockRepoint, PlannedRepoint}; use crate::formats::cargo::source_replacement::{crates_io_source, ConfigLayer, CratesIoSource}; use crate::formats::cargo::{is_crates_io_patch_table, is_crates_io_source, CargoLock}; use crate::formats::composer::hosted::rewrite_composer_lock; @@ -1945,10 +1947,11 @@ fn rewrite_cargo_with( let edits_before = result.edits.len(); let mut changed_manifests: std::collections::BTreeSet = std::collections::BTreeSet::new(); + // Parsed once, by the first probe or plan below that reads it. let mut cargo_lock = files .get("Cargo.lock") .cloned() - .map(|t| to_lf("Cargo.lock", t)); + .map(|t| CargoHostedLock::new(to_lf("Cargo.lock", t))); // Cargo reads the LEGACY extensionless `.cargo/config` in preference to // `config.toml` when both exist (it warns about the duplicate), so a // managed `[registries.…]` block written to `config.toml` there is @@ -2147,8 +2150,8 @@ fn rewrite_cargo_with( }); continue; } - let other_versions = - cargo_lock_other_versions(cargo_lock.as_deref(), &dep.name, &dep.version); + let lock_model = cargo_lock.as_ref().and_then(CargoHostedLock::model); + let other_versions = cargo_lock_other_versions(lock_model, &dep.name, &dep.version); let (toml_plans, excluded) = match plan_cargo_tomls(&manifests, &dep.name, &dep.version, &other_versions, ®) { Ok(planned) => planned, @@ -2174,7 +2177,7 @@ fn rewrite_cargo_with( &dep.name, &dep.version, &excluded, - cargo_lock.as_deref(), + lock_model, ), }); continue; @@ -2186,7 +2189,7 @@ fn rewrite_cargo_with( &dep.name, &dep.version, manifests.len(), - cargo_lock.as_deref(), + lock_model, ), }); continue; @@ -2213,14 +2216,14 @@ fn rewrite_cargo_with( // package whose manifest was not planned (outside the project, behind // a symlink) — keeps resolving it from crates.io, so the repointed // lock is unsatisfiable and that consumer compiles the unpatched copy. - if let Some(lock_text) = cargo_lock.as_deref() { + if let Some(lock) = cargo_lock.as_ref() { let pinned_packages: std::collections::BTreeSet<(&str, &str)> = toml_plans .iter() .filter_map(|(i, _)| manifest_packages[*i].as_ref()) .map(|(name, version)| (name.as_str(), version.as_str())) .collect(); let blocking = - cargo_unpinnable_dependents(lock_text, &dep.name, &dep.version, &pinned_packages); + cargo_unpinnable_dependents(lock, &dep.name, &dep.version, &pinned_packages); if !blocking.is_empty() { result.warnings.push(RewriteWarning { code: "redirect_cargo_transitive_dependents".into(), @@ -2257,17 +2260,16 @@ fn rewrite_cargo_with( // one declared dependency (the dependents gate above): the manifest // pin alone then forces the next resolution through the managed // registry, which serves the patched checksum. - enum LockCommit { - Write(String, Vec), + enum LockCommit<'a> { + Write(PlannedRepoint<'a>), InPlace, Absent, } - let lock_commit = if let Some(lock_text) = cargo_lock.as_ref() { + let lock_commit = if let Some(lock) = cargo_lock.as_mut() { // A lock that does not parse never reaches here: the dependents // check above refuses it. - let parsed = CargoLock::parse(lock_text).ok(); - let overridden = parsed.as_ref().and_then(|lock| { - cargo_lock_override_source(lock, &dep.name, &dep.version, || { + let overridden = lock.model().and_then(|model| { + cargo_lock_override_source(model, &dep.name, &dep.version, || { cargo_patch_override_table(&manifests, files, &dep.name) }) }); @@ -2277,13 +2279,10 @@ fn rewrite_cargo_with( .push(cargo_overridden_warning(&dep.name, &dep.version, &how)); continue; } - let plan = parsed.map_or(CargoLockPlan::NotFound, |lock| { - lock.plan_hosted(lock_text, &dep.name, &dep.version, index_url, &cksum) - }); - match plan { - CargoLockPlan::Rewritten { content, edits } => LockCommit::Write(content, edits), - CargoLockPlan::AlreadyRedirected => LockCommit::InPlace, - CargoLockPlan::NotFound => { + match lock.plan(&dep.name, &dep.version, index_url, &cksum) { + CargoLockRepoint::Rewritten(planned) => LockCommit::Write(planned), + CargoLockRepoint::AlreadyRedirected => LockCommit::InPlace, + CargoLockRepoint::NotFound => { result.warnings.push(RewriteWarning { code: "redirect_cargo_lock_pkg_not_found".into(), detail: format!( @@ -2294,7 +2293,7 @@ fn rewrite_cargo_with( }); continue; } - CargoLockPlan::Ambiguous => { + CargoLockRepoint::Ambiguous => { result.warnings.push(RewriteWarning { code: "redirect_cargo_lock_pkg_ambiguous".into(), detail: format!( @@ -2331,9 +2330,9 @@ fn rewrite_cargo_with( } } match lock_commit { - LockCommit::Write(content, edits) => { - cargo_lock = Some(content); - result.edits.extend(edits); + LockCommit::Write(planned) => { + // The repoint's edits come out as it is made. + result.edits.extend(planned.commit()); lock_changed = true; } LockCommit::InPlace | LockCommit::Absent => {} @@ -2341,6 +2340,8 @@ fn rewrite_cargo_with( result.confirmed_cargo_uuids.insert(dep.patch_uuid.clone()); } + let cargo_lock: Option = cargo_lock.map(CargoHostedLock::into_text); + // A re-pin to a superseding patch moved every declaration off the old // generation's registry: its `[registries.socket-patch-]` block is // now referenced by nothing, so it goes with the re-pin (#864) — left in @@ -2450,7 +2451,7 @@ fn cargo_not_declared_detail( crate_name: &str, version: &str, manifests: usize, - lock: Option<&str>, + lock: Option<&CargoLock>, ) -> String { let scope = if manifests > 1 { format!("any of the {manifests} workspace manifests") @@ -2480,7 +2481,7 @@ fn cargo_requirement_excludes_detail( crate_name: &str, version: &str, excluded: &[(String, String)], - lock: Option<&str>, + lock: Option<&CargoLock>, ) -> String { let declared = excluded .iter() @@ -2674,12 +2675,12 @@ fn cargo_patch_override_table( /// `"name version (source)"` id — so a v1 lock and a twin's full id are /// covered alike. A lock that does not parse yields one entry saying so. fn cargo_unpinnable_dependents( - lock: &str, + lock: &CargoHostedLock, crate_name: &str, version: &str, pinned_packages: &std::collections::BTreeSet<(&str, &str)>, ) -> Vec { - let Ok(lock) = CargoLock::parse(lock) else { + let Some(lock) = lock.model() else { return vec!["Cargo.lock (it does not parse as TOML)".to_string()]; }; let mut out = Vec::new(); @@ -3717,19 +3718,20 @@ enum CargoWorkspaceEntry { /// Whether a Cargo.lock (when there is one, and it parses) resolves /// `crate_name`@`version`. -fn cargo_lock_holds(lock: Option<&str>, crate_name: &str, version: &str) -> bool { - lock.and_then(|lock| CargoLock::parse(lock).ok()) - .is_some_and(|lock| lock.is_locked(crate_name, version)) +fn cargo_lock_holds(lock: Option<&CargoLock>, crate_name: &str, version: &str) -> bool { + lock.is_some_and(|lock| lock.is_locked(crate_name, version)) } -/// Every version of `crate_name` a Cargo.lock holds other than `version`. -fn cargo_lock_other_versions(lock: Option<&str>, crate_name: &str, version: &str) -> Vec { +/// Every version of `crate_name` a Cargo.lock (when there is one, and it +/// parses) holds other than `version`. +fn cargo_lock_other_versions( + lock: Option<&CargoLock>, + crate_name: &str, + version: &str, +) -> Vec { let Some(lock) = lock else { return Vec::new(); }; - let Ok(lock) = CargoLock::parse(lock) else { - return Vec::new(); - }; let mut versions = lock.locked_versions(crate_name); versions.retain(|v| v != version); versions