From eba3ec0529eb27fe0a1e9631a571be3ad64dad6f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 17:14:40 +0300 Subject: [PATCH 1/5] fix(repo): replace a directory with a file on abort, switch and undo (#247) materialize failed with IsADirectory when a restore laid a file where the stop (or the tree being left) had a directory: the removal pass deletes the tracked files but left the emptied directories. Clear empty directories at the write path (never one holding untracked or ignored content), and let the untracked-overwrite guard accept a directory whose contents are all tracked, which also fixes switch refusing a tracked dir-to-file change as untracked. Ref #247 --- CLAUDE.md | 2 +- crates/repo/src/abort_transitions.rs | 254 +++++++++++++++++++++++++++ crates/repo/src/lib.rs | 2 + crates/repo/src/repo.rs | 49 +++++- crates/repo/src/worktree.rs | 27 +++ 5 files changed, 328 insertions(+), 6 deletions(-) create mode 100644 crates/repo/src/abort_transitions.rs diff --git a/CLAUDE.md b/CLAUDE.md index 52f21dd2..26fa7b30 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -283,7 +283,7 @@ transport-adjacent. The rest, imperatively: the view. - **A merge, switch, cherry-pick, rebase, undo or sparse-spec change refuses, before any write, to lay a file or directory onto an untracked or ignored one** (`refuse_untracked_overwrite`); move it - away and retry. Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded. + away and retry. A directory holding only tracked files is not such a case: a file/directory change at one path crosses switch, undo, abort and `--continue`, and the emptied directories are cleared (#247). Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded. - **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. A push into a repo with a stopped op is diff --git a/crates/repo/src/abort_transitions.rs b/crates/repo/src/abort_transitions.rs new file mode 100644 index 00000000..2b618260 --- /dev/null +++ b/crates/repo/src/abort_transitions.rs @@ -0,0 +1,254 @@ +//! Tests for #247: aborting (or otherwise leaving) a tree where the other side +//! turned a file into a directory, or the reverse. The restore must replace +//! the stop's layout at that path, never fail with `IsADirectory` / +//! `NotADirectory`, and never delete anything the tree being replaced does not +//! track. + +use std::path::{Path, PathBuf}; + +use crate::error::Error; +use crate::repo::Repo; +use crate::RebaseResult; + +/// How the path `x` is laid out on a side. +#[derive(Clone, Copy, Debug)] +enum Shape { + File, + Dir, +} + +fn tmp_root(tag: &str) -> PathBuf { + let p = std::env::temp_dir().join(format!("scl-repo-abort-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&p); + std::fs::create_dir_all(&p).unwrap(); + p +} + +fn lay(root: &Path, shape: Shape) { + let _ = std::fs::remove_file(root.join("x")); + let _ = std::fs::remove_dir_all(root.join("x")); + match shape { + Shape::File => std::fs::write(root.join("x"), b"file\n").unwrap(), + Shape::Dir => { + std::fs::create_dir_all(root.join("x")).unwrap(); + std::fs::write(root.join("x/a"), b"a\n").unwrap(); + } + } +} + +fn assert_shape(root: &Path, shape: Shape) { + match shape { + Shape::File => assert_eq!(std::fs::read(root.join("x")).unwrap(), b"file\n"), + Shape::Dir => { + assert!(root.join("x").is_dir()); + assert_eq!(std::fs::read(root.join("x/a")).unwrap(), b"a\n"); + assert_eq!(std::fs::read_dir(root.join("x")).unwrap().count(), 1); + } + } +} + +/// `main` keeps `x` as `ours`; branch `other` turns it into `theirs` and both +/// edit `c.txt`'s first line, so combining them stops on a conflict. +fn fixture(tag: &str, ours: Shape, theirs: Shape) -> (PathBuf, Repo) { + let root = tmp_root(tag); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("c.txt"), b"1\n2\n3\n").unwrap(); + lay(&root, ours); + repo.commit("me", "base").unwrap(); + repo.branch("other").unwrap(); + std::fs::write(root.join("c.txt"), b"OURS\n2\n3\n").unwrap(); + repo.commit("me", "main").unwrap(); + repo.switch("other").unwrap(); + lay(&root, theirs); + std::fs::write(root.join("c.txt"), b"THEIRS\n2\n3\n").unwrap(); + repo.commit("me", "other").unwrap(); + repo.switch("main").unwrap(); + (root, repo) +} + +fn assert_restored(root: &Path, repo: &Repo, ours: Shape) { + assert_shape(root, ours); + assert_eq!(std::fs::read(root.join("c.txt")).unwrap(), b"OURS\n2\n3\n"); + let st = repo.status().unwrap(); + assert!(st.modified.is_empty() && st.deleted.is_empty(), "{st:?}"); +} + +fn finish(root: &Path, repo: Repo) { + drop(repo); + std::fs::remove_dir_all(root).unwrap(); +} + +const TRANSITIONS: [(&str, Shape, Shape); 2] = [ + ("f2d", Shape::File, Shape::Dir), + ("d2f", Shape::Dir, Shape::File), +]; + +#[test] +fn merge_abort_restores_a_file_dir_transition() { + for (tag, ours, theirs) in TRANSITIONS { + let (root, repo) = fixture(&format!("merge-{tag}"), ours, theirs); + assert!(matches!( + repo.merge("other", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + assert_shape(&root, theirs); + repo.merge_abort().unwrap(); + assert_restored(&root, &repo, ours); + finish(&root, repo); + } +} + +#[test] +fn cherry_pick_abort_restores_a_file_dir_transition() { + for (tag, ours, theirs) in TRANSITIONS { + let (root, repo) = fixture(&format!("pick-{tag}"), ours, theirs); + let r = repo.cherry_pick("other", "me", None, None); + assert!(matches!(r, Err(Error::PickConflicts(_))), "{r:?}"); + assert_shape(&root, theirs); + repo.cherry_pick_abort().unwrap(); + assert_restored(&root, &repo, ours); + finish(&root, repo); + } +} + +#[test] +fn rebase_abort_restores_a_file_dir_transition() { + for (tag, ours, theirs) in TRANSITIONS { + let (root, repo) = fixture(&format!("rebase-{tag}"), ours, theirs); + let r = repo.rebase("other", "me", None).unwrap(); + assert!(matches!(r, RebaseResult::Stopped { .. }), "{r:?}"); + assert_shape(&root, theirs); + repo.rebase_abort().unwrap(); + assert_restored(&root, &repo, ours); + finish(&root, repo); + } +} + +/// An untracked file inside the directory the abort must replace with a file +/// is the user's: the abort fails loudly and keeps it, and the stopped op +/// stays open to retry. +#[test] +fn merge_abort_keeps_untracked_content_in_the_obstructing_directory() { + let (root, repo) = fixture("merge-untracked", Shape::File, Shape::Dir); + assert!(matches!( + repo.merge("other", "me").unwrap_err(), + Error::MergeConflicts(_) + )); + std::fs::write(root.join("x/mine.txt"), b"mine\n").unwrap(); + assert!(repo.merge_abort().is_err()); + assert_eq!(std::fs::read(root.join("x/mine.txt")).unwrap(), b"mine\n"); + assert!(repo.merge_in_progress()); + std::fs::remove_file(root.join("x/mine.txt")).unwrap(); + repo.merge_abort().unwrap(); + assert_restored(&root, &repo, Shape::File); + finish(&root, repo); +} + +/// `switch` and `undo` across a file/directory change at one path. +#[test] +fn switch_and_undo_cross_a_file_dir_transition() { + for (tag, ours, theirs) in TRANSITIONS { + let root = tmp_root(&format!("switch-{tag}")); + let repo = Repo::init(&root).unwrap(); + lay(&root, ours); + repo.commit("me", "base").unwrap(); + repo.branch("other").unwrap(); + repo.switch("other").unwrap(); + lay(&root, theirs); + repo.commit("me", "other").unwrap(); + repo.switch("main").unwrap(); + assert_shape(&root, ours); + repo.switch("other").unwrap(); + assert_shape(&root, theirs); + repo.switch("main").unwrap(); + assert_shape(&root, ours); + lay(&root, theirs); + repo.commit("me", "flip").unwrap(); + repo.undo().unwrap(); + assert_shape(&root, ours); + finish(&root, repo); + } +} + +/// `rebase --continue` lays a later commit's file/directory change over the +/// resolved stop. +#[test] +fn rebase_continue_crosses_a_file_dir_transition() { + for (tag, from, to) in TRANSITIONS { + let root = tmp_root(&format!("continue-{tag}")); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("c.txt"), b"1\n2\n3\n").unwrap(); + lay(&root, from); + repo.commit("me", "base").unwrap(); + repo.branch("other").unwrap(); + std::fs::write(root.join("c.txt"), b"OURS\n2\n3\n").unwrap(); + repo.commit("me", "a").unwrap(); + lay(&root, to); + repo.commit("me", "b").unwrap(); + repo.switch("other").unwrap(); + std::fs::write(root.join("c.txt"), b"THEIRS\n2\n3\n").unwrap(); + repo.commit("me", "other").unwrap(); + repo.switch("main").unwrap(); + assert!(matches!( + repo.rebase("other", "me", None).unwrap(), + RebaseResult::Stopped { .. } + )); + std::fs::write(root.join("c.txt"), b"RESOLVED\n2\n3\n").unwrap(); + let r = repo.rebase_continue("me", None).unwrap(); + assert!(matches!(r, RebaseResult::Rebased { .. }), "{r:?}"); + assert_shape(&root, to); + finish(&root, repo); + } +} + +/// The same abort on a `--filter src/` partial clone, with `src/x` changing +/// between file and directory on the other side. +#[test] +fn merge_abort_restores_a_file_dir_transition_on_a_partial_clone() { + use crate::partial_merge::{clone_edit_src, Fx}; + for (tag, ours, theirs) in TRANSITIONS { + let fx = Fx::origin(&format!("abort-fd-{tag}"), |root| { + lay(&root.join("src"), ours); + }); + fx.origin.branch("b1").unwrap(); + fx.origin.switch("b1").unwrap(); + lay(&fx.origin_root.join("src"), theirs); + std::fs::write(fx.origin_root.join("src/a.txt"), b"ONE\ntwo\nthree\n").unwrap(); + fx.origin.commit("t", "b1").unwrap(); + fx.origin.switch("main").unwrap(); + let clone = fx.clone(false); + clone_edit_src(&fx, &clone, b"uno\ntwo\nthree\n"); + assert!(matches!( + clone.merge("origin/b1", "t").unwrap_err(), + Error::MergeConflicts(_) + )); + assert_shape(&fx.clone_root.join("src"), theirs); + clone.merge_abort().unwrap(); + assert_shape(&fx.clone_root.join("src"), ours); + let st = clone.status().unwrap(); + assert!(st.modified.is_empty() && st.deleted.is_empty(), "{st:?}"); + drop(clone); + fx.cleanup(); + } +} + +/// A forward `switch` onto a file where a directory with an untracked file +/// stands still refuses, and deletes nothing. +#[test] +fn switch_refuses_a_file_over_a_directory_holding_untracked_content() { + let root = tmp_root("switch-untracked"); + let repo = Repo::init(&root).unwrap(); + lay(&root, Shape::Dir); + repo.commit("me", "base").unwrap(); + repo.branch("other").unwrap(); + repo.switch("other").unwrap(); + lay(&root, Shape::File); + repo.commit("me", "other").unwrap(); + repo.switch("main").unwrap(); + std::fs::write(root.join("x/mine.txt"), b"mine\n").unwrap(); + let err = repo.switch("other").unwrap_err(); + assert!(matches!(err, Error::InvalidArgument(_)), "{err:?}"); + assert_eq!(std::fs::read(root.join("x/mine.txt")).unwrap(), b"mine\n"); + assert_eq!(std::fs::read(root.join("x/a")).unwrap(), b"a\n"); + finish(&root, repo); +} diff --git a/crates/repo/src/lib.rs b/crates/repo/src/lib.rs index 35b8b7b3..8a3005d0 100644 --- a/crates/repo/src/lib.rs +++ b/crates/repo/src/lib.rs @@ -1,6 +1,8 @@ //! `scl-repo` — the durable on-disk repository: `.sc/` layout, refs/HEAD, //! named branches, a git-like working tree, and commit/secret orchestration. +#[cfg(test)] +mod abort_transitions; pub mod bucket_transport; pub(crate) mod cache; pub(crate) mod conflict_plaintext; diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 87db0585..0335da47 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1984,6 +1984,7 @@ impl Repo { )?; for (path, bytes, mode, _recipients) in to_encrypt { let full = worktree::safe_join(&self.layout.root, path)?; + worktree::clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } @@ -2693,6 +2694,28 @@ fn is_tracked_case_alias( false } +/// True when the directory `full` (path `rel`) holds nothing but tracked +/// files and directories: no symlink, and no file `tracked` does not name. A +/// read failure counts as not tracked. +fn dir_holds_only_tracked( + full: &std::path::Path, + rel: &str, + tracked: &mut impl FnMut(&str) -> bool, +) -> bool { + let Ok(entries) = std::fs::read_dir(full) else { + return false; + }; + entries.into_iter().all(|e| { + let Ok(e) = e else { return false }; + let child = format!("{rel}/{}", e.file_name().to_string_lossy()); + match e.file_type() { + Ok(t) if t.is_dir() => dir_holds_only_tracked(&e.path(), &child, tracked), + Ok(t) if t.is_file() => tracked(&child), + _ => false, + } + }) +} + /// What stands in the way of a conflict stop's direct write to `rel`. #[derive(Debug, PartialEq, Eq)] enum StopBlocker { @@ -2709,7 +2732,8 @@ enum StopBlocker { /// 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. +/// directory at `rel` is fine only when everything under it is tracked (the +/// reverse replacement, #247); any other content in it is the user's. fn stop_write_blocker( root: &std::path::Path, rel: &str, @@ -2731,7 +2755,13 @@ fn stop_write_blocker( let full = worktree::safe_join(root, rel)?; match full.symlink_metadata() { Err(_) => Ok(None), - Ok(m) if m.is_dir() => Ok(Some(StopBlocker::Occupied)), + // A directory is fine when it holds only tracked files: the write + // removes them first and `worktree::clear_dir_obstruction` the husk. + Ok(m) if m.is_dir() => Ok(if dir_holds_only_tracked(&full, rel, tracked) { + None + } else { + Some(StopBlocker::Occupied) + }), // A symlink is never the tracked file: a write would follow it to // whatever it points at, outside the repository. Ok(m) if m.file_type().is_symlink() => Ok(Some(StopBlocker::Occupied)), @@ -7023,13 +7053,22 @@ mod stop_blocker_tests { } #[test] - fn a_directory_at_the_target_blocks_even_when_tracked() { + fn a_directory_at_the_target_blocks_unless_everything_in_it_is_tracked() { let root = tmp("dir-at-target"); std::fs::create_dir_all(root.join("x/y")).unwrap(); - let tracked = |_: &str| true; + std::fs::write(root.join("x/y/a"), b"a\n").unwrap(); + // Only `x/y/a` is tracked: the directory holds nothing else. + let tracked = |p: &str| p == "x/y/a"; assert_eq!( stop_write_blocker(&root, "x/y", &mut { tracked }).unwrap(), - Some(StopBlocker::Occupied) + None, + "the stop removes the tracked files, then the empty directories" + ); + std::fs::write(root.join("x/y/mine"), b"mine\n").unwrap(); + assert_eq!( + stop_write_blocker(&root, "x/y", &mut { tracked }).unwrap(), + Some(StopBlocker::Occupied), + "an untracked file in it is the user's" ); std::fs::remove_dir_all(&root).unwrap(); } diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index be17f841..f67e648d 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -921,6 +921,30 @@ pub(crate) fn lay_out_added_view( Ok(protected) } +/// Make room for a file at `full` (tracked path `path`) where a directory +/// stands: the removal pass has deleted the tracked files under it, so what is +/// left is a husk of empty directories, which goes. A directory that still +/// holds anything (an untracked or ignored file of the user's) is never +/// touched: the error names it, and the caller's state stays retryable (#247). +pub(crate) fn clear_dir_obstruction(full: &Path, path: &str) -> Result<()> { + fn prune(dir: &Path) -> std::io::Result<()> { + for e in std::fs::read_dir(dir)? { + let e = e?; + if e.file_type()?.is_dir() { + prune(&e.path())?; + } + } + std::fs::remove_dir(dir) + } + if full.symlink_metadata().is_ok_and(|m| m.is_dir()) && prune(full).is_err() { + return Err(Error::InvalidArgument(format!( + "cannot write {path}: a directory with untracked or ignored content stands there; \ + move it away, then retry" + ))); + } + Ok(()) +} + /// Materialize a snapshot's file tree into the working dir. /// /// `sparse` filters the disk view: a target entry outside `sparse` is never @@ -1060,6 +1084,7 @@ pub(crate) fn materialize_with_old_view( })(); match decrypted { Some(pt) => { + clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } @@ -1085,6 +1110,7 @@ pub(crate) fn materialize_with_old_view( // can't linger when a path becomes protected across a switch for // a non-recipient (confidentiality). A failed removal must // surface — swallowing it leaves plaintext on disk. + clear_dir_obstruction(&full, path)?; match std::fs::remove_file(&full) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} @@ -1094,6 +1120,7 @@ pub(crate) fn materialize_with_old_view( } } } else { + clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } From 5ded271da2948e935ca7a7fb916c251731bb7813 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 17:30:01 +0300 Subject: [PATCH 2/5] fix(repo): address review on #247: private switch, sidecar dirs, no partial prune Ref #247 --- crates/repo/src/abort_transitions.rs | 57 ++++++++++++++++++++++++++++ crates/repo/src/private.rs | 3 ++ crates/repo/src/repo.rs | 54 +++++++++++++++++++------- crates/repo/src/worktree.rs | 14 ++++--- 4 files changed, 109 insertions(+), 19 deletions(-) diff --git a/crates/repo/src/abort_transitions.rs b/crates/repo/src/abort_transitions.rs index 2b618260..8de54f37 100644 --- a/crates/repo/src/abort_transitions.rs +++ b/crates/repo/src/abort_transitions.rs @@ -76,6 +76,11 @@ fn assert_restored(root: &Path, repo: &Repo, ours: Shape) { fn finish(root: &Path, repo: Repo) { drop(repo); std::fs::remove_dir_all(root).unwrap(); + assert!( + !root.exists(), + "test root {} must be removed", + root.display() + ); } const TRANSITIONS: [(&str, Shape, Shape); 2] = [ @@ -252,3 +257,55 @@ fn switch_refuses_a_file_over_a_directory_holding_untracked_content() { assert_eq!(std::fs::read(root.join("x/a")).unwrap(), b"a\n"); finish(&root, repo); } + +/// A user's empty directory is not evidence of tracked content: a forward +/// `switch` onto a file at its path refuses and keeps it. +#[test] +fn switch_keeps_an_untracked_empty_directory_where_a_file_must_go() { + let root = tmp_root("switch-empty-dir"); + let repo = Repo::init(&root).unwrap(); + std::fs::write(root.join("c.txt"), b"c\n").unwrap(); + repo.commit("me", "base").unwrap(); + repo.branch("other").unwrap(); + repo.switch("other").unwrap(); + lay(&root, Shape::File); + repo.commit("me", "other").unwrap(); + repo.switch("main").unwrap(); + std::fs::create_dir(root.join("x")).unwrap(); + assert!(repo.switch("other").is_err()); + assert!(root.join("x").is_dir()); + finish(&root, repo); +} + +/// An abort that cannot replace a directory because of an untracked file +/// leaves the user's empty subdirectories alone too. +#[test] +fn merge_abort_refusal_does_not_prune_empty_user_directories() { + let (root, repo) = fixture("merge-prune", Shape::File, Shape::Dir); + assert!(repo.merge("other", "me").is_err()); + std::fs::write(root.join("x/mine.txt"), b"mine\n").unwrap(); + std::fs::create_dir(root.join("x/empty")).unwrap(); + assert!(repo.merge_abort().is_err()); + assert!(root.join("x/empty").is_dir()); + assert!(root.join("x/mine.txt").exists()); + finish(&root, repo); +} + +/// Switching onto a private branch across a directory-to-file change. +#[test] +fn private_switch_crosses_a_directory_to_file_transition() { + let root = tmp_root("private"); + let repo = Repo::init(&root).unwrap(); + let (sk, _pk) = scl_crypto::generate_keypair(); + lay(&root, Shape::Dir); + repo.commit("me", "base").unwrap(); + repo.branch_private("fix", &sk, &[], &[]).unwrap(); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + lay(&root, Shape::File); + repo.commit_private("me", "flip", Some(&sk)).unwrap(); + repo.switch_with_identity("main", Some(&sk)).unwrap(); + assert_shape(&root, Shape::Dir); + repo.switch_with_identity("fix", Some(&sk)).unwrap(); + assert_shape(&root, Shape::File); + finish(&root, repo); +} diff --git a/crates/repo/src/private.rs b/crates/repo/src/private.rs index 974f3c25..cd83eacf 100644 --- a/crates/repo/src/private.rs +++ b/crates/repo/src/private.rs @@ -401,6 +401,7 @@ impl Repo { // envelope, decrypted via the inner snapshot's wraps. match crate::protect::decrypt_with(&bytes, blob_id, &[protection], identity, path) { Ok(pt) => { + worktree::clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } @@ -410,6 +411,7 @@ impl Repo { // KEK recipient without path access: skip, never // leave stale plaintext behind (same rule as // `worktree::materialize`). + worktree::clear_dir_obstruction(&full, path)?; match std::fs::remove_file(&full) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} @@ -419,6 +421,7 @@ impl Repo { } } } else { + worktree::clear_dir_obstruction(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 0335da47..82d96103 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -1915,7 +1915,22 @@ impl Repo { .iter() .map(|(p, ..)| p.as_str()) .chain(sidecars.iter().map(|(r, _)| r.as_str())); + let sidecar_rels: std::collections::BTreeSet<&str> = + sidecars.iter().map(|(r, _)| r.as_str()).collect(); for rel in targets { + // Only a plaintext target clears a tracked directory husk; a + // sidecar is written with a plain write, so any directory at + // its path blocks. + if sidecar_rels.contains(rel) + && worktree::safe_join(&self.layout.root, rel)? + .symlink_metadata() + .is_ok_and(|m| m.is_dir()) + { + return Err(Error::InvalidArgument(format!( + "{op} has conflicts, and its sidecar {rel} would land on a directory; \ + move it away, then retry" + ))); + } // Every target is in the view (gated above; a sidecar is // never tracked, checked above). A failed lookup counts as // untracked. @@ -2694,26 +2709,37 @@ fn is_tracked_case_alias( false } -/// True when the directory `full` (path `rel`) holds nothing but tracked -/// files and directories: no symlink, and no file `tracked` does not name. A -/// read failure counts as not tracked. +/// True when the directory `full` (path `rel`) holds at least one tracked file +/// and nothing else of substance: no symlink, and no file `tracked` does not +/// name. An empty directory has no tracked file to show it is the old tree's, +/// and a read failure counts as not tracked. fn dir_holds_only_tracked( full: &std::path::Path, rel: &str, tracked: &mut impl FnMut(&str) -> bool, ) -> bool { - let Ok(entries) = std::fs::read_dir(full) else { - return false; - }; - entries.into_iter().all(|e| { - let Ok(e) = e else { return false }; - let child = format!("{rel}/{}", e.file_name().to_string_lossy()); - match e.file_type() { - Ok(t) if t.is_dir() => dir_holds_only_tracked(&e.path(), &child, tracked), - Ok(t) if t.is_file() => tracked(&child), - _ => false, + // `Some(n)`: only tracked files, `n` of them. + fn count( + full: &std::path::Path, + rel: &str, + tracked: &mut impl FnMut(&str) -> bool, + ) -> Option { + let mut n = 0; + for e in std::fs::read_dir(full).ok()? { + let e = e.ok()?; + let child = format!("{rel}/{}", e.file_name().to_string_lossy()); + let t = e.file_type().ok()?; + if t.is_dir() { + n += count(&e.path(), &child, tracked)?; + } else if t.is_file() && tracked(&child) { + n += 1; + } else { + return None; + } } - }) + Some(n) + } + count(full, rel, tracked).is_some_and(|n| n > 0) } /// What stands in the way of a conflict stop's direct write to `rel`. diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index f67e648d..1665d006 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -912,6 +912,7 @@ pub(crate) fn lay_out_added_view( continue; }; let full = safe_join(&layout.root, &path)?; + clear_dir_obstruction(&full, &path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } @@ -927,16 +928,19 @@ pub(crate) fn lay_out_added_view( /// holds anything (an untracked or ignored file of the user's) is never /// touched: the error names it, and the caller's state stays retryable (#247). pub(crate) fn clear_dir_obstruction(full: &Path, path: &str) -> Result<()> { - fn prune(dir: &Path) -> std::io::Result<()> { + // Only directories all the way down: one file (or symlink) anywhere keeps + // the whole tree, so a refusal never leaves it half pruned. + fn only_dirs(dir: &Path) -> std::io::Result { for e in std::fs::read_dir(dir)? { let e = e?; - if e.file_type()?.is_dir() { - prune(&e.path())?; + if !e.file_type()?.is_dir() || !only_dirs(&e.path())? { + return Ok(false); } } - std::fs::remove_dir(dir) + Ok(true) } - if full.symlink_metadata().is_ok_and(|m| m.is_dir()) && prune(full).is_err() { + let is_dir = full.symlink_metadata().is_ok_and(|m| m.is_dir()); + if is_dir && !(only_dirs(full).unwrap_or(false) && std::fs::remove_dir_all(full).is_ok()) { return Err(Error::InvalidArgument(format!( "cannot write {path}: a directory with untracked or ignored content stands there; \ move it away, then retry" From aaff37a30ab4da19a1608c94d392287a1e689bc6 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 17:44:08 +0300 Subject: [PATCH 3/5] fix(repo): remove obstructing directories bottom-up, never recursively Ref #247 --- crates/repo/src/worktree.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index 1665d006..6f1e129d 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -939,8 +939,16 @@ pub(crate) fn clear_dir_obstruction(full: &Path, path: &str) -> Result<()> { } Ok(true) } + // Bottom-up `remove_dir`, never `remove_dir_all`: a file created after the + // check above makes a directory non-empty and the removal fail, not vanish. + fn prune(dir: &Path) -> std::io::Result<()> { + for e in std::fs::read_dir(dir)? { + prune(&e?.path())?; + } + std::fs::remove_dir(dir) + } let is_dir = full.symlink_metadata().is_ok_and(|m| m.is_dir()); - if is_dir && !(only_dirs(full).unwrap_or(false) && std::fs::remove_dir_all(full).is_ok()) { + if is_dir && !(only_dirs(full).unwrap_or(false) && prune(full).is_ok()) { return Err(Error::InvalidArgument(format!( "cannot write {path}: a directory with untracked or ignored content stands there; \ move it away, then retry" From b9333d79afdca4a81937dada8e17a9032f321867 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 17:56:44 +0300 Subject: [PATCH 4/5] fix(repo): do not follow swapped entries or non-UTF-8 names when clearing a directory Ref #247 --- crates/repo/src/repo.rs | 3 ++- crates/repo/src/worktree.rs | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/repo/src/repo.rs b/crates/repo/src/repo.rs index 82d96103..1c5dde19 100644 --- a/crates/repo/src/repo.rs +++ b/crates/repo/src/repo.rs @@ -2727,7 +2727,8 @@ fn dir_holds_only_tracked( let mut n = 0; for e in std::fs::read_dir(full).ok()? { let e = e.ok()?; - let child = format!("{rel}/{}", e.file_name().to_string_lossy()); + // A name that is not UTF-8 cannot be a tracked path. + let child = format!("{rel}/{}", e.file_name().to_str()?); let t = e.file_type().ok()?; if t.is_dir() { n += count(&e.path(), &child, tracked)?; diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index 6f1e129d..f1c34dbf 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -943,7 +943,12 @@ pub(crate) fn clear_dir_obstruction(full: &Path, path: &str) -> Result<()> { // check above makes a directory non-empty and the removal fail, not vanish. fn prune(dir: &Path) -> std::io::Result<()> { for e in std::fs::read_dir(dir)? { - prune(&e?.path())?; + let e = e?; + // A child swapped for a symlink since the check is never followed. + if !e.file_type()?.is_dir() { + return Err(std::io::ErrorKind::DirectoryNotEmpty.into()); + } + prune(&e.path())?; } std::fs::remove_dir(dir) } From 689d8bbe5e327d15dbfe89930578905def53c98f Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 18:57:12 +0300 Subject: [PATCH 5/5] fix(repo): keep a user's empty directory when materializing with no old tree Ref #247 --- crates/repo/src/worktree.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/repo/src/worktree.rs b/crates/repo/src/worktree.rs index 829e0dfd..d1c31169 100644 --- a/crates/repo/src/worktree.rs +++ b/crates/repo/src/worktree.rs @@ -1022,6 +1022,15 @@ pub(crate) fn materialize_with_old_view( // (partial clones only; ADR-0048). The check lives here so every caller // is covered and none can forget it. preflight_view(layout, store, target_root, sparse)?; + // With no old tree there is no removal pass, so an empty directory at a + // target path is the user's, not a husk: leave it, and let the write fail. + let clear = |full: &Path, path: &str| { + if old_root.is_some() { + clear_dir_obstruction(full, path) + } else { + Ok(()) + } + }; // Gap-tolerant when sparse is active (P27 Task 4): a promisor-filtered // clone never fetched out-of-filter subtrees at all, so an unfiltered // walk here would `NotFound` on them. @@ -1108,7 +1117,7 @@ pub(crate) fn materialize_with_old_view( })(); match decrypted { Some(pt) => { - clear_dir_obstruction(&full, path)?; + clear(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; } @@ -1134,7 +1143,7 @@ pub(crate) fn materialize_with_old_view( // can't linger when a path becomes protected across a switch for // a non-recipient (confidentiality). A failed removal must // surface — swallowing it leaves plaintext on disk. - clear_dir_obstruction(&full, path)?; + clear(&full, path)?; match std::fs::remove_file(&full) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} @@ -1144,7 +1153,7 @@ pub(crate) fn materialize_with_old_view( } } } else { - clear_dir_obstruction(&full, path)?; + clear(&full, path)?; if let Some(parent) = full.parent() { std::fs::create_dir_all(parent)?; }