mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
chore: rename project to grove and add MIT license
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
126acb4b57
commit
c935d779e1
29 files changed
+99
-76
No files matched your search
@@ -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(_))));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()),
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
}))
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user