From 126acb4b57c5a3cc2f22c4e564f796aa0e335bad Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 12:12:46 +0100 Subject: [PATCH] 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 --- crates/gitsync-core/src/migrate.rs | 36 +++++++- crates/gitsync-core/src/receive.rs | 95 +++++++++++++++++-- crates/gitsync-core/tests/migrate.rs | 10 ++ crates/gitsync-core/tests/receive.rs | 131 ++++++++++++++++++++++++++- crates/gitsync/src/main.rs | 6 +- docs/phase1.md | 19 +++- 6 files changed, 277 insertions(+), 20 deletions(-) diff --git a/crates/gitsync-core/src/migrate.rs b/crates/gitsync-core/src/migrate.rs index b8f9637..64421f8 100644 --- a/crates/gitsync-core/src/migrate.rs +++ b/crates/gitsync-core/src/migrate.rs @@ -95,6 +95,8 @@ struct Progress { wt_meta: Option, filled: bool, index_moved: bool, + /// Original `core.worktree`, restored on rollback. + orig_core_worktree: Option, } #[derive(Debug, PartialEq, Eq)] @@ -154,7 +156,7 @@ fn preflight(root: &Path) -> Result { } 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 { )); } } + 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() { diff --git a/crates/gitsync-core/src/receive.rs b/crates/gitsync-core/src/receive.rs index 4cc0a47..9491255 100644 --- a/crates/gitsync-core/src/receive.rs +++ b/crates/gitsync-core/src/receive.rs @@ -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///`; 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, 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 { + 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 Result Result, 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 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" + ); +} diff --git a/crates/gitsync/src/main.rs b/crates/gitsync/src/main.rs index a51db78..fb8ccde 100644 --- a/crates/gitsync/src/main.rs +++ b/crates/gitsync/src/main.rs @@ -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 { diff --git a/docs/phase1.md b/docs/phase1.md index c25d4de..a58b169 100644 --- a/docs/phase1.md +++ b/docs/phase1.md @@ -37,8 +37,23 @@ they may only contain letters, digits, `-` and `_`. to the original layout (tested by injecting a failure after every step). - Every operation that rewrites a worktree writes a backup ref first. - `apply_snapshot` declines (changing nothing) on any local work; `read-tree -m -u` additionally - refuses to overwrite untracked files. -- `archive_gone` keeps dirty worktrees and writes a backup ref before deleting a branch. + refuses to overwrite untracked files. Both it and the fast-forward in `receive` also decline when + the incoming change would overwrite a local *ignored* file (`ignored_conflicts`). +- `archive_gone` keeps any worktree whose `status --porcelain --ignored` is non-empty (so `.env` + and similar are never deleted), never archives when the remote lists no branches, and writes a + backup ref before deleting a branch. +- Backup refs live in per-kind namespaces (`refs/sync-backup///`, kinds + `add`, `receive/`, `apply/`, `archive/`) so several in one pass cannot + collide as ref directory/file. +- `add` also refuses sparse checkouts and `extensions.worktreeConfig`. + +## Known limitations + +- Nested untracked git repos are snapshotted only as gitlinks (their content is not synced). +- No crash-resume: a hard kill in the middle of `add` leaves `.gitsync-stage`; the error says where + the files are, but recovery is manual (the backup tar and ref exist). +- Machine-name uniqueness across machines is not enforced. +- Split-index repos are untested. ## Not done yet (later phases)