feat(core): add receive logic, foreign snapshot apply, materialize and archive

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 12:05:56 +01:00
1 parent b6f868ee76
commit e731c691f8
3 files changed
+552

No files matched your search

+3
View File
@@ -3,5 +3,8 @@
pub mod config;
pub mod git;
pub mod inspect;
pub mod layout;
pub mod migrate;
pub mod receive;
pub mod snapshot;
pub mod state;
+269
View File
@@ -0,0 +1,269 @@
//! Keeping this machine current (section 7.2): fetch, fast-forward, foreign snapshots,
//! materializing new branches and archiving gone ones. Never touches a dirty worktree.
use crate::git::{Git, GitError};
use crate::inspect::{facts, state};
use crate::layout::dir_name;
use crate::snapshot::ref_name;
use crate::state::State;
use std::fs;
use std::path::{Path, PathBuf};
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}")
}
/// Make sure a bare repo created with `git clone --bare` can track remote branches.
pub fn ensure_fetch_refspec(repo: &Path, remote: &str) -> Result<(), GitError> {
let g = Git::new(repo);
let key = format!("remote.{remote}.fetch");
if g.probe(&["config", "--get", &key])?.is_none() {
g.run(&[
"config",
&key,
&format!("+refs/heads/*:refs/remotes/{remote}/*"),
])?;
}
Ok(())
}
/// Fetch branches (pruning) and every machine's snapshot refs.
pub fn fetch(repo: &Path, remote: &str) -> Result<(), GitError> {
let g = Git::new(repo);
g.run(&["fetch", "-q", "--prune", remote])?;
g.run(&[
"fetch",
"-q",
remote,
&format!("+refs/sync/*:{REMOTE_SYNC}/*"),
])?;
Ok(())
}
/// Push this machine's snapshot ref for the worktree's branch (machine-owned, so forced).
pub fn push_snapshot(worktree: &Path, machine: &str, remote: &str) -> Result<(), GitError> {
let g = Git::new(worktree);
let branch = g
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into()))?;
let r = ref_name(machine, &branch);
g.run(&["push", "-q", "--force", remote, &format!("{r}:{r}")])?;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Received {
FastForwarded { from: String, to: String },
Skipped(State),
}
/// Fast-forward a clean, strictly-behind worktree to its upstream. Anything else is skipped.
pub fn receive(worktree: &Path, machine: &str, stamp: &str) -> Result<Received, GitError> {
let st = state(worktree);
if st != State::Behind {
return Ok(Received::Skipped(st));
}
let g = Git::new(worktree);
let from = g.run(&["rev-parse", "HEAD"])?;
g.run(&["update-ref", &backup_ref(machine, stamp), &from])?;
g.run(&["merge", "-q", "--ff-only", "@{upstream}"])?;
let to = g.run(&["rev-parse", "HEAD"])?;
Ok(Received::FastForwarded { from, to })
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForeignSnapshot {
pub machine: String,
pub commit: String,
/// First parent: the branch commit the snapshot was taken on.
pub based_on: String,
}
/// Other machines' fetched snapshots for the worktree's current branch.
pub fn foreign_snapshots(worktree: &Path, machine: &str) -> Result<Vec<ForeignSnapshot>, GitError> {
let g = Git::new(worktree);
let Some(branch) = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])? else {
return Ok(vec![]);
};
let listing = g.run(&[
"for-each-ref",
"--format=%(refname) %(objectname)",
REMOTE_SYNC,
])?;
let mut out = Vec::new();
for line in listing.lines() {
let Some((name, oid)) = line.split_once(' ') else {
continue;
};
let Some(rest) = name.strip_prefix(&format!("{REMOTE_SYNC}/")) else {
continue;
};
let Some((m, b)) = rest.split_once('/') else {
continue;
};
if m == machine || b != branch {
continue;
}
let based_on = g.run(&["rev-parse", &format!("{oid}^1")])?;
out.push(ForeignSnapshot {
machine: m.to_string(),
commit: oid.to_string(),
based_on,
});
}
out.sort_by(|a, b| a.machine.cmp(&b.machine));
Ok(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Applied {
Applied,
/// Snapshot tree already equals the worktree's committed tree.
Nothing,
Declined(String),
}
/// Apply another machine's snapshot as working changes. Only when the worktree is clean
/// with no local commits ahead, and HEAD can fast-forward to the snapshot's base.
pub fn apply_snapshot(
worktree: &Path,
snap: &ForeignSnapshot,
machine: &str,
stamp: &str,
) -> Result<Applied, GitError> {
let f = facts(worktree)?;
if f.dirty {
return Ok(Applied::Declined("worktree has local changes".into()));
}
if f.ahead {
return Ok(Applied::Declined("worktree has unpushed commits".into()));
}
let g = Git::new(worktree);
if g.probe(&["merge-base", "--is-ancestor", "HEAD", &snap.based_on])?
.is_none()
{
return Ok(Applied::Declined(
"snapshot is not based on a descendant of HEAD".into(),
));
}
let head = g.run(&["rev-parse", "HEAD"])?;
let snap_tree = g.run(&["rev-parse", &format!("{}^{{tree}}", snap.commit)])?;
if snap_tree == g.run(&["rev-parse", "HEAD^{tree}"])? {
return Ok(Applied::Nothing);
}
g.run(&["update-ref", &backup_ref(machine, stamp), &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.
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"])?;
Ok(Applied::Applied)
}
/// Create worktrees under `root` for remote branches that have none. Returns new paths.
pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> {
let bare = root.join(".bare");
let g = Git::new(&bare);
let prefix = format!("refs/remotes/{remote}/");
let remotes = g.run(&["for-each-ref", "--format=%(refname)", &prefix])?;
let existing_branches: Vec<String> = crate::inspect::worktrees(&bare)?
.into_iter()
.filter_map(|w| w.branch)
.collect();
let mut taken: Vec<String> = fs::read_dir(root)?
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
let mut created = Vec::new();
for r in remotes.lines() {
let Some(branch) = r.strip_prefix(&prefix) else {
continue;
};
if branch == "HEAD" || existing_branches.iter().any(|b| b == branch) {
continue;
}
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
let dir = dir_name(branch, &refs);
let path = root.join(&dir);
let path_str = path.to_string_lossy().into_owned();
let local_exists = g
.probe(&[
"rev-parse",
"-q",
"--verify",
&format!("refs/heads/{branch}"),
])?
.is_some();
if local_exists {
g.run(&["worktree", "add", "-q", &path_str, branch])?;
} else {
g.run(&[
"worktree",
"add",
"-q",
"--track",
"-b",
branch,
&path_str,
&format!("{remote}/{branch}"),
])?;
}
taken.push(dir);
created.push(path);
}
Ok(created)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Archived {
/// Worktree removed and branch deleted; the tip is kept under `backup_ref`.
Removed { branch: String, backup_ref: String },
/// Worktree has local changes: kept and flagged.
KeptDirty { branch: String },
}
/// Archive worktrees whose upstream branch is gone (merged/deleted on the remote).
pub fn archive_gone(root: &Path, machine: &str, stamp: &str) -> Result<Vec<Archived>, GitError> {
let bare = root.join(".bare");
let g = Git::new(&bare);
let listing = g.run(&[
"for-each-ref",
"--format=%(refname:short)|%(upstream:track)",
"refs/heads",
])?;
let gone: Vec<&str> = listing
.lines()
.filter_map(|l| l.split_once('|'))
.filter(|(_, t)| t.contains("gone"))
.map(|(b, _)| b)
.collect();
let wts = crate::inspect::worktrees(&bare)?;
let mut out = Vec::new();
for branch in gone {
let Some(wt) = wts.iter().find(|w| w.branch.as_deref() == Some(branch)) else {
continue;
};
if facts(&wt.path)?.dirty {
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);
g.run(&["update-ref", &bref, &tip])?;
g.run(&["worktree", "remove", &wt.path.to_string_lossy()])?;
g.run(&["branch", "-D", branch])?;
out.push(Archived::Removed {
branch: branch.to_string(),
backup_ref: bref,
});
}
Ok(out)
}
+280
View File
@@ -0,0 +1,280 @@
mod common;
use common::*;
use gitsync_core::git::Git;
use gitsync_core::migrate::migrate;
use gitsync_core::receive::*;
use gitsync_core::snapshot::take;
use gitsync_core::state::State;
use std::fs;
use std::path::PathBuf;
struct World {
base: PathBuf,
remote: PathBuf,
g1: Git,
d1: PathBuf,
g2: Git,
d2: PathBuf,
}
/// Bare remote plus two plain clones (machines "m1" and "m2") sharing `main` with one commit.
fn world() -> World {
let base = tmpdir("recv");
let remote = base.join("remote.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let d1 = base.join("m1");
let g1 = init(&d1);
g1.run(&["remote", "add", "origin", remote.to_str().unwrap()])
.unwrap();
commit(&g1, "a.txt", "1\n");
commit(&g1, ".gitignore", "*.env\n");
g1.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
let d2 = base.join("m2");
Git::new(&base)
.run(&[
"clone",
"-q",
remote.to_str().unwrap(),
d2.to_str().unwrap(),
])
.unwrap();
let g2 = Git::new(&d2);
g2.run(&["config", "user.email", "t@t"]).unwrap();
g2.run(&["config", "user.name", "t"]).unwrap();
World {
base,
remote,
g1,
d1,
g2,
d2,
}
}
#[test]
fn fetch_works_when_remote_has_no_snapshots() {
let w = world();
fetch(&w.d2, REMOTE).unwrap();
}
#[test]
fn clean_behind_worktree_fast_forwards_with_backup() {
let w = world();
commit(&w.g1, "b.txt", "2\n");
w.g1.run(&["push", "-q"]).unwrap();
fetch(&w.d2, REMOTE).unwrap();
let old = w.g2.run(&["rev-parse", "HEAD"]).unwrap();
let r = receive(&w.d2, "m2", "t1").unwrap();
assert!(matches!(r, Received::FastForwarded { .. }));
assert_eq!(
w.g2.run(&["rev-parse", "HEAD"]).unwrap(),
w.g1.run(&["rev-parse", "HEAD"]).unwrap()
);
assert!(w.d2.join("b.txt").exists());
assert_eq!(
w.g2.run(&["rev-parse", "refs/sync-backup/m2/t1"]).unwrap(),
old
);
}
#[test]
fn dirty_worktree_is_never_touched() {
let w = world();
commit(&w.g1, "b.txt", "2\n");
w.g1.run(&["push", "-q"]).unwrap();
fs::write(w.d2.join("a.txt"), "1\nlocal edit\n").unwrap();
fetch(&w.d2, REMOTE).unwrap();
let head = w.g2.run(&["rev-parse", "HEAD"]).unwrap();
assert_eq!(
receive(&w.d2, "m2", "t").unwrap(),
Received::Skipped(State::BehindDirty)
);
assert_eq!(w.g2.run(&["rev-parse", "HEAD"]).unwrap(), head);
assert_eq!(
fs::read_to_string(w.d2.join("a.txt")).unwrap(),
"1\nlocal edit\n"
);
assert!(!w.d2.join("b.txt").exists());
}
#[test]
fn divergence_keeps_both_sides_intact() {
let w = world();
commit(&w.g1, "b.txt", "remote\n");
w.g1.run(&["push", "-q"]).unwrap();
commit(&w.g2, "c.txt", "local\n");
fetch(&w.d2, REMOTE).unwrap();
let head = w.g2.run(&["rev-parse", "HEAD"]).unwrap();
assert_eq!(
receive(&w.d2, "m2", "t").unwrap(),
Received::Skipped(State::Diverged)
);
assert_eq!(w.g2.run(&["rev-parse", "HEAD"]).unwrap(), head);
assert!(w.d2.join("c.txt").exists() && !w.d2.join("b.txt").exists());
// The remote side is still reachable for resolution.
assert!(w.g2.run(&["rev-parse", "origin/main"]).is_ok());
}
#[test]
fn snapshot_roundtrip_between_machines() {
let w = world();
// m1 commits (pushed) and then has work in progress on top.
commit(&w.g1, "b.txt", "2\n");
w.g1.run(&["push", "-q"]).unwrap();
fs::write(w.d1.join("a.txt"), "1\nwip edit\n").unwrap();
fs::write(w.d1.join("new.txt"), "untracked\n").unwrap();
fs::write(w.d1.join("s.env"), "secret\n").unwrap();
fs::remove_file(w.d1.join("b.txt")).unwrap();
take(&w.d1, "m1", "t1").unwrap();
push_snapshot(&w.d1, "m1", REMOTE).unwrap();
// m2 is behind by one commit and clean.
fetch(&w.d2, REMOTE).unwrap();
let snaps = foreign_snapshots(&w.d2, "m2").unwrap();
assert_eq!(snaps.len(), 1);
assert_eq!(snaps[0].machine, "m1");
assert!(
foreign_snapshots(&w.d2, "m1").unwrap().is_empty(),
"own snapshots excluded"
);
assert_eq!(
apply_snapshot(&w.d2, &snaps[0], "m2", "t2").unwrap(),
Applied::Applied
);
assert_eq!(
fs::read_to_string(w.d2.join("a.txt")).unwrap(),
"1\nwip edit\n"
);
assert!(w.d2.join("new.txt").exists());
assert!(!w.d2.join("b.txt").exists(), "deletion applied");
assert!(!w.d2.join("s.env").exists(), "ignored file never travels");
// Arrives as plain working changes, nothing staged.
assert_eq!(
w.g2.run(&["diff", "--cached", "--name-only"]).unwrap(),
"",
"nothing staged"
);
// HEAD fast-forwarded to the snapshot's base.
assert_eq!(w.g2.run(&["rev-parse", "HEAD"]).unwrap(), snaps[0].based_on);
}
#[test]
fn snapshot_is_declined_when_target_has_local_work() {
let w = world();
fs::write(w.d1.join("x.txt"), "x\n").unwrap();
take(&w.d1, "m1", "t1").unwrap();
push_snapshot(&w.d1, "m1", REMOTE).unwrap();
fetch(&w.d2, REMOTE).unwrap();
let snap = foreign_snapshots(&w.d2, "m2").unwrap().remove(0);
fs::write(w.d2.join("mine.txt"), "m\n").unwrap();
assert!(matches!(
apply_snapshot(&w.d2, &snap, "m2", "t").unwrap(),
Applied::Declined(_)
));
assert!(!w.d2.join("x.txt").exists());
fs::remove_file(w.d2.join("mine.txt")).unwrap();
commit(&w.g2, "local.txt", "l\n");
assert!(matches!(
apply_snapshot(&w.d2, &snap, "m2", "t").unwrap(),
Applied::Declined(_)
));
}
#[test]
fn snapshot_does_not_clobber_untracked_files() {
let w = world();
fs::write(w.d1.join("clash.txt"), "from m1\n").unwrap();
take(&w.d1, "m1", "t1").unwrap();
push_snapshot(&w.d1, "m1", REMOTE).unwrap();
fetch(&w.d2, REMOTE).unwrap();
let snap = foreign_snapshots(&w.d2, "m2").unwrap().remove(0);
// Dirty (untracked) worktree is declined before anything is written.
fs::write(w.d2.join("clash.txt"), "from m2\n").unwrap();
assert!(matches!(
apply_snapshot(&w.d2, &snap, "m2", "t").unwrap(),
Applied::Declined(_)
));
assert_eq!(
fs::read_to_string(w.d2.join("clash.txt")).unwrap(),
"from m2\n"
);
}
#[test]
fn materializes_new_remote_branches_and_archives_gone_ones() {
let w = world();
// m2 becomes a bare+worktree repo.
let r = migrate(&w.d2, "m2", &w.base.join("bk"), "1").unwrap();
let root = w.d2.canonicalize().unwrap();
assert_eq!(materialize(&root, REMOTE).unwrap().len(), 0);
w.g1.run(&["checkout", "-q", "-b", "feat/x"]).unwrap();
commit(&w.g1, "x.txt", "x\n");
w.g1.run(&["push", "-q", "-u", "origin", "feat/x"]).unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
let created = materialize(&root, REMOTE).unwrap();
assert_eq!(created, vec![root.join("feat-x")]);
assert!(root.join("feat-x/x.txt").exists());
assert_eq!(state_of(&root.join("feat-x")), State::Synced);
assert!(materialize(&root, REMOTE).unwrap().is_empty(), "idempotent");
// Remote branch deleted: clean worktree is archived with a backup ref.
w.g1.run(&["push", "-q", "origin", "--delete", "feat/x"])
.unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
let out = archive_gone(&root, "m2", "t9").unwrap();
assert_eq!(out.len(), 1);
assert!(matches!(&out[0], Archived::Removed { branch, .. } if branch == "feat/x"));
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"])
.is_ok()
);
assert!(
bg.probe(&["rev-parse", "-q", "--verify", "refs/heads/feat/x"])
.unwrap()
.is_none()
);
}
#[test]
fn gone_branch_with_local_changes_is_kept_and_flagged() {
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/y"]).unwrap();
commit(&w.g1, "y.txt", "y\n");
w.g1.run(&["push", "-q", "-u", "origin", "feat/y"]).unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
materialize(&root, REMOTE).unwrap();
fs::write(root.join("feat-y/wip.txt"), "w\n").unwrap();
w.g1.run(&["push", "-q", "origin", "--delete", "feat/y"])
.unwrap();
fetch(&r.bare_dir, REMOTE).unwrap();
assert_eq!(
archive_gone(&root, "m2", "t").unwrap(),
vec![Archived::KeptDirty {
branch: "feat/y".into()
}]
);
assert!(root.join("feat-y/wip.txt").exists());
let _ = &w.remote;
}
fn state_of(p: &std::path::Path) -> State {
gitsync_core::inspect::state(p)
}