fix(core): protect ignored files and fix backup ref namespaces

Archive no longer deletes worktrees holding ignored files, fast-forward and
snapshot apply decline instead of overwriting ignored files, backup refs use
per-kind namespaces, add refuses sparse checkouts. Regression tests and docs
updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 12:12:46 +01:00
1 parent 938604193e
commit 126acb4b57
6 files changed
+277 -20

No files matched your search

+31 -5
View File
@@ -95,6 +95,8 @@ struct Progress {
wt_meta: Option<PathBuf>,
filled: bool,
index_moved: bool,
/// Original `core.worktree`, restored on rollback.
orig_core_worktree: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
@@ -154,7 +156,7 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
}
if root.join(STAGE).exists() {
return refuse(format!(
"{STAGE} exists: a previous migration was interrupted"
"{STAGE} exists: a previous migration was interrupted. Your files are in {STAGE} and the git dir in .bare; restore from the backup tar or move them back by hand"
));
}
if !dotgit.is_dir() {
@@ -188,6 +190,17 @@ fn preflight(root: &Path) -> Result<String, MigrateError> {
));
}
}
if matches!(
git.probe(&["config", "--get", "core.sparseCheckout"])?
.as_deref(),
Some("true")
) || matches!(
git.probe(&["config", "--get", "extensions.worktreeConfig"])?
.as_deref(),
Some("true")
) {
return refuse("sparse checkout / per-worktree config is not supported yet");
}
if root.join(".gitmodules").exists() || dotgit.join("modules").exists() {
return refuse("submodules are not supported yet");
}
@@ -209,6 +222,10 @@ fn backup(
backup_dir: &Path,
stamp: &str,
) -> Result<(PathBuf, String), MigrateError> {
// Check before creating anything so a refusal never leaves stray directories behind.
if std::path::absolute(backup_dir)?.starts_with(root) {
return refuse("backup directory must be outside the repository");
}
fs::create_dir_all(backup_dir)?;
let backup_dir = backup_dir.canonicalize()?;
if backup_dir.starts_with(root) {
@@ -236,7 +253,7 @@ fn backup(
String::from_utf8_lossy(&out.stderr)
));
}
let backup_ref = format!("refs/sync-backup/{machine}/{stamp}");
let backup_ref = format!("refs/sync-backup/{machine}/{stamp}/add");
git.run(&["update-ref", &backup_ref, "HEAD"])?;
Ok((tar, backup_ref))
}
@@ -322,6 +339,9 @@ fn run_steps(
root_git
.run(&["--git-dir", BARE, "config", "core.bare", "true"])
.map_err(s)?;
p.orig_core_worktree = root_git
.probe(&["--git-dir", BARE, "config", "--get", "core.worktree"])
.map_err(s)?;
root_git
.probe(&["--git-dir", BARE, "config", "--unset", "core.worktree"])
.map_err(s)?;
@@ -416,12 +436,18 @@ fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
&& meta.exists()
{
fs::remove_dir_all(meta).map_err(s)?;
let _ = fs::remove_dir(bare.join("worktrees"));
}
if p.git_moved {
Git::new(root)
.run(&["--git-dir", BARE, "config", "core.bare", "false"])
let g = Git::new(root);
// Drop metadata of a half-created worktree (e.g. `worktree add` failed midway).
let _ = g.probe(&["--git-dir", BARE, "worktree", "prune"]);
let _ = fs::remove_dir(bare.join("worktrees"));
g.run(&["--git-dir", BARE, "config", "core.bare", "false"])
.map_err(s)?;
if let Some(w) = &p.orig_core_worktree {
g.run(&["--git-dir", BARE, "config", "core.worktree", w])
.map_err(s)?;
}
fs::rename(&bare, root.join(".git")).map_err(s)?;
}
if p.staged && stage.exists() {
+86 -9
View File
@@ -13,8 +13,51 @@ pub const REMOTE: &str = "origin";
/// Local namespace where other machines' snapshot refs are fetched to.
pub const REMOTE_SYNC: &str = "refs/sync-remote";
fn backup_ref(machine: &str, stamp: &str) -> String {
format!("refs/sync-backup/{machine}/{stamp}")
/// Backup refs live in `refs/sync-backup/<machine>/<stamp>/<kind>`; each kind has its own
/// sub-namespace so refs of different operations in one pass can never collide (D/F conflict).
fn backup_ref(machine: &str, stamp: &str, kind: &str) -> String {
format!("refs/sync-backup/{machine}/{stamp}/{kind}")
}
/// Paths the incoming change would add that already exist locally as *ignored* files.
/// `git status` does not report those, but a merge/read-tree would silently overwrite them.
fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, GitError> {
let added = g.run(&[
"diff",
"--no-renames",
"--diff-filter=A",
"--name-only",
"-z",
"HEAD",
target,
])?;
let added: Vec<&str> = added.split('\0').filter(|p| !p.is_empty()).collect();
if added.is_empty() {
return Ok(vec![]);
}
let ignored = g.run(&[
"ls-files",
"--others",
"--ignored",
"--exclude-standard",
"--directory",
"-z",
])?;
let ignored: Vec<&str> = ignored.split('\0').filter(|p| !p.is_empty()).collect();
Ok(added
.into_iter()
.filter(|a| {
ignored
.iter()
.any(|i| a == i || (i.ends_with('/') && a.starts_with(i)))
})
.map(String::from)
.collect())
}
fn current_branch(g: &Git) -> Result<String, GitError> {
g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into()))
}
/// Make sure a bare repo created with `git clone --bare` can track remote branches.
@@ -57,8 +100,13 @@ pub fn push_snapshot(worktree: &Path, machine: &str, remote: &str) -> Result<(),
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Received {
FastForwarded { from: String, to: String },
FastForwarded {
from: String,
to: String,
},
Skipped(State),
/// Clean and behind, but the update would overwrite local ignored files.
Declined(String),
}
/// Fast-forward a clean, strictly-behind worktree to its upstream. Anything else is skipped.
@@ -68,8 +116,16 @@ pub fn receive(worktree: &Path, machine: &str, stamp: &str) -> Result<Received,
return Ok(Received::Skipped(st));
}
let g = Git::new(worktree);
let clash = ignored_conflicts(&g, "@{upstream}")?;
if !clash.is_empty() {
return Ok(Received::Declined(format!(
"would overwrite ignored local files: {}",
clash.join(", ")
)));
}
let from = g.run(&["rev-parse", "HEAD"])?;
g.run(&["update-ref", &backup_ref(machine, stamp), &from])?;
let bref = backup_ref(machine, stamp, &format!("receive/{}", current_branch(&g)?));
g.run(&["update-ref", &bref, &from])?;
g.run(&["merge", "-q", "--ff-only", "@{upstream}"])?;
let to = g.run(&["rev-parse", "HEAD"])?;
Ok(Received::FastForwarded { from, to })
@@ -108,7 +164,10 @@ pub fn foreign_snapshots(worktree: &Path, machine: &str) -> Result<Vec<ForeignSn
if m == machine || b != branch {
continue;
}
let based_on = g.run(&["rev-parse", &format!("{oid}^1")])?;
// A snapshot taken on an unborn HEAD has no parent: nothing to base it on, skip it.
let Some(based_on) = g.probe(&["rev-parse", "-q", "--verify", &format!("{oid}^1")])? else {
continue;
};
out.push(ForeignSnapshot {
machine: m.to_string(),
commit: oid.to_string(),
@@ -155,11 +214,19 @@ pub fn apply_snapshot(
if snap_tree == g.run(&["rev-parse", "HEAD^{tree}"])? {
return Ok(Applied::Nothing);
}
g.run(&["update-ref", &backup_ref(machine, stamp), &head])?;
let clash = ignored_conflicts(&g, &snap.commit)?;
if !clash.is_empty() {
return Ok(Applied::Declined(format!(
"would overwrite ignored local files: {}",
clash.join(", ")
)));
}
let bref = backup_ref(machine, stamp, &format!("apply/{}", current_branch(&g)?));
g.run(&["update-ref", &bref, &head])?;
if head != snap.based_on {
g.run(&["merge", "-q", "--ff-only", &snap.based_on])?;
}
// Two-way merge: refuses (without changing anything) if it would clobber untracked files.
// Two-way merge: refuses on untracked files; ignored ones were checked above.
g.run(&["read-tree", "-m", "-u", "HEAD", &snap.commit])?;
// Present the changes as working changes, like on the machine that made them.
g.run(&["reset", "-q"])?;
@@ -232,6 +299,12 @@ pub enum Archived {
pub fn archive_gone(root: &Path, machine: &str, stamp: &str) -> Result<Vec<Archived>, GitError> {
let bare = root.join(".bare");
let g = Git::new(&bare);
// A remote that currently shows no branches at all (empty, re-created, outage) would make
// every branch look "gone": never archive in that case.
let tracked = g.run(&["for-each-ref", "--format=%(refname)", "refs/remotes"])?;
if tracked.lines().all(|l| l.ends_with("/HEAD")) {
return Ok(vec![]);
}
let listing = g.run(&[
"for-each-ref",
"--format=%(refname:short)|%(upstream:track)",
@@ -249,14 +322,18 @@ pub fn archive_gone(root: &Path, machine: &str, stamp: &str) -> Result<Vec<Archi
let Some(wt) = wts.iter().find(|w| w.branch.as_deref() == Some(branch)) else {
continue;
};
if facts(&wt.path)?.dirty {
// Ignored files (.env, build output...) count as local work too.
if !Git::new(&wt.path)
.run(&["status", "--porcelain", "--ignored"])?
.is_empty()
{
out.push(Archived::KeptDirty {
branch: branch.to_string(),
});
continue;
}
let tip = g.run(&["rev-parse", &format!("refs/heads/{branch}")])?;
let bref = format!("{}/{}", backup_ref(machine, stamp), branch);
let bref = backup_ref(machine, stamp, &format!("archive/{branch}"));
g.run(&["update-ref", &bref, &tip])?;
g.run(&["worktree", "remove", &wt.path.to_string_lossy()])?;
g.run(&["branch", "-D", branch])?;
+10
View File
@@ -195,6 +195,16 @@ fn refuses_unsafe_situations_without_touching_anything() {
commit(&g, "a", "1");
assert!(refused(migrate(&inside, "m", &inside.join("bk"), "1")).contains("outside"));
assert!(inside.join(".git").is_dir());
assert!(
!inside.join("bk").exists(),
"refusal must not create the backup dir"
);
let sparse = base.join("sparse");
let g = init(&sparse);
commit(&g, "a", "1");
g.run(&["config", "core.sparseCheckout", "true"]).unwrap();
assert!(refused(migrate(&sparse, "m", &bk, "1")).contains("sparse"));
// Subdirectory is not a repo root.
fs::create_dir(inside.join("sub")).unwrap();
assert!(refused(migrate(&inside.join("sub"), "m", &bk, "1")).contains("plain clone"));
+129 -2
View File
@@ -81,7 +81,8 @@ fn clean_behind_worktree_fast_forwards_with_backup() {
);
assert!(w.d2.join("b.txt").exists());
assert_eq!(
w.g2.run(&["rev-parse", "refs/sync-backup/m2/t1"]).unwrap(),
w.g2.run(&["rev-parse", "refs/sync-backup/m2/t1/receive/main"])
.unwrap(),
old
);
}
@@ -241,7 +242,7 @@ fn materializes_new_remote_branches_and_archives_gone_ones() {
assert!(!root.join("feat-x").exists());
let bg = Git::new(&r.bare_dir);
assert!(
bg.run(&["rev-parse", "refs/sync-backup/m2/t9/feat/x"])
bg.run(&["rev-parse", "refs/sync-backup/m2/t9/archive/feat/x"])
.is_ok()
);
assert!(
@@ -278,3 +279,129 @@ fn gone_branch_with_local_changes_is_kept_and_flagged() {
fn state_of(p: &std::path::Path) -> State {
gitsync_core::inspect::state(p)
}
// ---- regression tests for the review findings ----
#[test]
fn archive_keeps_clean_worktree_that_holds_ignored_files() {
let w = world();
let r = migrate(&w.d2, "m2", &w.base.join("bk"), "1").unwrap();
let root = w.d2.canonicalize().unwrap();
w.g1.run(&["checkout", "-q", "-b", "feat/e"]).unwrap();
commit(&w.g1, "e.txt", "e\n");
w.g1.run(&["push", "-q", "-u", "origin", "feat/e"]).unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
materialize(&root, REMOTE).unwrap();
fs::write(root.join("feat-e/local.env"), "SECRET=1\n").unwrap(); // ignored by *.env
assert_eq!(
state_of(&root.join("feat-e")),
State::Synced,
"ignored files are invisible to status"
);
w.g1.run(&["push", "-q", "origin", "--delete", "feat/e"])
.unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
assert_eq!(
archive_gone(&root, "m2", "t").unwrap(),
vec![Archived::KeptDirty {
branch: "feat/e".into()
}]
);
assert_eq!(
fs::read_to_string(root.join("feat-e/local.env")).unwrap(),
"SECRET=1\n"
);
}
#[test]
fn archive_does_nothing_when_remote_shows_no_branches() {
let w = world();
let r = migrate(&w.d2, "m2", &w.base.join("bk"), "1").unwrap();
let root = w.d2.canonicalize().unwrap();
let bg = Git::new(&r.bare_dir);
for line in bg
.run(&["for-each-ref", "--format=%(refname)", "refs/remotes"])
.unwrap()
.lines()
{
bg.run(&["update-ref", "-d", line]).unwrap();
}
assert!(archive_gone(&root, "m2", "t").unwrap().is_empty());
assert!(root.join("main").exists());
}
#[test]
fn fast_forward_declines_instead_of_overwriting_local_ignored_file() {
let w = world();
commit(&w.g1, "conf.local", "theirs\n");
w.g1.run(&["push", "-q"]).unwrap();
fs::write(w.d2.join(".git/info/exclude"), "conf.local\n").unwrap();
fs::write(w.d2.join("conf.local"), "mine\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
let head = w.g2.run(&["rev-parse", "HEAD"]).unwrap();
assert!(matches!(
receive(&w.d2, "m2", "t").unwrap(),
Received::Declined(_)
));
assert_eq!(w.g2.run(&["rev-parse", "HEAD"]).unwrap(), head);
assert_eq!(
fs::read_to_string(w.d2.join("conf.local")).unwrap(),
"mine\n"
);
}
#[test]
fn snapshot_apply_declines_instead_of_overwriting_local_ignored_file() {
let w = world();
fs::write(w.d1.join("conf.local"), "theirs\n").unwrap();
take(&w.d1, "m1", "t1").unwrap();
push_snapshot(&w.d1, "m1", REMOTE).unwrap();
fs::write(w.d2.join(".git/info/exclude"), "conf.local\n").unwrap();
fs::write(w.d2.join("conf.local"), "mine\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
let snap = foreign_snapshots(&w.d2, "m2").unwrap().remove(0);
assert!(matches!(
apply_snapshot(&w.d2, &snap, "m2", "t").unwrap(),
Applied::Declined(_)
));
assert_eq!(
fs::read_to_string(w.d2.join("conf.local")).unwrap(),
"mine\n"
);
}
#[test]
fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
use gitsync_core::sync::{Options, sync_repo};
let w = world();
migrate(&w.d2, "m2", &w.base.join("bk"), "1").unwrap();
let root = w.d2.canonicalize().unwrap();
let o = |stamp: &str| Options {
machine: "m2".into(),
stamp: stamp.into(),
remote: "origin".into(),
offline: false,
materialize: true,
};
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
commit(&w.g1, "z.txt", "z\n");
w.g1.run(&["push", "-q", "-u", "origin", "feat/z"]).unwrap();
sync_repo(&root, &o("s1")).unwrap();
assert!(root.join("feat-z").exists());
// Same pass: feat/z disappears upstream AND main moves.
w.g1.run(&["push", "-q", "origin", "--delete", "feat/z"])
.unwrap();
w.g1.run(&["checkout", "-q", "main"]).unwrap();
commit(&w.g1, "m.txt", "m\n");
w.g1.run(&["push", "-q", "origin", "main"]).unwrap();
let rep = sync_repo(&root, &o("s2")).unwrap();
assert_eq!(rep.archived.len(), 1);
for wt in &rep.worktrees {
assert!(wt.errors.is_empty(), "{:?}", wt.errors);
}
assert!(
root.join("main/m.txt").exists(),
"main fast-forwarded in the same pass"
);
}
+4 -2
View File
@@ -153,8 +153,10 @@ fn print_report(rep: &SyncReport) -> Result<()> {
if let Some(s) = w.snapshot {
notes.push(format!("snapshot {s}"));
}
if let Some(Received::FastForwarded { .. }) = &w.received {
notes.push("fast-forwarded".into());
match &w.received {
Some(Received::FastForwarded { .. }) => notes.push("fast-forwarded".into()),
Some(Received::Declined(why)) => notes.push(format!("not fast-forwarded: {why}")),
_ => {}
}
if let Some((m, a)) = &w.applied {
match a {