chore: rename project to grove and add MIT license

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 12:52:25 +01:00
1 parent 126acb4b57
commit c935d779e1
29 files changed
+99 -76

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
[package]
name = "grove-core"
description = "Sync engine for grove: snapshots, state classification"
edition.workspace = true
version.workspace = true
[dependencies]
serde = { version = "1.0.229", features = ["derive"] }
toml = "1.2.1"
+280
View File
@@ -0,0 +1,280 @@
//! `config.toml` model, loading and validation (section 6 of the plan).
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Config {
pub machine: Machine,
pub root: Root,
#[serde(default)]
pub providers: BTreeMap<String, Provider>,
#[serde(default)]
pub groups: Vec<Group>,
#[serde(default)]
pub sync: Sync,
pub config_repo: Option<ConfigRepo>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Machine {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Root {
pub path: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderKind {
Gitea,
Forgejo,
Github,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Provider {
pub kind: ProviderKind,
pub url: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Layout {
#[default]
BareWorktrees,
Plain,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Group {
pub name: String,
pub primary: String,
#[serde(default)]
pub mirror_to: Vec<String>,
#[serde(default)]
pub layout: Layout,
#[serde(default = "yes")]
pub auto_materialize: bool,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Sync {
#[serde(default = "default_debounce")]
pub snapshot_debounce_ms: u64,
#[serde(default = "default_fetch")]
pub fetch_interval_s: u64,
#[serde(default)]
pub ignore_extra: Vec<String>,
}
impl Default for Sync {
fn default() -> Self {
Sync {
snapshot_debounce_ms: default_debounce(),
fetch_interval_s: default_fetch(),
ignore_extra: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ConfigRepo {
pub provider: String,
pub name: String,
}
fn yes() -> bool {
true
}
fn default_debounce() -> u64 {
2000
}
fn default_fetch() -> u64 {
60
}
#[derive(Debug)]
pub enum ConfigError {
Io(PathBuf, std::io::Error),
Parse(String),
Invalid(String),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Io(p, e) => write!(f, "cannot read {}: {e}", p.display()),
ConfigError::Parse(m) => write!(f, "invalid config syntax: {m}"),
ConfigError::Invalid(m) => write!(f, "invalid config: {m}"),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
pub fn parse(text: &str) -> Result<Config, ConfigError> {
let cfg: Config = toml::from_str(text).map_err(|e| ConfigError::Parse(e.to_string()))?;
cfg.validate()?;
Ok(cfg)
}
pub fn load(path: &Path) -> Result<Config, ConfigError> {
let text =
std::fs::read_to_string(path).map_err(|e| ConfigError::Io(path.to_path_buf(), e))?;
Config::parse(&text)
}
/// Default location: `$XDG_CONFIG_HOME/grove/config.toml` or `~/.config/...`.
pub fn default_path() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
Some(base.join("grove/config.toml"))
}
/// Local state directory: `$XDG_STATE_HOME/grove` or `~/.local/state/grove`.
pub fn state_dir() -> Option<PathBuf> {
let base = std::env::var_os("XDG_STATE_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/state")))?;
Some(base.join("grove"))
}
/// `root.path` with a leading `~` expanded.
pub fn root_path(&self) -> PathBuf {
expand_home(&self.root.path)
}
fn validate(&self) -> Result<(), ConfigError> {
let bad = |m: String| Err(ConfigError::Invalid(m));
// The machine name is embedded in ref names: keep it ref-safe.
let n = &self.machine.name;
if n.is_empty()
|| !n
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return bad(format!(
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
));
}
for g in &self.groups {
if !self.providers.contains_key(&g.primary) {
return bad(format!(
"group {:?}: unknown primary provider {:?}",
g.name, g.primary
));
}
if let Some(m) = g
.mirror_to
.iter()
.find(|m| !self.providers.contains_key(*m))
{
return bad(format!("group {:?}: unknown mirror provider {m:?}", g.name));
}
if g.mirror_to.contains(&g.primary) {
return bad(format!(
"group {:?}: primary cannot also be a mirror target",
g.name
));
}
}
if let Some(c) = &self.config_repo
&& !self.providers.contains_key(&c.provider)
{
return bad(format!("config_repo: unknown provider {:?}", c.provider));
}
Ok(())
}
}
fn expand_home(p: &str) -> PathBuf {
match (p.strip_prefix("~/"), std::env::var_os("HOME")) {
(Some(rest), Some(home)) => PathBuf::from(home).join(rest),
_ if p == "~" => std::env::var_os("HOME").map_or_else(|| PathBuf::from(p), PathBuf::from),
_ => PathBuf::from(p),
}
}
#[cfg(test)]
mod tests {
use super::*;
const FULL: &str = r#"
[machine]
name = "desktop"
[root]
path = "~/Hacking"
[providers.gitea-main]
kind = "gitea"
url = "https://git.example.com"
[providers.github]
kind = "github"
[[groups]]
name = "work"
primary = "gitea-main"
mirror_to = ["github"]
[sync]
fetch_interval_s = 30
[config_repo]
provider = "gitea-main"
name = "grove-config"
"#;
#[test]
fn parses_full_config_with_defaults() {
let c = Config::parse(FULL).unwrap();
assert_eq!(c.machine.name, "desktop");
assert_eq!(c.groups[0].layout, Layout::BareWorktrees);
assert!(c.groups[0].auto_materialize);
assert_eq!(c.sync.fetch_interval_s, 30);
assert_eq!(c.sync.snapshot_debounce_ms, 2000);
assert_eq!(c.providers["github"].kind, ProviderKind::Github);
}
#[test]
fn minimal_config_is_valid() {
let c = Config::parse("[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n").unwrap();
assert!(c.groups.is_empty());
assert_eq!(c.root_path(), PathBuf::from("/x"));
}
#[test]
fn rejects_unsafe_machine_name() {
for n in ["", "a/b", "a b", "a..b"] {
let t = format!("[machine]\nname=\"{n}\"\n[root]\npath=\"/x\"\n");
assert!(
matches!(Config::parse(&t), Err(ConfigError::Invalid(_))),
"{n:?}"
);
}
}
#[test]
fn rejects_unknown_providers_and_self_mirror() {
let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n";
let unknown = format!("{base}[[groups]]\nname=\"g\"\nprimary=\"nope\"\n");
assert!(matches!(
Config::parse(&unknown),
Err(ConfigError::Invalid(_))
));
let selfm = format!("{base}[[groups]]\nname=\"g\"\nprimary=\"p\"\nmirror_to=[\"p\"]\n");
assert!(matches!(
Config::parse(&selfm),
Err(ConfigError::Invalid(_))
));
}
#[test]
fn rejects_bad_syntax_and_unknown_kind() {
assert!(matches!(Config::parse("["), Err(ConfigError::Parse(_))));
let t = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitlab\"\n";
assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_))));
}
}
+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)
}
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Read-only inspection of worktrees: gathers `Facts` and classifies them.
use crate::git::{Git, GitError};
use crate::state::{Facts, State, classify};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Worktree {
pub path: PathBuf,
/// `None` for detached HEAD.
pub branch: Option<String>,
}
/// Non-bare worktrees of the repository containing `path` (adopts foreign ones too).
pub fn worktrees(path: &Path) -> Result<Vec<Worktree>, GitError> {
let out = Git::new(path).run(&["worktree", "list", "--porcelain"])?;
let mut list = Vec::new();
for block in out.split("\n\n").filter(|b| !b.trim().is_empty()) {
let mut wt = None;
let mut branch = None;
let mut bare = false;
for line in block.lines() {
if let Some(p) = line.strip_prefix("worktree ") {
wt = Some(PathBuf::from(p));
} else if let Some(b) = line.strip_prefix("branch refs/heads/") {
branch = Some(b.to_string());
} else if line == "bare" {
bare = true;
}
}
if let (Some(path), false) = (wt, bare) {
list.push(Worktree { path, branch });
}
}
Ok(list)
}
/// Collect facts for one worktree. Without an upstream, ahead/behind are false.
pub fn facts(worktree: &Path) -> Result<Facts, GitError> {
let git = Git::new(worktree);
let dirty = !git.run(&["status", "--porcelain"])?.is_empty();
let (mut ahead, mut behind) = (false, false);
if git
.probe(&["rev-parse", "--abbrev-ref", "@{upstream}"])?
.is_some()
{
let counts = git.run(&["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])?;
let mut it = counts.split_whitespace();
ahead = it.next().is_some_and(|n| n != "0");
behind = it.next().is_some_and(|n| n != "0");
}
Ok(Facts {
dirty,
ahead,
behind,
error: None,
})
}
/// Classify a worktree; git failures become `State::Error` instead of propagating.
pub fn state(worktree: &Path) -> State {
match facts(worktree) {
Ok(f) => classify(&f),
Err(e) => State::Error(e.to_string()),
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Branch name to directory name mapping (section 5 of the plan).
/// Map a branch name to a visible, filesystem-safe directory name that is not in `taken`.
/// `/` becomes `-`; collisions get a short deterministic suffix derived from the branch.
pub fn dir_name(branch: &str, taken: &[&str]) -> String {
let mut base: String = branch
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
c
} else {
'-'
}
})
.collect();
base = base.trim_start_matches('.').to_string();
if base.is_empty() {
base = "branch".to_string();
}
if !taken.contains(&base.as_str()) {
return base;
}
let suffixed = format!("{base}-{:06x}", fnv1a(branch) & 0xff_ffff);
if !taken.contains(&suffixed.as_str()) {
return suffixed;
}
(2..)
.map(|n| format!("{suffixed}-{n}"))
.find(|c| !taken.contains(&c.as_str()))
.expect("unbounded range")
}
fn fnv1a(s: &str) -> u32 {
s.bytes().fold(0x811c_9dc5u32, |h, b| {
(h ^ u32::from(b)).wrapping_mul(0x0100_0193)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flattens_slashes() {
assert_eq!(dir_name("feat/login", &[]), "feat-login");
assert_eq!(dir_name("main", &[]), "main");
}
#[test]
fn collisions_get_a_deterministic_suffix() {
let a = dir_name("feat/x", &["feat-x"]);
assert_ne!(a, "feat-x");
assert!(a.starts_with("feat-x-"));
assert_eq!(a, dir_name("feat/x", &["feat-x"]));
// Two branches mapping to the same base end up different.
let first = dir_name("feat/x", &[]);
let second = dir_name("feat-x", &[first.as_str()]);
assert_ne!(first, second);
}
#[test]
fn reserved_names_are_avoided() {
assert_ne!(dir_name(".bare", &[".bare"]), ".bare");
assert!(!dir_name("..", &[]).starts_with('.'));
assert!(!dir_name("", &[]).is_empty());
}
/// Fuzz-style invariants with a tiny LCG (no extra dependency).
#[test]
fn invariants_hold_for_random_names() {
let alphabet: Vec<char> = "ab/._- é\\:*?\"<>|0Z".chars().collect();
let mut seed = 0x1234_5678_u64;
let mut taken: Vec<String> = vec![".bare".into(), ".grove-stage".into()];
for _ in 0..2000 {
let len = {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(seed >> 60) as usize
};
let name: String = (0..len)
.map(|_| {
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
alphabet[(seed >> 33) as usize % alphabet.len()]
})
.collect();
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
let d = dir_name(&name, &refs);
assert!(!d.is_empty());
assert!(!d.contains('/'));
assert!(!d.starts_with('.'));
assert!(!taken.contains(&d), "{name:?} -> {d:?} already taken");
taken.push(d);
}
}
}
+11
View File
@@ -0,0 +1,11 @@
//! Sync engine core: git plumbing wrapper, config, snapshots and state classification.
pub mod config;
pub mod git;
pub mod inspect;
pub mod layout;
pub mod migrate;
pub mod receive;
pub mod snapshot;
pub mod state;
pub mod sync;
+458
View File
@@ -0,0 +1,458 @@
//! Migrate a plain clone to the bare + worktree layout in place (section 5).
//!
//! Safety: a full tar backup and a backup ref are taken first; the observable state
//! (`status --ignored`, stashes, refs) is compared before and after; any failure after
//! the first modification triggers a rollback to the original layout.
use crate::git::{Git, GitError};
use crate::layout::dir_name;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
const BARE: &str = ".bare";
const STAGE: &str = ".grove-stage";
#[derive(Debug)]
pub enum MigrateError {
/// Pre-flight check failed; nothing was touched.
Refused(String),
Git(GitError),
Io(io::Error),
/// A step failed after the backup was taken.
Failed {
cause: String,
rolled_back: bool,
backup: PathBuf,
},
}
impl fmt::Display for MigrateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MigrateError::Refused(m) => write!(f, "refused: {m}"),
MigrateError::Git(e) => write!(f, "{e}"),
MigrateError::Io(e) => write!(f, "io error: {e}"),
MigrateError::Failed {
cause,
rolled_back,
backup,
} => write!(
f,
"migration failed: {cause}; {}; backup at {}",
if *rolled_back {
"original layout restored"
} else {
"ROLLBACK INCOMPLETE, restore from the backup"
},
backup.display()
),
}
}
}
impl std::error::Error for MigrateError {}
impl From<GitError> for MigrateError {
fn from(e: GitError) -> Self {
MigrateError::Git(e)
}
}
impl From<io::Error> for MigrateError {
fn from(e: io::Error) -> Self {
MigrateError::Io(e)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Report {
pub bare_dir: PathBuf,
pub worktree: PathBuf,
pub branch: String,
pub backup_tar: PathBuf,
pub backup_ref: String,
}
/// Steps after which a failure can be injected (tests only).
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Staged,
GitMoved,
WorktreeAdded,
Filled,
IndexMoved,
Verified,
}
#[derive(Default)]
struct Progress {
staged: bool,
git_moved: bool,
wt_dir: Option<PathBuf>,
wt_meta: Option<PathBuf>,
filled: bool,
index_moved: bool,
/// Original `core.worktree`, restored on rollback.
orig_core_worktree: Option<String>,
}
#[derive(Debug, PartialEq, Eq)]
struct Observed {
status: String,
stash: String,
refs: String,
}
fn observe(git: &Git) -> Result<Observed, GitError> {
let refs = git.run(&["for-each-ref", "--format=%(refname) %(objectname)"])?;
let refs = refs
.lines()
.filter(|l| !l.starts_with("refs/sync-backup/"))
.collect::<Vec<_>>()
.join("\n");
Ok(Observed {
status: git.run(&["status", "--porcelain", "--ignored"])?,
stash: git.run(&["stash", "list", "--format=%H"])?,
refs,
})
}
fn s<E: fmt::Display>(e: E) -> String {
e.to_string()
}
/// Migrate the plain repo whose root is `repo`. `stamp` must be filesystem-safe.
pub fn migrate(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
) -> Result<Report, MigrateError> {
migrate_inner(repo, machine, backup_dir, stamp, None)
}
#[doc(hidden)]
pub fn migrate_failing_after(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
step: Step,
) -> Result<Report, MigrateError> {
migrate_inner(repo, machine, backup_dir, stamp, Some(step))
}
fn refuse<T>(m: impl Into<String>) -> Result<T, MigrateError> {
Err(MigrateError::Refused(m.into()))
}
fn preflight(root: &Path) -> Result<String, MigrateError> {
let dotgit = root.join(".git");
if root.join(BARE).exists() {
return refuse("already migrated (.bare exists)");
}
if root.join(STAGE).exists() {
return refuse(format!(
"{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() {
return refuse("not a plain clone (.git is not a directory)");
}
let git = Git::new(root);
let top = PathBuf::from(git.run(&["rev-parse", "--show-toplevel"])?).canonicalize()?;
if top != root {
return refuse("path is not the repository root");
}
let Some(branch) = git.probe(&["symbolic-ref", "--short", "-q", "HEAD"])? else {
return refuse("detached HEAD: check out a branch first");
};
if git
.probe(&["rev-parse", "-q", "--verify", "HEAD"])?
.is_none()
{
return refuse("repository has no commits yet");
}
for f in [
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
] {
if dotgit.join(f).exists() {
return refuse(format!(
"operation in progress ({f}): finish or abort it first"
));
}
}
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");
}
if git
.run(&["worktree", "list", "--porcelain"])?
.matches("worktree ")
.count()
> 1
{
return refuse("repository already has linked worktrees; not supported yet");
}
Ok(branch)
}
fn backup(
root: &Path,
git: &Git,
machine: &str,
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) {
return refuse("backup directory must be outside the repository");
}
let name = root
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "repo".into());
let tar = backup_dir.join(format!("{name}-{stamp}.tar"));
let parent = root
.parent()
.ok_or_else(|| MigrateError::Refused("repo has no parent".into()))?;
let out = Command::new("tar")
.arg("-cf")
.arg(&tar)
.arg("-C")
.arg(parent)
.arg(&name)
.output()?;
if !out.status.success() {
let _ = fs::remove_file(&tar);
return refuse(format!(
"tar backup failed: {}",
String::from_utf8_lossy(&out.stderr)
));
}
let backup_ref = format!("refs/sync-backup/{machine}/{stamp}/add");
git.run(&["update-ref", &backup_ref, "HEAD"])?;
Ok((tar, backup_ref))
}
fn migrate_inner(
repo: &Path,
machine: &str,
backup_dir: &Path,
stamp: &str,
inject: Option<Step>,
) -> Result<Report, MigrateError> {
let root = repo.canonicalize()?;
let branch = preflight(&root)?;
let git = Git::new(&root);
let before = observe(&git)?;
let (backup_tar, backup_ref) = backup(&root, &git, machine, backup_dir, stamp)?;
let dir = dir_name(&branch, &[BARE, STAGE]);
let mut p = Progress::default();
match run_steps(&root, &branch, &dir, &before, &mut p, inject) {
Ok(worktree) => Ok(Report {
bare_dir: root.join(BARE),
worktree,
branch,
backup_tar,
backup_ref,
}),
Err(cause) => {
let rb = rollback(&root, &p);
let (cause, rolled_back) = match rb {
Ok(()) => (cause, true),
Err(e) => (format!("{cause}; rollback error: {e}"), false),
};
Err(MigrateError::Failed {
cause,
rolled_back,
backup: backup_tar,
})
}
}
}
fn move_entries(from: &Path, to: &Path, skip: &[&str]) -> io::Result<()> {
for entry in fs::read_dir(from)? {
let entry = entry?;
let name = entry.file_name();
if skip.iter().any(|k| name == *k) {
continue;
}
fs::rename(entry.path(), to.join(&name))?;
}
Ok(())
}
fn hook(inject: Option<Step>, at: Step) -> Result<(), String> {
if inject == Some(at) {
Err(format!("injected failure after {at:?}"))
} else {
Ok(())
}
}
fn run_steps(
root: &Path,
branch: &str,
dir: &str,
before: &Observed,
p: &mut Progress,
inject: Option<Step>,
) -> Result<PathBuf, String> {
let stage = root.join(STAGE);
let root_git = Git::new(root);
// 1. Move everything except .git into a staging dir.
fs::create_dir(&stage).map_err(s)?;
p.staged = true;
move_entries(root, &stage, &[".git", STAGE]).map_err(s)?;
hook(inject, Step::Staged)?;
// 2. .git -> .bare, make it bare.
fs::rename(root.join(".git"), root.join(BARE)).map_err(s)?;
p.git_moved = true;
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)?;
hook(inject, Step::GitMoved)?;
// 3. Register the worktree without checking anything out.
let wt = root.join(dir);
p.wt_dir = Some(wt.clone());
let wt_str = wt.to_string_lossy().into_owned();
root_git
.run(&[
"--git-dir",
BARE,
"worktree",
"add",
"--no-checkout",
&wt_str,
branch,
])
.map_err(s)?;
let pointer = fs::read_to_string(wt.join(".git")).map_err(s)?;
let meta = pointer
.trim()
.strip_prefix("gitdir: ")
.map(PathBuf::from)
.ok_or("unexpected .git file in new worktree")?;
p.wt_meta = Some(meta.clone());
hook(inject, Step::WorktreeAdded)?;
// 4. Put the user's files into the worktree.
p.filled = true;
move_entries(&stage, &wt, &[]).map_err(s)?;
hook(inject, Step::Filled)?;
// 5. Carry over the index so staged changes survive.
let old_index = root.join(BARE).join("index");
if old_index.exists() {
fs::rename(&old_index, meta.join("index")).map_err(s)?;
p.index_moved = true;
}
hook(inject, Step::IndexMoved)?;
// 6. Verify nothing observable changed.
let after = observe(&Git::new(&wt)).map_err(s)?;
if &after != before {
let what = if after.status != before.status {
"status"
} else if after.stash != before.stash {
"stashes"
} else {
"refs"
};
return Err(format!(
"verification failed: {what} differ after migration"
));
}
hook(inject, Step::Verified)?;
fs::remove_dir(&stage).map_err(s)?;
Ok(wt)
}
fn rollback(root: &Path, p: &Progress) -> Result<(), String> {
let stage = root.join(STAGE);
let bare = root.join(BARE);
if p.index_moved
&& let Some(meta) = &p.wt_meta
{
fs::rename(meta.join("index"), bare.join("index")).map_err(s)?;
}
if let Some(wt) = &p.wt_dir
&& wt.exists()
{
if p.filled {
fs::create_dir_all(&stage).map_err(s)?;
move_entries(wt, &stage, &[".git"]).map_err(s)?;
}
// Only delete the worktree dir if user files are no longer in it.
let leftovers = fs::read_dir(wt)
.map_err(s)?
.filter_map(Result::ok)
.any(|e| e.file_name() != ".git");
if leftovers {
return Err(format!(
"{} still holds user files; not deleting",
wt.display()
));
}
fs::remove_dir_all(wt).map_err(s)?;
}
if let Some(meta) = &p.wt_meta
&& meta.exists()
{
fs::remove_dir_all(meta).map_err(s)?;
}
if p.git_moved {
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() {
move_entries(&stage, root, &[]).map_err(s)?;
fs::remove_dir(&stage).map_err(s)?;
}
Ok(())
}
+346
View File
@@ -0,0 +1,346 @@
//! 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";
/// 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.
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),
/// 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.
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 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"])?;
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 })
}
#[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;
}
// 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(),
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);
}
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 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"])?;
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);
// 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)",
"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;
};
// 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 = 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])?;
out.push(Archived::Removed {
branch: branch.to_string(),
backup_ref: bref,
});
}
Ok(out)
}
+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!("grove-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", "grove")
.with_env("GIT_AUTHOR_EMAIL", "grove@localhost")
.with_env("GIT_COMMITTER_NAME", "grove")
.with_env("GIT_COMMITTER_EMAIL", "grove@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!("grove 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);
}
}
+150
View File
@@ -0,0 +1,150 @@
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive.
//! Failures of individual steps are reported per worktree and never abort the whole pass.
use crate::git::{Git, GitError};
use crate::inspect::{facts, state, worktrees};
use crate::receive::{
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
materialize, push_snapshot, receive,
};
use crate::snapshot::{Outcome, ref_name, take};
use crate::state::State;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct Options {
pub machine: String,
pub stamp: String,
pub remote: String,
/// Skip every network operation (fetch/push).
pub offline: bool,
/// Create worktrees for new remote branches and archive gone ones (bare layout only).
pub materialize: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct WorktreeReport {
pub path: PathBuf,
pub branch: Option<String>,
pub snapshot: Option<&'static str>,
pub received: Option<Received>,
pub applied: Option<(String, Applied)>,
pub state: State,
pub errors: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SyncReport {
pub fetch_error: Option<String>,
pub materialized: Vec<PathBuf>,
pub archived: Vec<Archived>,
pub worktrees: Vec<WorktreeReport>,
}
/// Git dir to operate on: `<path>/.bare` for the bare layout, `path` otherwise.
pub fn git_dir_for(path: &Path) -> PathBuf {
let bare = path.join(".bare");
if bare.is_dir() {
bare
} else {
path.to_path_buf()
}
}
pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
let gitdir = git_dir_for(path);
let bare_layout = gitdir != path;
let mut rep = SyncReport::default();
if !o.offline
&& let Err(e) = fetch(&gitdir, &o.remote)
{
rep.fetch_error = Some(e.to_string());
}
if bare_layout && o.materialize && rep.fetch_error.is_none() {
match archive_gone(path, &o.machine, &o.stamp) {
Ok(a) => rep.archived = a,
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
}
match materialize(path, &o.remote) {
Ok(m) => rep.materialized = m,
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
}
}
for wt in worktrees(&gitdir)? {
let mut r = WorktreeReport {
path: wt.path.clone(),
branch: wt.branch.clone(),
snapshot: None,
received: None,
applied: None,
state: State::Synced,
errors: Vec::new(),
};
if let Some(branch) = &wt.branch {
sync_worktree(&mut r, branch, o, rep.fetch_error.is_none());
}
r.state = state(&wt.path);
rep.worktrees.push(r);
}
Ok(rep)
}
fn sync_worktree(r: &mut WorktreeReport, branch: &str, o: &Options, fetched: bool) {
let path = r.path.clone();
let g = Git::new(&path);
let own_ref = ref_name(&o.machine, branch);
let has_ref = matches!(
g.probe(&["rev-parse", "-q", "--verify", &own_ref]),
Ok(Some(_))
);
let dirty = match facts(&path) {
Ok(f) => f.dirty,
Err(e) => {
r.errors.push(e.to_string());
return;
}
};
// A clean worktree still refreshes an existing snapshot so a stale WIP never lingers.
if dirty || has_ref {
match take(&path, &o.machine, &o.stamp) {
Ok(Outcome::Created(_)) => r.snapshot = Some("created"),
Ok(Outcome::Unchanged(_)) => r.snapshot = Some("unchanged"),
Err(e) => {
r.errors.push(format!("snapshot: {e}"));
return;
}
}
if !o.offline
&& let Err(e) = push_snapshot(&path, &o.machine, &o.remote)
{
r.errors.push(format!("push snapshot: {e}"));
}
}
if !fetched {
return;
}
match receive(&path, &o.machine, &o.stamp) {
Ok(x) => r.received = Some(x),
Err(e) => {
r.errors.push(format!("receive: {e}"));
return;
}
}
match foreign_snapshots(&path, &o.machine) {
Ok(snaps) => {
for s in snaps {
match apply_snapshot(&path, &s, &o.machine, &o.stamp) {
Ok(Applied::Applied) => {
r.applied = Some((s.machine, Applied::Applied));
break;
}
Ok(other) => r.applied = Some((s.machine, other)),
Err(e) => r.errors.push(format!("apply: {e}")),
}
}
}
Err(e) => r.errors.push(format!("snapshots: {e}")),
}
}
+51
View File
@@ -0,0 +1,51 @@
#![allow(dead_code)]
use grove_core::git::Git;
use std::fs;
use std::path::{Path, PathBuf};
pub fn tmpdir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!(
"grove-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
}
pub fn init(dir: &Path) -> Git {
fs::create_dir_all(dir).unwrap();
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();
g
}
pub fn commit(g: &Git, file: &str, body: &str) {
let path = g.dir().join(file);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, body).unwrap();
g.run(&["add", "."]).unwrap();
g.run(&["commit", "-qm", file]).unwrap();
}
/// A repo with history, a second branch, a stash, staged, modified, untracked and ignored files.
pub fn messy_repo(dir: &Path) -> Git {
let g = init(dir);
commit(&g, ".gitignore", "*.env\n");
commit(&g, "src/a.txt", "one\n");
commit(&g, "b.txt", "b\n");
g.run(&["branch", "other"]).unwrap();
fs::write(dir.join("b.txt"), "b changed for stash\n").unwrap();
g.run(&["stash", "push", "-q"]).unwrap();
fs::write(dir.join("src/a.txt"), "one\nmodified\n").unwrap();
fs::write(dir.join("staged.txt"), "staged\n").unwrap();
g.run(&["add", "staged.txt"]).unwrap();
fs::write(dir.join("untracked.txt"), "u\n").unwrap();
fs::write(dir.join("secret.env"), "s\n").unwrap();
g
}
+117
View File
@@ -0,0 +1,117 @@
use grove_core::git::Git;
use grove_core::inspect::{state, worktrees};
use grove_core::state::State;
use std::fs;
use std::path::{Path, PathBuf};
fn tmpdir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!(
"grove-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 commit(g: &Git, dir: &Path, file: &str, body: &str) {
fs::write(dir.join(file), body).unwrap();
g.run(&["add", "."]).unwrap();
g.run(&["commit", "-qm", file]).unwrap();
}
/// A bare "remote" plus two clones (two machines) tracking its `main`.
fn setup() -> (Git, PathBuf, Git, PathBuf) {
let base = tmpdir("inspect");
let remote = base.join("remote.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let mut out = Vec::new();
for name in ["m1", "m2"] {
let dir = base.join(name);
Git::new(&base)
.run(&[
"clone",
"-q",
remote.to_str().unwrap(),
dir.to_str().unwrap(),
])
.unwrap();
let g = Git::new(&dir);
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
out.push((g, dir));
}
let (g2, d2) = out.pop().unwrap();
let (g1, d1) = out.pop().unwrap();
commit(&g1, &d1, "a.txt", "1\n");
g1.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
g2.run(&["pull", "-q", "origin", "main"]).unwrap();
g2.run(&["branch", "-q", "--set-upstream-to=origin/main", "main"])
.unwrap();
(g1, d1, g2, d2)
}
#[test]
fn classifies_real_repos() {
let (g1, d1, g2, d2) = setup();
assert_eq!(state(&d1), State::Synced);
fs::write(d1.join("wip.txt"), "x").unwrap();
assert_eq!(state(&d1), State::Dirty);
fs::remove_file(d1.join("wip.txt")).unwrap();
commit(&g1, &d1, "b.txt", "2\n");
assert_eq!(state(&d1), State::Ahead);
g1.run(&["push", "-q"]).unwrap();
g2.run(&["fetch", "-q"]).unwrap();
assert_eq!(state(&d2), State::Behind);
fs::write(d2.join("wip2.txt"), "x").unwrap();
assert_eq!(state(&d2), State::BehindDirty);
fs::remove_file(d2.join("wip2.txt")).unwrap();
commit(&g2, &d2, "c.txt", "3\n");
assert_eq!(state(&d2), State::Diverged);
}
#[test]
fn lists_worktrees_skipping_bare() {
let base = tmpdir("wtlist");
let src = base.join("src");
fs::create_dir_all(&src).unwrap();
let g = Git::new(&src);
g.run(&["init", "-q", "-b", "main"]).unwrap();
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
commit(&g, &src, "a.txt", "1\n");
let bare = base.join("r/.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("r/main");
bg.run(&["worktree", "add", "-q", wt.to_str().unwrap(), "main"])
.unwrap();
let list = worktrees(&bare).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].branch.as_deref(), Some("main"));
}
+211
View File
@@ -0,0 +1,211 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::{MigrateError, Step, migrate, migrate_failing_after};
use std::fs;
fn names(dir: &std::path::Path) -> Vec<String> {
let mut v: Vec<String> = fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
v.sort();
v
}
#[test]
fn migrates_preserving_all_local_state() {
let base = tmpdir("mig");
let repo = base.join("proj");
let g = messy_repo(&repo);
let status = g.run(&["status", "--porcelain", "--ignored"]).unwrap();
let stash = g.run(&["stash", "list", "--format=%H"]).unwrap();
let branches = g
.run(&["branch", "--format=%(refname) %(objectname)"])
.unwrap();
let r = migrate(&repo, "desktop", &base.join("backups"), "20261116").unwrap();
assert_eq!(names(&repo), vec![".bare", "main"]);
assert_eq!(r.worktree, repo.canonicalize().unwrap().join("main"));
let wt = Git::new(&r.worktree);
assert_eq!(
wt.run(&["status", "--porcelain", "--ignored"]).unwrap(),
status
);
assert_eq!(wt.run(&["stash", "list", "--format=%H"]).unwrap(), stash);
assert_eq!(
wt.run(&["branch", "--format=%(refname) %(objectname)"])
.unwrap(),
branches
);
assert!(
status.contains("A staged.txt"),
"staged state kept: {status}"
);
assert!(r.worktree.join("secret.env").exists(), "ignored file kept");
assert!(r.worktree.join("untracked.txt").exists());
assert_eq!(
fs::read_to_string(r.worktree.join("src/a.txt")).unwrap(),
"one\nmodified\n"
);
// Backup exists and the backup ref points at the old HEAD.
assert!(r.backup_tar.metadata().unwrap().len() > 0);
assert_eq!(
wt.run(&["rev-parse", &r.backup_ref]).unwrap(),
wt.run(&["rev-parse", "HEAD"]).unwrap()
);
// Repo is bare now; the worktree is still fully usable.
assert_eq!(
Git::new(&r.bare_dir)
.run(&["rev-parse", "--is-bare-repository"])
.unwrap(),
"true"
);
commit(&wt, "after.txt", "x\n");
}
#[test]
fn slash_branch_gets_flattened_directory() {
let base = tmpdir("slash");
let repo = base.join("p");
let g = init(&repo);
commit(&g, "a.txt", "1\n");
g.run(&["checkout", "-q", "-b", "feat/login"]).unwrap();
let r = migrate(&repo, "m", &base.join("bk"), "1").unwrap();
assert!(r.worktree.ends_with("feat-login"));
assert_eq!(names(&repo), vec![".bare", "feat-login"]);
}
#[test]
fn every_failure_point_rolls_back_to_the_original_layout() {
for step in [
Step::Staged,
Step::GitMoved,
Step::WorktreeAdded,
Step::Filled,
Step::IndexMoved,
Step::Verified,
] {
let base = tmpdir("rb");
let repo = base.join("proj");
let g = messy_repo(&repo);
let status = g.run(&["status", "--porcelain", "--ignored"]).unwrap();
let stash = g.run(&["stash", "list", "--format=%H"]).unwrap();
let before_names = names(&repo);
let err = migrate_failing_after(&repo, "m", &base.join("bk"), "1", step).unwrap_err();
let MigrateError::Failed {
rolled_back,
backup,
..
} = err
else {
panic!("{step:?}: expected Failed")
};
assert!(rolled_back, "{step:?}: rollback incomplete");
assert!(backup.exists());
assert_eq!(names(&repo), before_names, "{step:?}: layout restored");
let g = Git::new(&repo);
assert_eq!(
g.run(&["rev-parse", "--is-bare-repository"]).unwrap(),
"false",
"{step:?}"
);
assert_eq!(
g.run(&["status", "--porcelain", "--ignored"]).unwrap(),
status,
"{step:?}"
);
assert_eq!(
g.run(&["stash", "list", "--format=%H"]).unwrap(),
stash,
"{step:?}"
);
assert_eq!(
g.run(&["worktree", "list", "--porcelain"])
.unwrap()
.matches("worktree ")
.count(),
1
);
// And a retry succeeds afterwards.
migrate(&repo, "m", &base.join("bk"), "2").unwrap();
}
}
fn refused(r: Result<grove_core::migrate::Report, MigrateError>) -> String {
match r {
Err(MigrateError::Refused(m)) => m,
other => panic!("expected Refused, got {other:?}"),
}
}
#[test]
fn refuses_unsafe_situations_without_touching_anything() {
let base = tmpdir("ref");
let bk = base.join("bk");
let detached = base.join("detached");
let g = init(&detached);
commit(&g, "a", "1");
g.run(&["checkout", "-q", "--detach"]).unwrap();
assert!(refused(migrate(&detached, "m", &bk, "1")).contains("detached"));
let unborn = base.join("unborn");
init(&unborn);
assert!(refused(migrate(&unborn, "m", &bk, "1")).contains("no commits"));
let merging = base.join("merging");
let g = init(&merging);
commit(&g, "a", "1");
fs::write(merging.join(".git/MERGE_HEAD"), "x").unwrap();
assert!(refused(migrate(&merging, "m", &bk, "1")).contains("in progress"));
let subm = base.join("subm");
let g = init(&subm);
commit(&g, "a", "1");
fs::write(subm.join(".gitmodules"), "").unwrap();
assert!(refused(migrate(&subm, "m", &bk, "1")).contains("submodule"));
let multi = base.join("multi");
let g = init(&multi);
commit(&g, "a", "1");
g.run(&[
"worktree",
"add",
"-q",
"-b",
"x",
base.join("extra").to_str().unwrap(),
])
.unwrap();
assert!(refused(migrate(&multi, "m", &bk, "1")).contains("linked worktrees"));
let done = base.join("done");
let g = init(&done);
commit(&g, "a", "1");
migrate(&done, "m", &bk, "1").unwrap();
assert!(refused(migrate(&done, "m", &bk, "2")).contains("already migrated"));
let inside = base.join("inside");
let g = init(&inside);
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"));
}
+407
View File
@@ -0,0 +1,407 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::migrate;
use grove_core::receive::*;
use grove_core::snapshot::take;
use grove_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/receive/main"])
.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/archive/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 {
grove_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 grove_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"
);
}
+137
View File
@@ -0,0 +1,137 @@
use grove_core::git::Git;
use grove_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!(
"grove-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());
}
+116
View File
@@ -0,0 +1,116 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::receive::Applied;
use grove_core::state::State;
use grove_core::sync::{Options, sync_repo};
use std::fs;
use std::path::Path;
fn opts(machine: &str, stamp: &str) -> Options {
Options {
machine: machine.into(),
stamp: stamp.into(),
remote: "origin".into(),
offline: false,
materialize: true,
}
}
fn clone(base: &Path, remote: &Path, name: &str) -> (Git, std::path::PathBuf) {
let d = base.join(name);
Git::new(base)
.run(&["clone", "-q", remote.to_str().unwrap(), d.to_str().unwrap()])
.unwrap();
let g = Git::new(&d);
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
(g, d)
}
#[test]
fn two_machines_converge_without_manual_git() {
let base = tmpdir("sync");
let remote = base.join("r.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let seed = init(&base.join("seed"));
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
.unwrap();
commit(&seed, "a.txt", "1\n");
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
let (ga, da) = clone(&base, &remote, "A");
let (_gb, db) = clone(&base, &remote, "B");
// A works (WIP only, nothing committed) and syncs.
fs::write(da.join("a.txt"), "1\nwork\n").unwrap();
fs::write(da.join("scratch.txt"), "s\n").unwrap();
let ra = sync_repo(&da, &opts("A", "t1")).unwrap();
assert_eq!(ra.worktrees[0].snapshot, Some("created"));
assert!(
ra.worktrees[0].errors.is_empty(),
"{:?}",
ra.worktrees[0].errors
);
// B syncs and ends up with A's work in progress.
let rb = sync_repo(&db, &opts("B", "t2")).unwrap();
assert_eq!(
rb.worktrees[0].applied.as_ref().unwrap().1,
Applied::Applied
);
assert_eq!(fs::read_to_string(db.join("a.txt")).unwrap(), "1\nwork\n");
assert!(db.join("scratch.txt").exists());
// A commits and pushes by hand; B (now dirty from the applied WIP) must not be touched.
ga.run(&["add", "-A"]).unwrap();
ga.run(&["commit", "-qm", "work"]).unwrap();
ga.run(&["push", "-q"]).unwrap();
let rb2 = sync_repo(&db, &opts("B", "t3")).unwrap();
assert_eq!(rb2.worktrees[0].state, State::BehindDirty);
assert_eq!(fs::read_to_string(db.join("a.txt")).unwrap(), "1\nwork\n");
// Discarding B's applied copy makes it clean; the next sync fast-forwards it.
Git::new(&db).run(&["checkout", "-q", "--", "."]).unwrap();
fs::remove_file(db.join("scratch.txt")).unwrap();
let rb3 = sync_repo(&db, &opts("B", "t4")).unwrap();
assert_eq!(rb3.worktrees[0].state, State::Synced);
assert!(db.join("scratch.txt").exists());
}
#[test]
fn offline_pass_skips_network_and_never_fails() {
let base = tmpdir("offline");
let g = init(&base.join("p"));
commit(&g, "a.txt", "1\n");
fs::write(base.join("p/w.txt"), "w\n").unwrap();
let mut o = opts("A", "t");
o.offline = true;
let r = sync_repo(&base.join("p"), &o).unwrap();
assert_eq!(r.worktrees[0].snapshot, Some("created"));
assert!(r.worktrees[0].errors.is_empty());
assert!(r.fetch_error.is_none());
}
#[test]
fn unreachable_remote_is_reported_but_local_snapshot_still_taken() {
let base = tmpdir("noremote");
let g = init(&base.join("p"));
commit(&g, "a.txt", "1\n");
g.run(&["remote", "add", "origin", "/nonexistent/remote.git"])
.unwrap();
fs::write(base.join("p/w.txt"), "w\n").unwrap();
let r = sync_repo(&base.join("p"), &opts("A", "t")).unwrap();
assert!(r.fetch_error.is_some());
assert_eq!(r.worktrees[0].snapshot, Some("created"));
assert!(!r.worktrees[0].errors.is_empty(), "push failure surfaced");
assert_eq!(r.worktrees[0].state, State::Dirty);
}