Skip to content
Merged
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,9 @@ 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 (except that a private stop refuses a `.theirs` sidecar that would land on an existing file).
away and retry. On a sparse checkout the same holds for a path the result adds
outside the view (a later commit would take the user's file instead, #248).
Merging into an unborn branch and the conflict stop of a merge into a private branch are not guarded (except that a private stop refuses a `.theirs` sidecar that would land on an existing file).
- **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
Expand Down
19 changes: 19 additions & 0 deletions crates/repo/src/private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,12 +377,23 @@ impl Repo {
old_paths: &BTreeSet<String>,
protection: &Protection,
identity: &SecretKey,
restores: bool,
) -> Result<Vec<String>> {
let sparse = self.sparse_spec()?;
let target = self.inner_tree_files(store, ctx, target_root)?;
// Before the first removal or write: nothing of the user's may be
// replaced (see `refuse_untracked_paths`).
self.refuse_untracked_paths(op, old_paths, target.keys())?;
// A restore (abort) re-lays the tree the stop started from: nothing is
// added, and `old_paths` is only what the stop wrote, in view.
if !restores {
self.refuse_untracked_out_of_view_paths(
op,
&sparse,
old_paths,
&target.keys().cloned().collect(),
)?;
}
for p in old_paths {
if !target.contains_key(p) || !sparse.matches(p) {
let full = worktree::safe_join(&self.layout.root, p)?;
Expand Down Expand Up @@ -459,6 +470,7 @@ impl Repo {
old_paths,
&tip_snap.protection,
sk,
false,
)?
};
refs::write_head(&self.layout, name)?;
Expand Down Expand Up @@ -896,6 +908,7 @@ impl Repo {
&written,
&ours.protection,
sk,
true,
)?;
drop(store);
// After the restore, so a failed restore leaves the sidecars to retry.
Expand Down Expand Up @@ -1350,6 +1363,7 @@ impl Repo {
&old_paths,
&theirs_snap.protection,
sk,
false,
)?;
drop(store);
refs::write_branch_tip(&self.layout, &head, &new_mid)?;
Expand Down Expand Up @@ -1412,6 +1426,10 @@ impl Repo {
// value (`commit_private`, #240). It reads MERGE_HEAD.
let prior_entries = self.inner_tree_files(&mut store, &ctx, ours_snap.root)?;
let prior_paths: BTreeSet<String> = prior_entries.keys().cloned().collect();
// Completion reads the working tree, where a file wins over the
// merge's addition: refuse one in the way outside the view (#248).
let merged_paths: BTreeSet<String> = fm.files.iter().map(|f| f.path.clone()).collect();
self.refuse_untracked_out_of_view_paths("merge", &sparse, &prior_paths, &merged_paths)?;
// Carried protected ciphertext: decrypt for the resolver to see
// (completion re-seals it as needed). One this recipient cannot
// read has its old plaintext dropped, so completion carries the
Expand Down Expand Up @@ -1619,6 +1637,7 @@ impl Repo {
&old_paths,
&merged_prot,
sk,
false,
)?;
drop(store);
refs::write_branch_tip(&self.layout, &head, &new_mid)?;
Expand Down
75 changes: 75 additions & 0 deletions crates/repo/src/private_sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,78 @@ fn replay_onto_a_private_branch_stays_refused_under_sparse() {
std::fs::remove_dir_all(&f.root).unwrap();
assert!(!f.root.exists(), "test dir left behind");
}

#[test]
fn an_untracked_file_where_the_public_side_adds_one_out_of_view_is_refused() {
let f = fixture("collide", true, false);
let mine = f.root.join("docs/new.txt");
std::fs::create_dir_all(mine.parent().unwrap()).unwrap();
std::fs::write(&mine, "MINE\n").unwrap();
let (_, before, _) = f.repo.head_private().unwrap().unwrap();
let err = f
.repo
.merge_into_private("main", "alice", Some(&f.sk))
.unwrap_err()
.to_string();
assert!(err.contains("docs/new.txt"), "{err}");
assert!(err.contains("move it away"), "{err}");
assert!(!crate::merge_state::in_progress(f.repo.layout()));
assert_eq!(f.repo.head_private().unwrap().unwrap().1, before);
assert_eq!(std::fs::read_to_string(&mine).unwrap(), "MINE\n");
assert_eq!(
std::fs::read_to_string(f.root.join("src/lib.rs")).unwrap(),
"private\n",
"refusal wrote nothing"
);
// Moved away, the same run lands the public addition.
std::fs::remove_file(&mine).unwrap();
let got = run(&f, true);
assert_eq!(got["new.txt"], "new-public\n");
std::fs::remove_dir_all(&f.root).unwrap();
assert!(!f.root.exists(), "test dir left behind");
}

#[test]
fn leaving_a_private_branch_refuses_an_untracked_file_where_main_has_one_out_of_view() {
let f = fixture("leave", true, false);
let mine = f.root.join("docs/new.txt");
std::fs::create_dir_all(mine.parent().unwrap()).unwrap();
std::fs::write(&mine, "MINE\n").unwrap();
let err = f
.repo
.switch_with_identity("main", Some(&f.sk))
.unwrap_err()
.to_string();
assert!(
err.contains("docs/new.txt") && err.contains("move it away"),
"{err}"
);
assert!(
f.repo.head_private().unwrap().is_some(),
"still on the private branch"
);
assert_eq!(std::fs::read_to_string(&mine).unwrap(), "MINE\n");
std::fs::remove_file(&mine).unwrap();
f.repo.switch_with_identity("main", Some(&f.sk)).unwrap();
std::fs::remove_dir_all(&f.root).unwrap();
assert!(!f.root.exists(), "test dir left behind");
}

#[test]
fn aborting_a_private_stop_ignores_a_file_at_an_out_of_view_tracked_path() {
let f = fixture("abort", true, false);
let sk = Some(&f.sk);
assert!(matches!(
f.repo.merge_into_private("main", "alice", sk),
Err(Error::MergeConflicts(1))
));
// `docs/ours.txt` is tracked by the private tip, outside the view.
put(&f.root, "docs/ours.txt", "MINE\n");
f.repo.merge_abort_with_identity(sk).unwrap();
assert_eq!(
std::fs::read_to_string(f.root.join("docs/ours.txt")).unwrap(),
"MINE\n"
);
std::fs::remove_dir_all(&f.root).unwrap();
assert!(!f.root.exists(), "test dir left behind");
}
108 changes: 107 additions & 1 deletion crates/repo/src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2056,7 +2056,11 @@ impl Repo {
.collect()
}
};
self.refuse_untracked_overwrite_vs(op, &old, target_root)
self.refuse_untracked_overwrite_vs(op, &old, target_root)?;
match old_root {
Some(old) => self.refuse_untracked_out_of_view(op, old, target_root),
None => Ok(()),
}
}

/// Refuse, before any write, a forward operation (`op`) whose result would
Expand Down Expand Up @@ -2189,6 +2193,88 @@ impl Repo {
Ok(())
}

/// Refuse, before any write, an operation (`op`) whose result adds a file
/// outside the sparse view at a path where the user already has an
/// untracked or ignored file or directory. Nothing is written there, but
/// a later commit (a stop's completion, or the next ordinary one) reads
/// the working tree, where a file wins over the tree, and would commit the
/// user's bytes instead of the addition, silently (#248). `old_root` is
/// the tree the working tree reflects, `target_root` the result. A path
/// `old_root` already tracks is not an addition, and is left to the
/// ordinary tracked-file rules.
pub(crate) fn refuse_untracked_out_of_view(
&self,
op: &str,
old_root: ObjectId,
target_root: ObjectId,
) -> Result<()> {
let sparse = self.sparse_spec()?;
if sparse.is_full() {
return Ok(());
}
let partial = self.promisor()?.is_some();
let (old, target) = {
let store_arc = self.vfs.store();
let mut store = store_arc.lock().unwrap();
let mut paths = |root| -> Result<std::collections::BTreeSet<String>> {
// A partial clone lacks some subtrees: read what it holds.
Ok(if partial {
worktree::tree_file_entries_with_perms_sparse_present(
&mut store,
root,
&crate::Sparse::default(),
)?
Comment on lines +2222 to +2226

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect collisions beneath absent partial-clone subtrees

On a partial clone whose sparse view excludes a subtree, that subtree is commonly absent from the local store, so tree_file_entries_with_perms_sparse_present silently skips every target path beneath it. If a merge, pick, rebase, switch, or undo carries a changed absent subtree containing a newly added path and an untracked file already exists at that path, this guard sees neither the addition nor the collision: a clean operation can move the ref and a conflicted operation can write its in-view stop state instead of refusing up front. A later commit may only fail with GappedPathContent, after the operation has already changed visible state, so the guard needs to compare absent carried subtree entries or conservatively check on-disk paths beneath changed missing subtrees.

Useful? React with 👍 / 👎.

} else {
worktree::tree_file_entries_with_perms(&mut store, root)?
}
.into_keys()
.collect())
};
(paths(old_root)?, paths(target_root)?)
};
self.refuse_untracked_out_of_view_paths(op, &sparse, &old, &target)
}

/// The path-list core of [`Repo::refuse_untracked_out_of_view`], for a
/// caller that already holds both trees' file paths (a private branch's
/// decrypted trees).
pub(crate) fn refuse_untracked_out_of_view_paths(
&self,
op: &str,
sparse: &crate::Sparse,
old: &std::collections::BTreeSet<String>,
target: &std::collections::BTreeSet<String>,
) -> Result<()> {
// `rel` is not in `old`, and a tree holds no file at an ancestor of
// another of its paths, so nothing on the way is a tracked file.
// Relies on `stop_write_blocker` treating whatever stands at `rel` (any
// directory included) as the user's: nothing outside the view is laid
// out, so no tracked file can be on disk there.
// Only a case alias of a path `old` laid out, so inside the view (a
// case-only rename on a case-insensitive filesystem), is the tracked
// file; an out-of-view old path was never on disk.
let root = &self.layout.root;
let laid_out = std::cell::OnceCell::new();
let mut is_tracked = |p: &str| {
let laid_out: &std::collections::BTreeSet<String> = laid_out
.get_or_init(|| old.iter().filter(|o| sparse.matches(o)).cloned().collect());
is_tracked_case_alias(root, laid_out, p)
};
for rel in target
.iter()
.filter(|p| !sparse.matches(p) && !old.contains(*p))
{
if stop_write_blocker(&self.layout.root, rel, &mut is_tracked)?.is_some() {
return Err(Error::InvalidArgument(format!(
"{op} would add {rel} (outside your sparse checkout), where an untracked or \
ignored file or directory already stands; a later commit would take that \
instead of the addition; move it away, then retry"
)));
}
}
Ok(())
}

/// The sidecars the in-progress stop recorded writing. A record with no
/// merge, pick or rebase in progress is residue of a crash mid-stop, and
/// names nothing that is ours: it reads as empty.
Expand Down Expand Up @@ -2520,6 +2606,26 @@ impl Repo {
// before the first stale file is removed or written (ADR-0048).
self.ensure_view(target_root, &self.sparse_spec()?)?;
self.refuse_untracked_overwrite_vs("switch", &old_paths, target_root)?;
match old_root {
Some(old) => self.refuse_untracked_out_of_view("switch", old, target_root)?,
// Leaving a private branch: `old_paths` is its full inner tree
// (partial clones refuse private branches).
None => {
let target: std::collections::BTreeSet<String> = {
let store_arc = self.vfs.store();
let mut store = store_arc.lock().unwrap();
worktree::tree_file_entries_with_perms(&mut store, target_root)?
.into_keys()
.collect()
};
self.refuse_untracked_out_of_view_paths(
"switch",
&self.sparse_spec()?,
&old_paths,
&target,
)?;
}
}
if head_priv.is_some() {
// Remove private-tip paths the public target doesn't track,
// BEFORE materialize lays the target down.
Expand Down
Loading
Loading