feat(core): add git runner, snapshots and state classification

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 11:58:43 +01:00
1 parent 5b3737ad3b
commit 753bd2c267
10 files changed
+462 -2

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
[package]
name = "gitsync-core"
description = "Sync engine for gitsync: snapshots, state classification"
edition.workspace = true
version.workspace = true
[dependencies]
+98
View File
@@ -0,0 +1,98 @@
//! Thin wrapper over the system `git` binary.
use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Debug)]
pub enum GitError {
Spawn(io::Error),
Failed {
args: Vec<String>,
code: Option<i32>,
stderr: String,
},
Other(String),
}
impl fmt::Display for GitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GitError::Spawn(e) => write!(f, "cannot run git: {e}"),
GitError::Failed { args, code, stderr } => {
write!(f, "git {} failed ({code:?}): {stderr}", args.join(" "))
}
GitError::Other(m) => write!(f, "{m}"),
}
}
}
impl std::error::Error for GitError {}
impl From<io::Error> for GitError {
fn from(e: io::Error) -> Self {
GitError::Spawn(e)
}
}
/// A git invocation context: a working directory plus extra environment.
#[derive(Debug, Clone)]
pub struct Git {
dir: PathBuf,
envs: Vec<(String, String)>,
}
impl Git {
pub fn new(dir: impl Into<PathBuf>) -> Self {
Git {
dir: dir.into(),
envs: Vec::new(),
}
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.envs.push((key.into(), value.into()));
self
}
fn command<S: AsRef<OsStr>>(&self, args: &[S]) -> Command {
let mut cmd = Command::new("git");
cmd.current_dir(&self.dir).args(args);
for (k, v) in &self.envs {
cmd.env(k, v);
}
cmd
}
/// Run git, returning trimmed stdout. Any non-zero exit is an error.
pub fn run(&self, args: &[&str]) -> Result<String, GitError> {
let out = self.command(args).output()?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
Err(GitError::Failed {
args: args.iter().map(|s| s.to_string()).collect(),
code: out.status.code(),
stderr: String::from_utf8_lossy(&out.stderr).trim().to_string(),
})
}
}
/// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`).
pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> {
let out = self.command(args).output()?;
if out.status.success() {
Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
))
} else {
Ok(None)
}
}
}
+5
View File
@@ -0,0 +1,5 @@
//! Sync engine core: git plumbing wrapper, snapshots and state classification.
pub mod git;
pub mod snapshot;
pub mod state;
+94
View File
@@ -0,0 +1,94 @@
//! Snapshots: capture the full worktree state into `refs/sync/<machine>/<branch>`
//! without touching the user's branch, index or history (section 7.1).
use crate::git::{Git, GitError};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Snapshot {
pub commit: String,
pub tree: String,
pub refname: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
Created(Snapshot),
/// The worktree tree equals the last snapshot's tree; nothing was written.
Unchanged(String),
}
pub fn ref_name(machine: &str, branch: &str) -> String {
format!("refs/sync/{machine}/{branch}")
}
struct TempIndex(PathBuf);
impl Drop for TempIndex {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn temp_index_path() -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!("gitsync-index-{}-{nanos}", std::process::id()))
}
/// Take a snapshot of `worktree` for `machine`. `message_stamp` is embedded in the
/// commit message (callers pass a timestamp; keeping it a parameter keeps this testable).
pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result<Outcome, GitError> {
let git = Git::new(worktree);
let gitdir = PathBuf::from(git.run(&["rev-parse", "--absolute-git-dir"])?);
let branch = git
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD: cannot snapshot".into()))?;
let refname = ref_name(machine, &branch);
// Work on a copy of the real index so the user's index is never modified.
let tmp = TempIndex(temp_index_path());
let real_index = gitdir.join("index");
if real_index.exists() {
std::fs::copy(&real_index, &tmp.0)?;
}
let snap = git
.clone()
.with_env("GIT_INDEX_FILE", tmp.0.to_string_lossy())
.with_env("GIT_AUTHOR_NAME", "gitsync")
.with_env("GIT_AUTHOR_EMAIL", "gitsync@localhost")
.with_env("GIT_COMMITTER_NAME", "gitsync")
.with_env("GIT_COMMITTER_EMAIL", "gitsync@localhost");
snap.run(&["add", "-A"])?;
let tree = snap.run(&["write-tree"])?;
let prev = snap.probe(&["rev-parse", "-q", "--verify", &refname])?;
if let Some(p) = &prev {
let prev_tree = snap.run(&["rev-parse", &format!("{p}^{{tree}}")])?;
if prev_tree == tree {
return Ok(Outcome::Unchanged(p.clone()));
}
}
let head = snap.probe(&["rev-parse", "-q", "--verify", "HEAD"])?;
let message = format!("gitsync snapshot {machine} {message_stamp}");
let mut args: Vec<&str> = vec!["commit-tree", &tree];
if let Some(h) = &head {
args.extend(["-p", h]);
}
if let Some(p) = &prev {
args.extend(["-p", p]);
}
args.extend(["-m", &message]);
let commit = snap.run(&args)?;
snap.run(&["update-ref", &refname, &commit])?;
Ok(Outcome::Created(Snapshot {
commit,
tree,
refname,
}))
}
+102
View File
@@ -0,0 +1,102 @@
//! Pure classification of a worktree's sync state (section 7.4 of the plan).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
/// Uncommitted changes (tracked, staged or untracked, minus ignored).
pub dirty: bool,
/// Local branch has commits the remote branch lacks.
pub ahead: bool,
/// Remote branch has commits the local branch lacks.
pub behind: bool,
/// Last operation failed (auth, network, hook failure...).
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum State {
Synced,
Dirty,
Ahead,
Behind,
/// Remote moved but the worktree has local edits: never touched.
BehindDirty,
Diverged,
Error(String),
}
pub fn classify(f: &Facts) -> State {
if let Some(e) = &f.error {
return State::Error(e.clone());
}
match (f.ahead, f.behind, f.dirty) {
(true, true, _) => State::Diverged,
(false, true, true) => State::BehindDirty,
(false, true, false) => State::Behind,
(true, false, _) => State::Ahead,
(false, false, true) => State::Dirty,
(false, false, false) => State::Synced,
}
}
/// What the receive step may do to the files of a worktree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiveAction {
FastForward,
Skip,
}
/// Only a clean, strictly-behind worktree is ever fast-forwarded.
pub fn receive_action(state: &State) -> ReceiveAction {
match state {
State::Behind => ReceiveAction::FastForward,
_ => ReceiveAction::Skip,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn f(dirty: bool, ahead: bool, behind: bool) -> Facts {
Facts {
dirty,
ahead,
behind,
error: None,
}
}
#[test]
fn classifies_every_combination() {
assert_eq!(classify(&f(false, false, false)), State::Synced);
assert_eq!(classify(&f(true, false, false)), State::Dirty);
assert_eq!(classify(&f(false, true, false)), State::Ahead);
assert_eq!(classify(&f(true, true, false)), State::Ahead);
assert_eq!(classify(&f(false, false, true)), State::Behind);
assert_eq!(classify(&f(true, false, true)), State::BehindDirty);
assert_eq!(classify(&f(false, true, true)), State::Diverged);
assert_eq!(classify(&f(true, true, true)), State::Diverged);
}
#[test]
fn error_wins() {
let mut x = f(true, true, true);
x.error = Some("auth".into());
assert_eq!(classify(&x), State::Error("auth".into()));
}
#[test]
fn only_clean_behind_fast_forwards() {
for s in [
State::Synced,
State::Dirty,
State::Ahead,
State::BehindDirty,
State::Diverged,
State::Error("x".into()),
] {
assert_eq!(receive_action(&s), ReceiveAction::Skip);
}
assert_eq!(receive_action(&State::Behind), ReceiveAction::FastForward);
}
}
+137
View File
@@ -0,0 +1,137 @@
use gitsync_core::git::Git;
use gitsync_core::snapshot::{Outcome, take};
use std::fs;
use std::path::{Path, PathBuf};
fn tmpdir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!(
"gitsync-test-{tag}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&p).unwrap();
p
}
fn repo(dir: &Path) -> Git {
let g = Git::new(dir);
g.run(&["init", "-q", "-b", "main"]).unwrap();
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
fs::write(dir.join("a.txt"), "hi\n").unwrap();
fs::write(dir.join(".gitignore"), "*.env\n").unwrap();
g.run(&["add", "."]).unwrap();
g.run(&["commit", "-qm", "init"]).unwrap();
g
}
fn files(g: &Git, rev: &str) -> Vec<String> {
g.run(&["ls-tree", "-r", "--name-only", rev])
.unwrap()
.lines()
.map(String::from)
.collect()
}
#[test]
fn snapshot_captures_wip_without_touching_user_state() {
let dir = tmpdir("snap");
let g = repo(&dir);
fs::write(dir.join("a.txt"), "hi\nedit\n").unwrap();
fs::write(dir.join("new.txt"), "untracked\n").unwrap();
fs::write(dir.join("secret.env"), "x\n").unwrap();
g.run(&["add", "a.txt"]).unwrap(); // staged edit
let head_before = g.run(&["rev-parse", "HEAD"]).unwrap();
let status_before = g.run(&["status", "--porcelain"]).unwrap();
let out = take(&dir, "desktop", "t1").unwrap();
let Outcome::Created(s) = out else {
panic!("expected Created")
};
assert_eq!(s.refname, "refs/sync/desktop/main");
let f = files(&g, &s.commit);
assert!(f.contains(&"new.txt".to_string()), "untracked captured");
assert!(!f.contains(&"secret.env".to_string()), "ignored excluded");
assert_eq!(
g.run(&["show", &format!("{}:a.txt", s.commit)]).unwrap(),
"hi\nedit"
);
// User's branch, index and worktree are untouched.
assert_eq!(g.run(&["rev-parse", "HEAD"]).unwrap(), head_before);
assert_eq!(g.run(&["status", "--porcelain"]).unwrap(), status_before);
assert_eq!(
g.run(&["rev-parse", "refs/heads/main"]).unwrap(),
head_before
);
// First parent is HEAD.
assert_eq!(
g.run(&["rev-parse", &format!("{}^1", s.commit)]).unwrap(),
head_before
);
}
#[test]
fn unchanged_tree_is_a_noop_and_changes_chain_snapshots() {
let dir = tmpdir("chain");
let g = repo(&dir);
fs::write(dir.join("w.txt"), "1\n").unwrap();
let Outcome::Created(first) = take(&dir, "m", "t1").unwrap() else {
panic!()
};
assert_eq!(
take(&dir, "m", "t2").unwrap(),
Outcome::Unchanged(first.commit.clone())
);
fs::write(dir.join("w.txt"), "2\n").unwrap();
let Outcome::Created(second) = take(&dir, "m", "t3").unwrap() else {
panic!()
};
assert_eq!(
g.run(&["rev-parse", &format!("{}^2", second.commit)])
.unwrap(),
first.commit
);
}
#[test]
fn works_in_a_linked_worktree_of_a_bare_repo() {
let base = tmpdir("bare");
let src = base.join("src");
fs::create_dir_all(&src).unwrap();
repo(&src);
let bare = base.join("repo/.bare");
fs::create_dir_all(bare.parent().unwrap()).unwrap();
Git::new(&base)
.run(&[
"clone",
"-q",
"--bare",
src.to_str().unwrap(),
bare.to_str().unwrap(),
])
.unwrap();
let bg = Git::new(&bare);
let wt = base.join("repo/main");
bg.run(&["worktree", "add", "-q", wt.to_str().unwrap(), "main"])
.unwrap();
fs::write(wt.join("wip.txt"), "wip\n").unwrap();
let Outcome::Created(s) = take(&wt, "laptop", "t").unwrap() else {
panic!()
};
assert!(files(&bg, &s.commit).contains(&"wip.txt".to_string()));
}
#[test]
fn detached_head_is_an_error() {
let dir = tmpdir("detached");
let g = repo(&dir);
g.run(&["checkout", "-q", "--detach"]).unwrap();
assert!(take(&dir, "m", "t").is_err());
}