diff --git a/crates/repo/src/replay.rs b/crates/repo/src/replay.rs index b92f4c8a..53438b0d 100644 --- a/crates/repo/src/replay.rs +++ b/crates/repo/src/replay.rs @@ -2779,6 +2779,175 @@ mod tests { std::fs::remove_dir_all(&root).ok(); } + /// ADR-0049 q21: the conflict stop refuses, before any write, when the + /// plaintext it would write lands on an untracked file the user kept (the + /// "stop tracking, keep it ignored" move). Nothing is lost, and the pick + /// can be retried once the file is moved. + #[test] + fn a_conflict_stop_refuses_to_overwrite_an_untracked_local_copy() { + let root = tmp_root("cp-prot-untracked"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + 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::remove_file(root.join("secret/a.txt")).unwrap(); + std::fs::write(root.join(".scignore"), b"secret/\n").unwrap(); + repo.commit("me", "main deletes and ignores").unwrap(); + repo.switch("work").unwrap(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"EDITED\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + // The user's own ignored copy of the file main stopped tracking. + std::fs::create_dir_all(root.join("secret")).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"MY LOCAL COPY\n").unwrap(); + let before = repo.head_tip().unwrap(); + + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("overwrite an untracked")), + "got {err:?}" + ); + assert!(!repo.pick_in_progress()); + assert_eq!(repo.head_tip().unwrap(), before); + assert_eq!( + std::fs::read(root.join("secret/a.txt")).unwrap(), + b"MY LOCAL COPY\n", + "the local copy is untouched" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// A full clone with a sparse view: the tree tracks a protected path the + /// view never materialized, and the user keeps an ignored local copy there. + /// An in-view conflict together with a clean protected merge of that path + /// would write plaintext over it, so the stop refuses. + #[test] + fn a_conflict_stop_does_not_treat_an_out_of_view_path_as_materialized() { + let root = tmp_root("mg-sparse-untracked"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + repo.protect("vault/", &[alice_pk], None).unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join("vault")).unwrap(); + std::fs::write(root.join("src/a.txt"), b"l1\nl2\nl3\n").unwrap(); + std::fs::write(root.join("vault/s.txt"), b"a\nb\nc\nd\ne\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("work").unwrap(); + std::fs::write(root.join("src/a.txt"), b"OURS\nl2\nl3\n").unwrap(); + std::fs::write(root.join("vault/s.txt"), b"A\nb\nc\nd\ne\n").unwrap(); + repo.commit("me", "main edits").unwrap(); + repo.switch_with_identity("work", Some(&alice_sk)).unwrap(); + std::fs::write(root.join("src/a.txt"), b"THEIRS\nl2\nl3\n").unwrap(); + std::fs::write(root.join("vault/s.txt"), b"a\nb\nc\nd\nE\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + repo.set_sparse(&["src/".to_string()], Some(&alice_sk)) + .unwrap(); + assert!(!root.join("vault/s.txt").exists(), "out of the view"); + std::fs::create_dir_all(root.join("vault")).unwrap(); + std::fs::write(root.join("vault/s.txt"), b"MY LOCAL COPY\n").unwrap(); + + let err = repo + .merge_with_identity("work", "me", Some(&alice_sk)) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("overwrite an untracked")), + "got {err:?}" + ); + assert!(!repo.merge_in_progress()); + assert_eq!( + std::fs::read(root.join("vault/s.txt")).unwrap(), + b"MY LOCAL COPY\n" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// A binary conflict writes `.theirs`. An untracked file already + /// there (a leftover from an earlier stop, or the user's own) is refused, + /// not overwritten. + #[test] + fn a_binary_conflict_stop_refuses_over_an_untracked_sidecar() { + let root = tmp_root("mg-sidecar-untracked"); + 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(); + std::fs::write(root.join("bin.dat.theirs"), b"leftover\n").unwrap(); + + let err = repo.merge("work", "me").unwrap_err(); + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("overwrite an untracked")), + "got {err:?}" + ); + assert!(!repo.merge_in_progress()); + assert_eq!( + std::fs::read(root.join("bin.dat.theirs")).unwrap(), + b"leftover\n" + ); + assert_eq!( + std::fs::read(root.join("bin.dat")).unwrap(), + b"\xff\xfeOURS\n" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + + /// A file where a parent directory of a plaintext path must be fails the + /// write halfway; the stop refuses before writing anything instead. + #[test] + fn a_conflict_stop_refuses_when_a_file_blocks_a_parent_directory() { + let root = tmp_root("cp-prot-blocked-parent"); + let repo = Repo::init(&root).unwrap(); + let (alice_sk, alice_pk) = scl_crypto::generate_keypair(); + 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::remove_file(root.join("secret/a.txt")).unwrap(); + std::fs::write(root.join(".scignore"), b"secret\n").unwrap(); + repo.commit("me", "main deletes and ignores").unwrap(); + repo.switch("work").unwrap(); + repo.protect("secret/", &[alice_pk], None).unwrap(); + std::fs::write(root.join("secret/a.txt"), b"EDITED\nl2\nl3\n").unwrap(); + repo.commit("me", "work edits").unwrap(); + repo.switch_with_identity("main", Some(&alice_sk)).unwrap(); + // The user keeps an ignored FILE named `secret`. + let _ = std::fs::remove_dir_all(root.join("secret")); + std::fs::write(root.join("secret"), b"not a directory\n").unwrap(); + + let err = repo + .cherry_pick("work", "me", Some(&alice_sk), None) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidArgument(m) if m.contains("stands where a directory")), + "got {err:?}" + ); + assert!(!repo.pick_in_progress()); + assert!( + !root.join(".sc/CONFLICT_PLAINTEXT").exists(), + "nothing written" + ); + assert_eq!( + std::fs::read(root.join("secret")).unwrap(), + b"not a directory\n" + ); + drop(repo); + std::fs::remove_dir_all(&root).ok(); + } + #[test] fn cherry_pick_protected_conflict_writes_plaintext_markers_worktree_only() { // Same-line edits of secret/a.txt on both sides: the pick conflicts. diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index b59e846e..f9169047 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1799,6 +1799,48 @@ impl Repo { } } } + // The stop writes plaintext and sidecars with plain writes, outside + // `materialize`. A file or directory already on disk at one of those + // paths that `old_root` does not track is the user's own (an ignored or + // untracked copy, or a leftover sidecar): the write would replace it, + // and abort would then delete it. A file standing where a parent + // directory must be would fail the write halfway. Refuse both before + // any write (ADR-0049 q21). A lookup that fails counts as untracked. + { + let partial = self.promisor()?.is_some(); + let store_arc = self.vfs.store(); + let mut store = store_arc.lock().unwrap(); + let targets = to_encrypt + .iter() + .map(|(p, ..)| p.as_str()) + .chain(sidecars.iter().map(|(r, _)| r.as_str())); + for rel in targets { + // A path the sparse view never materialized holds no tracked + // file on disk, even if the tree tracks it: whatever is there + // is the user's own. A failed lookup counts as untracked. + let mut tracked = |p: &str| { + sparse.matches(p) + && worktree::tree_entry_at(&mut store, old_root, p, partial) + .is_ok_and(|e| e.is_some()) + }; + match stop_write_blocker(&self.layout.root, rel, &mut tracked)? { + None => {} + Some(StopBlocker::ParentFile) => { + return Err(Error::InvalidArgument(format!( + "merge has conflicts, and a file stands where a directory for {rel} \ + must be; move that file away, then retry" + ))) + } + Some(StopBlocker::Occupied) => { + return Err(Error::InvalidArgument(format!( + "merge has conflicts, and writing {rel} would overwrite an untracked \ + or ignored file or directory (possibly a sidecar left by an earlier \ + stop); move it away, then retry" + ))) + } + } + } + } // A carried subtree can sit inside the view: fill its closure before // the first working-tree write (lazy partial clones only), outside // the store lock. @@ -2262,6 +2304,45 @@ impl Repo { } } +/// What stands in the way of a conflict stop's direct write to `rel`. +#[derive(Debug, PartialEq, Eq)] +enum StopBlocker { + /// A file the old tree does not track sits where a parent directory of + /// `rel` must be. + ParentFile, + /// `rel` itself exists on disk and is not a tracked file: an untracked or + /// ignored copy, a leftover sidecar, or a directory. + Occupied, +} + +/// Decide whether a conflict stop may write `rel` under `root` (ADR-0049 +/// q21). `tracked(path)` says whether the tree the working tree reflects +/// tracks `path` as a file that is on disk. A tracked file standing where a +/// parent directory must be is fine: the stop's materialize removes it before +/// the write, as a merge that replaces a file with a directory does. A +/// directory at `rel` is never fine, tracked or not: the write would fail. +fn stop_write_blocker( + root: &std::path::Path, + rel: &str, + tracked: &mut impl FnMut(&str) -> bool, +) -> Result> { + let comps: Vec<&str> = rel.split('/').collect(); + for i in 1..comps.len() { + let prefix = comps[..i].join("/"); + let full = worktree::safe_join(root, &prefix)?; + if full.symlink_metadata().is_ok_and(|m| !m.is_dir()) && !tracked(&prefix) { + return Ok(Some(StopBlocker::ParentFile)); + } + } + let full = worktree::safe_join(root, rel)?; + match full.symlink_metadata() { + Err(_) => Ok(None), + Ok(m) if m.is_dir() => Ok(Some(StopBlocker::Occupied)), + Ok(_) if tracked(rel) => Ok(None), + Ok(_) => Ok(Some(StopBlocker::Occupied)), + } +} + #[cfg(test)] mod tests { use super::*; @@ -6373,3 +6454,66 @@ mod tests { std::fs::remove_dir_all(&dst_root).unwrap(); } } + +#[cfg(test)] +mod stop_blocker_tests { + use super::*; + + fn tmp(tag: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("scl-stop-blocker-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn a_tracked_file_replaced_by_a_directory_does_not_block() { + let root = tmp("file-to-dir"); + std::fs::write(root.join("a"), b"tracked\n").unwrap(); + let tracked = |p: &str| p == "a"; + assert_eq!( + stop_write_blocker(&root, "a/b", &mut { tracked }).unwrap(), + None, + "the old tree tracks `a`; materialize removes it before the write" + ); + let untracked = |_: &str| false; + assert_eq!( + stop_write_blocker(&root, "a/b", &mut { untracked }).unwrap(), + Some(StopBlocker::ParentFile) + ); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_directory_at_the_target_blocks_even_when_tracked() { + let root = tmp("dir-at-target"); + std::fs::create_dir_all(root.join("x/y")).unwrap(); + let tracked = |_: &str| true; + assert_eq!( + stop_write_blocker(&root, "x/y", &mut { tracked }).unwrap(), + Some(StopBlocker::Occupied) + ); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_tracked_file_target_is_fine_and_an_untracked_one_is_not() { + let root = tmp("file-target"); + std::fs::write(root.join("f"), b"x").unwrap(); + let tracked = |p: &str| p == "f"; + assert_eq!( + stop_write_blocker(&root, "f", &mut { tracked }).unwrap(), + None + ); + let untracked = |_: &str| false; + assert_eq!( + stop_write_blocker(&root, "f", &mut { untracked }).unwrap(), + Some(StopBlocker::Occupied) + ); + assert_eq!( + stop_write_blocker(&root, "missing", &mut { untracked }).unwrap(), + None + ); + std::fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/docs/adr/0049-merge-on-partial-clones.md b/docs/adr/0049-merge-on-partial-clones.md index eee13650..c07b08a5 100644 --- a/docs/adr/0049-merge-on-partial-clones.md +++ b/docs/adr/0049-merge-on-partial-clones.md @@ -184,7 +184,7 @@ Replay is a three-way merge with a different base, and `replay_commit` is the on 19. **Completion can drop a newly tracked ignored file.** *Resolved:* completion reads the working tree with the decided root's paths counted as tracked, so an ignore rule cannot hide a file the operation itself added. Test `completing_a_conflicted_pick_keeps_an_added_file_the_parent_ignores`. 20. **A stopped pick or rebase without its decided root.** `PICK_DECIDED_ROOT` and `REBASE_DECIDED_ROOT` are written before the state's in-progress signal, so the state cannot normally be missing. If it is (a lost file, a power loss before the data reached disk), a partial clone's completion refuses, because grafting from the tip would keep the old out-of-view content; `--abort` still works. -21. **A conflict stop overwrites an ignored or untracked file at a plaintext path.** The stop writes the decrypted text with a plain write, so a local copy the user kept at that path (the usual "stop tracking, keep it ignored" move) is replaced, and abort now removes the path. The loss happens at the stop and predates the record; refusing the stop when an untracked file sits at a plaintext path would close it. +21. **A conflict stop overwrites an ignored or untracked file at a plaintext path.** *Resolved for merge, cherry-pick and rebase:* `materialize_conflict_state` refuses, before any write, when a plaintext or sidecar path already exists on disk (as a file or directory, including a leftover sidecar) and the tree the working tree reflects does not track it or the sparse view never materialized it, or when a file stands where a parent directory must be. A lookup that fails counts as untracked. A clean merge, pick or rebase still overwrites an untracked file that a materialized added file lands on; that is `materialize`'s behaviour and is not changed here. The private-branch merge stop (`merge_into_private`) writes its files directly and has no such guard. Tests `a_conflict_stop_refuses_to_overwrite_an_untracked_local_copy`, `a_conflict_stop_does_not_treat_an_out_of_view_path_as_materialized`, `a_binary_conflict_stop_refuses_over_an_untracked_sidecar` and `a_conflict_stop_refuses_when_a_file_blocks_a_parent_directory`. ## Alternatives considered