diff --git a/CLAUDE.md b/CLAUDE.md index 77385f62..0c47796b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -241,7 +241,10 @@ transport-adjacent. The rest, imperatively: - **A stopped merge/pick/rebase lists the paths it wrote as plaintext in `.sc/CONFLICT_PLAINTEXT`.** Protected conflict text never enters the CAS, so no tree records it; completion treats a listed path absent from disk as deleted, - and abort removes listed paths the restored tree does not track as plain files. + and abort removes listed paths the restored tree does not track as plain files. The `.theirs` + sidecars it wrote are listed apart in `.sc/CONFLICT_SIDECARS`; abort, `rebase + --continue` and `sc resolve` remove only those, never a `.theirs` file the stop + did not write. - **Every ref-moving or commit-creating op (including all secret/protect policy ops) is guarded against an in-progress merge/pick/rebase** — finish or abort the in-progress op first. diff --git a/ROADMAP.md b/ROADMAP.md index 6589dfb0..318fc337 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -720,12 +720,17 @@ scale-&-reach horizon): limitation across different Git repos). - **Richer trust models** beyond trusted-key lists (delegation, expiry) — P22 ships the key-list model. -- **Sidecar-cleanup footgun in `rebase_continue` — half fixed (P37c).** - `remove_conflict_sidecars` now skips paths the completion's parent tree - tracks, but it still has no non-text-kind gate: a text conflict writes no - `.theirs` sidecar, so an untracked user file named `foo.txt.theirs` is - still deleted when the stop's conflict path is `foo.txt`. Pass the conflict - kind (or the written sidecar list) to the sweep to close it. +- **Sidecar-cleanup footgun in `rebase_continue` — fixed.** A stop records the + `.theirs` sidecars it actually wrote in `.sc/CONFLICT_SIDECARS`; merge/pick/ + rebase abort, `rebase --continue` and `sc resolve` unlink only those (and + never a path the restored tree tracks), so an untracked user `foo.txt.theirs` + survives whatever the conflict kind. +- **Completion commits a leftover `.theirs` sidecar.** A binary conflict's + `.theirs` is working-tree scratch, but if the user resolves by editing + `` (not `sc resolve`) and leaves the sidecar, the completing `sc commit` + or `rebase --continue` snapshots it as a tracked file (reproduced on main with + a merge). Exclude recorded sidecars (`.sc/CONFLICT_SIDECARS`) that no input + root tracks from the completion snapshot. - **In-progress guard for the RECEIVING repo on push.** `LocalTransport::update_ref` moves a branch tip with only a CAS/ff gate and no in-progress check on the receiving side — a push into a repo diff --git a/crates/repo/src/conflict_plaintext.rs b/crates/repo/src/conflict_plaintext.rs index de052a70..bdc6b2c4 100644 --- a/crates/repo/src/conflict_plaintext.rs +++ b/crates/repo/src/conflict_plaintext.rs @@ -48,15 +48,63 @@ pub(crate) fn read(layout: &Layout) -> Result> { } } -/// Drop the record. +/// Drop both records. pub(crate) fn clear(layout: &Layout) -> Result<()> { - match std::fs::remove_file(path(layout)) { + remove_if_present(&path(layout))?; + remove_if_present(&sidecar_path(layout)) +} + +fn remove_if_present(p: &std::path::Path) -> Result<()> { + match std::fs::remove_file(p) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(e.into()), } } +fn sidecar_path(layout: &Layout) -> std::path::PathBuf { + layout.dot_sc.join("CONFLICT_SIDECARS") +} + +/// Record the `.theirs` sidecars a stop wrote, by full path. They are +/// kept apart from the plaintext list because completion counts a plaintext +/// path as tracked, and a sidecar must never be committed. An empty list +/// removes the record. +pub(crate) fn write_sidecars(layout: &Layout, paths: &[String]) -> Result<()> { + if paths.is_empty() { + return remove_if_present(&sidecar_path(layout)); + } + let tmp = layout.dot_sc.join("CONFLICT_SIDECARS.tmp"); + std::fs::write(&tmp, paths.join("\0"))?; + std::fs::rename(&tmp, sidecar_path(layout))?; + Ok(()) +} + +/// Drop one sidecar from the record once it has been dealt with, so a file +/// the user later creates at that path is not mistaken for ours. +pub(crate) fn retire_sidecar(layout: &Layout, sidecar: &str) -> Result<()> { + let mut paths = read_sidecars(layout)?; + if paths.remove(sidecar) { + write_sidecars(layout, &paths.into_iter().collect::>())?; + } + Ok(()) +} + +/// The recorded sidecar paths, empty when there is no record. Only the +/// sidecars a stop actually wrote are listed: a `.theirs` file beside a +/// conflict that wrote none is the user's own. +pub(crate) fn read_sidecars(layout: &Layout) -> Result> { + match std::fs::read_to_string(sidecar_path(layout)) { + Ok(text) => Ok(text + .split('\0') + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()), + Err(e) => Err(e.into()), + } +} + #[cfg(test)] mod tests { use super::*; @@ -83,8 +131,32 @@ mod tests { write(&layout, &[]).unwrap(); assert!(read(&layout).unwrap().is_empty(), "an empty list clears"); write(&layout, &["x".into()]).unwrap(); + write_sidecars(&layout, &["x.theirs".into()]).unwrap(); + assert_eq!( + read_sidecars(&layout) + .unwrap() + .into_iter() + .collect::>(), + vec!["x.theirs"] + ); + write_sidecars(&layout, &["x.theirs".into(), "y.theirs".into()]).unwrap(); + retire_sidecar(&layout, "x.theirs").unwrap(); + assert_eq!( + read_sidecars(&layout) + .unwrap() + .into_iter() + .collect::>(), + vec!["y.theirs"] + ); + retire_sidecar(&layout, "y.theirs").unwrap(); + assert!( + read_sidecars(&layout).unwrap().is_empty(), + "last one removes the file" + ); + write_sidecars(&layout, &["x.theirs".into()]).unwrap(); clear(&layout).unwrap(); assert!(read(&layout).unwrap().is_empty()); + assert!(read_sidecars(&layout).unwrap().is_empty()); std::fs::remove_dir_all(&root).unwrap(); } } diff --git a/crates/repo/src/conflicts.rs b/crates/repo/src/conflicts.rs index 5b807d01..7f0cf705 100644 --- a/crates/repo/src/conflicts.rs +++ b/crates/repo/src/conflicts.rs @@ -292,32 +292,32 @@ impl Repo { }, } - // Drop the `.theirs` sidecar this system may have written — the only - // sidecar extension ever written (`.base` and `.ours` are never - // produced, so removing them was both dead code and a footgun: a - // repo can legitimately track a real file named - // `foo.txt.base`/`foo.txt.ours`, and blind-unlinking it would - // silently destroy user data). `.theirs` is written only for - // BINARY/PROTECTED-with-binary-content conflicts (merge.rs writes - // `{path}.theirs` in the binary-conflict arm) — a TEXT conflict - // never writes one, so a `.theirs`-named file sitting untracked next - // to a text conflict is not this system's scratch, it's the user's; - // removing it there would silently and unrecoverably delete - // untracked data. So only consider removal when the conflict kind is - // NOT Text (`!= Text`, not `== Binary`: a protected binary conflict - // still writes a plaintext `.theirs` sidecar and classifies as - // Protected, so it must still be cleaned up). And even then, only - // remove it when it is NOT a tracked path — a genuine sidecar is - // untracked scratch by construction, so a tracked `{path}.theirs` - // must be a user's real file and is left alone. - if kind != ConflictKind::Text { - let theirs_sidecar_path = format!("{path}.theirs"); - if !self.tracked_paths()?.contains(&theirs_sidecar_path) { - let sidecar = safe_join(&self.layout.root, &theirs_sidecar_path)?; - match std::fs::remove_file(&sidecar) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(e) => return Err(e.into()), + // Drop the `.theirs` sidecar the stop recorded writing for this path. + // Only a recorded sidecar is ours: the kind of conflict does not say + // whether one was written (a protected UTF-8 conflict and a binary + // delete/modify write none), and a `.theirs` file the stop did not + // write is the user's, as is a tracked `{path}.theirs` (a repo can + // legitimately track `foo.txt.theirs`, `.base` or `.ours`). + let theirs_sidecar_path = format!("{path}.theirs"); + if crate::conflict_plaintext::read_sidecars(&self.layout)?.contains(&theirs_sidecar_path) + && !self.tracked_paths()?.contains(&theirs_sidecar_path) + { + let sidecar = safe_join(&self.layout.root, &theirs_sidecar_path)?; + // Retire first: a crash after the unlink must not leave a record + // that names a path the user may recreate. A failed unlink puts + // the entry back. + crate::conflict_plaintext::retire_sidecar(&self.layout, &theirs_sidecar_path)?; + match std::fs::remove_file(&sidecar) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => { + let mut paths = crate::conflict_plaintext::read_sidecars(&self.layout)?; + paths.insert(theirs_sidecar_path); + let _ = crate::conflict_plaintext::write_sidecars( + &self.layout, + &paths.into_iter().collect::>(), + ); + return Err(e.into()); } } } diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index 53438b0d..6d236d1f 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -660,10 +660,7 @@ impl Repo { if let Some(root) = sidecar_roots.first() { self.remove_conflict_plaintext(*root)?; } - self.remove_conflict_sidecars( - &crate::pick_state::read_conflicts(&self.layout)?, - &sidecar_roots, - )?; + self.remove_conflict_sidecars(&sidecar_roots)?; crate::pick_state::clear(&self.layout)?; Ok(skipped) } @@ -1219,10 +1216,7 @@ impl Repo { // user's own): see `remove_conflict_sidecars`. // Not a file the completion's parent tracks (that one is the // user's own): see `remove_conflict_sidecars`. - self.remove_conflict_sidecars( - &crate::rebase_state::read_conflicts(&self.layout)?, - &[self.snapshot(&st.acc_tip)?.root], - )?; + self.remove_conflict_sidecars(&[self.snapshot(&st.acc_tip)?.root])?; // Advance state BEFORE attempting the fold, so an error from the // fold below (on a later commit) leaves a retryable, idempotent // `--continue` rather than losing resumability. `rebase_abort` @@ -1308,10 +1302,7 @@ impl Repo { )? }; self.remove_conflict_plaintext(snap.root)?; - self.remove_conflict_sidecars( - &crate::rebase_state::read_conflicts(&self.layout)?, - &[snap.root], - )?; + self.remove_conflict_sidecars(&[snap.root])?; crate::rebase_state::clear(&self.layout)?; Ok(skipped) } @@ -2905,6 +2896,283 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// Remove a test repository and assert it is gone. + fn remove_root(root: &std::path::Path) { + std::fs::remove_dir_all(root).unwrap(); + assert!(!root.exists(), "test repository must leave no residue"); + } + + /// Two branches that conflict as text on `x.txt`, `main` checked out, with + /// an untracked user file `x.txt.theirs` beside it. A text conflict writes + /// no sidecar, so no sweep may touch that file. + fn text_conflict_with_user_theirs_file(name: &str) -> (std::path::PathBuf, Repo) { + let root = tmp_root(name); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("x.txt"), b"a\nb\nc\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("x.txt"), b"a\nMAIN\nc\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("x.txt"), b"a\nWORK\nc\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + std::fs::write(root.join("x.txt.theirs"), b"mine\n").unwrap(); + (root, repo) + } + + fn assert_user_theirs_file_survives(root: &std::path::Path) { + assert_eq!( + std::fs::read(root.join("x.txt.theirs")).unwrap(), + b"mine\n", + "an untracked x.txt.theirs beside a text conflict is the user's" + ); + } + + /// Binary delete/modify writes no sidecar: `ours` deletes, `work` edits. + #[test] + fn abort_keeps_a_user_theirs_file_beside_a_binary_delete_modify_conflict() { + let root = tmp_root("sweep-bin-delmod"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + std::fs::write(root.join("keep.txt"), b"k\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::remove_file(root.join("bin.dat")).unwrap(); + repo.commit("me", "main deletes").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeWORK\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch("main").unwrap(); + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.merge_abort().unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n" + ); + drop(repo); + remove_root(&root); + } + + /// A protected UTF-8 conflict writes markers, not a sidecar. + #[test] + fn abort_and_resolve_keep_a_user_theirs_file_beside_a_protected_text_conflict() { + let root = tmp_root("sweep-protected-text"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"l1\nl2\nl3\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("secret/a.txt"), b"MAIN\nl2\nl3\n").unwrap(); + repo.commit("me", "main edits").unwrap(); + repo.switch_with_identity("work", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"WORK\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("secret/a.txt.theirs"), b"mine\n").unwrap(); + let mine = || std::fs::read(root.join("secret/a.txt.theirs")).unwrap(); + + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!(matches!(err, Error::PickConflicts(1)), "got {err:?}"); + repo.resolve_path("secret/a.txt", crate::ResolveSide::Ours, Some(&alice_sk)) + .unwrap(); + assert_eq!(mine(), b"mine\n", "resolve must keep the user's file"); + repo.cherry_pick_abort().unwrap(); + assert_eq!(mine(), b"mine\n", "abort must keep the user's file"); + drop(repo); + remove_root(&root); + } + + /// The control: a binary conflict's own sidecar is still cleaned up. + #[test] + fn abort_still_removes_the_sidecar_a_binary_conflict_wrote() { + let root = tmp_root("sweep-bin-own"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + assert!(root.join("bin.dat.theirs").exists()); + repo.merge_abort().unwrap(); + assert!(!root.join("bin.dat.theirs").exists()); + drop(repo); + remove_root(&root); + } + + /// `sc resolve` removes the sidecar it recorded; a file the user later + /// creates at that path must survive a later abort. + #[test] + fn abort_keeps_a_user_file_created_at_a_sidecar_path_after_resolve() { + let root = tmp_root("sweep-after-resolve"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.resolve_path("bin.dat", crate::ResolveSide::Ours, None) + .unwrap(); + assert!(!root.join("bin.dat.theirs").exists()); + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + repo.merge_abort().unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n" + ); + drop(repo); + remove_root(&root); + } + + /// A sweep retires the record: a retried `--continue` (or any second + /// sweep) must not remove a file the user creates at that path meanwhile. + #[test] + fn a_swept_sidecar_is_retired_from_the_record() { + let root = tmp_root("sweep-retired"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + let ours = repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + let ours_root = repo.snapshot(&ours).unwrap().root; + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert!( + !root.join("bin.dat.theirs").exists(), + "first sweep removes it" + ); + + std::fs::write(root.join("bin.dat.theirs"), b"mine\n").unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"mine\n", + "second sweep must not touch a file made after the first" + ); + drop(repo); + remove_root(&root); + } + + /// A sweep that cannot remove a sidecar fails with the record intact, so a + /// retry can finish the job. + #[test] + fn a_failed_sidecar_removal_keeps_the_record_for_a_retry() { + let root = tmp_root("sweep-remove-fails"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfebase\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeOURS\n").unwrap(); + let ours = repo.commit("me", "main").unwrap(); + repo.switch("work").unwrap(); + std::fs::write(root.join("bin.dat"), b"\xff\xfeTHEIRS\n").unwrap(); + repo.commit("me", "work").unwrap(); + repo.switch("main").unwrap(); + repo.merge("work", "me").unwrap_err(); + let ours_root = repo.snapshot(&ours).unwrap().root; + // Replace the sidecar with a directory: `remove_file` cannot unlink it. + std::fs::remove_file(root.join("bin.dat.theirs")).unwrap(); + std::fs::create_dir(root.join("bin.dat.theirs")).unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap_err(); + assert!( + crate::conflict_plaintext::read_sidecars(&repo.layout) + .unwrap() + .contains("bin.dat.theirs"), + "the record survives a failed removal" + ); + std::fs::remove_dir(root.join("bin.dat.theirs")).unwrap(); + std::fs::write(root.join("bin.dat.theirs"), b"x\n").unwrap(); + repo.remove_conflict_sidecars(&[ours_root]).unwrap(); + assert!( + !root.join("bin.dat.theirs").exists(), + "the retry finishes it" + ); + drop(repo); + remove_root(&root); + } + + #[test] + fn merge_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { + let (root, repo) = text_conflict_with_user_theirs_file("sweep-merge-abort"); + assert!(matches!( + repo.merge("work", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + repo.merge_abort().unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + remove_root(&root); + } + + #[test] + fn cherry_pick_abort_keeps_a_user_theirs_file_beside_a_text_conflict() { + let (root, repo) = text_conflict_with_user_theirs_file("sweep-pick-abort"); + assert!(matches!( + repo.cherry_pick("work", "me", None, None).unwrap_err(), + Error::PickConflicts(_) + )); + assert!(repo.pick_in_progress()); + repo.cherry_pick_abort().unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + remove_root(&root); + } + + #[test] + fn rebase_abort_and_continue_keep_a_user_theirs_file_beside_a_text_conflict() { + // work is rebased onto main: x.txt conflicts as text. + let (root, repo) = text_conflict_with_user_theirs_file("sweep-rebase"); + repo.switch("work").unwrap(); + assert!(matches!( + repo.rebase("main", "me", None).unwrap(), + RebaseResult::Stopped { .. } + )); + repo.rebase_abort().unwrap(); + assert_user_theirs_file_survives(&root); + + assert!(matches!( + repo.rebase("main", "me", None).unwrap(), + RebaseResult::Stopped { .. } + )); + std::fs::write(root.join("x.txt"), b"a\nresolved\nc\n").unwrap(); + repo.rebase_continue("me", None).unwrap(); + assert_user_theirs_file_survives(&root); + drop(repo); + remove_root(&root); + } + /// A file where a parent directory of a plaintext path must be fails the /// write halfway; the stop refuses before writing anything instead. #[test] diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index f9169047..d76bdcd8 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1877,6 +1877,10 @@ impl Repo { .map(|(p, ..)| p.clone()) .collect::>(), )?; + crate::conflict_plaintext::write_sidecars( + &self.layout, + &sidecars.iter().map(|(r, _)| r.clone()).collect::>(), + )?; for (path, bytes, _mode, _recipients) in to_encrypt { let full = worktree::safe_join(&self.layout.root, path)?; if let Some(parent) = full.parent() { @@ -1927,27 +1931,47 @@ impl Repo { Ok(()) } - /// Remove the `.theirs` sidecars a stopped merge, pick or rebase - /// wrote for `paths`, except a file any of `roots` tracks: that one is the - /// user's own and was just restored. A failed lookup counts as tracked: a - /// stray sidecar is harmless, deleting a tracked file is not. Call it after - /// the restore, so a restore that fails leaves the sidecars to retry. - pub(crate) fn remove_conflict_sidecars( - &self, - paths: &[String], - roots: &[ObjectId], - ) -> Result<()> { + /// Remove the `.theirs` sidecars the stop recorded writing + /// (`conflict_plaintext::read_sidecars`), except a file any of `roots` + /// tracks: that one is the user's own and was just restored. A `.theirs` + /// file the stop did not write is the user's, whatever kind of conflict + /// sits beside it. A failed lookup counts as tracked: a stray sidecar is + /// harmless, deleting a tracked file is not. Call it after the restore, so + /// a restore that fails leaves the sidecars to retry. The record is retired + /// once swept. + pub(crate) fn remove_conflict_sidecars(&self, roots: &[ObjectId]) -> Result<()> { + let sidecars = crate::conflict_plaintext::read_sidecars(&self.layout)?; + if sidecars.is_empty() { + return Ok(()); + } + // Retire the whole record before unlinking anything, in one write: a + // crash then leaves harmless residue, never a record naming a path the + // user may recreate before the retry. A removal that fails puts the + // failed and unprocessed paths back so the retry can finish the job. + crate::conflict_plaintext::write_sidecars(&self.layout, &[])?; let partial = self.promisor()?.is_some(); let store_arc = self.vfs.store(); let mut store = store_arc.lock().unwrap(); - for path in paths { - let sidecar = format!("{path}.theirs"); + let sidecars: Vec = sidecars.into_iter().collect(); + for (i, sidecar) in sidecars.iter().enumerate() { let tracked = roots.iter().any(|root| { - worktree::tree_entry_at(&mut store, *root, &sidecar, partial) + worktree::tree_entry_at(&mut store, *root, sidecar, partial) .map_or(true, |e| e.is_some()) }); - if !tracked { - let _ = std::fs::remove_file(self.layout.root.join(sidecar)); + if tracked { + continue; + } + let removed = worktree::safe_join(&self.layout.root, sidecar).and_then(|full| { + match std::fs::remove_file(full) { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } + }); + if let Err(e) = removed { + // Best effort: the removal error is the one worth reporting. + let _ = crate::conflict_plaintext::write_sidecars(&self.layout, &sidecars[i..]); + return Err(e); } } Ok(()) @@ -2007,10 +2031,7 @@ impl Repo { if let Some(root) = sidecar_roots.first() { self.remove_conflict_plaintext(*root)?; } - self.remove_conflict_sidecars( - &crate::merge_state::read_conflicts(&self.layout)?, - &sidecar_roots, - )?; + self.remove_conflict_sidecars(&sidecar_roots)?; crate::merge_state::clear(&self.layout)?; Ok(skipped) }