mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16:11 +00:00
Merge pull request 'feat: Phase 1 core + CLI (snapshots, add, sync, doctor)' (#1) from feat/core-snapshot into development
Reviewed-on: #1
This commit is contained in:
commit
f762d02c99
31 files changed
+3576
-10
No files matched your search
@@ -0,0 +1 @@
|
||||
/target
|
||||
@@ -1,23 +1,24 @@
|
||||
# Grove (working name: gitsync)
|
||||
# Grove
|
||||
|
||||
## Overview
|
||||
Linux tool that keeps chosen git repos continuously in sync across machines, including
|
||||
uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote.
|
||||
Planned as a Rust workspace (core, providers, daemon, CLI, Tauri GUI). Currently in
|
||||
**Phase 0 done / Phase 1 not started**: only spike scripts and docs exist. Do not start a
|
||||
**Phase 0 done, Phase 1 implemented and validated against the real Gitea with two simulated machines (real two-PC run still pending)**: `grove-core` + `grove` CLI (`status`, `snapshot`, `add`, `sync`, `doctor`); daemon, GUI and providers do not exist yet. Do not start a
|
||||
new phase before its predecessor's results are written to `docs/`.
|
||||
|
||||
## Commands
|
||||
- Check shell scripts: `for f in spikes/*.sh; do bash -n "$f"; done`
|
||||
- Throwaway Forgejo (dev only, Podman): `spikes/forgejo-up.sh`, then `spikes/phase0.sh`
|
||||
- Once the Rust workspace exists: `cargo fmt --check`, `cargo clippy -- -D warnings`, `cargo test`
|
||||
- Rust: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test`
|
||||
|
||||
## Architecture
|
||||
See `docs/` (`phase0-spike.md`, `DECISIONS.md`). Git is the storage layer; shell out to
|
||||
See `docs/` (`phase0-spike.md`, `phase1.md`, `DECISIONS.md`). Git is the storage layer; shell out to
|
||||
system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
|
||||
user's branch or index.
|
||||
|
||||
## Conventions
|
||||
- Dependencies: serde+toml (config), clap+anyhow (CLI), approved. Ask before adding more.
|
||||
- Everything in the repo is English. Open questions go to `docs/DECISIONS.md`.
|
||||
- Never destroy local work; divergence is surfaced, never auto-merged.
|
||||
|
||||
|
||||
Generated
+308
@@ -0,0 +1,308 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.6.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||
|
||||
[[package]]
|
||||
name = "grove"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"grove-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "grove-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.2.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.3+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.2.0+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
|
||||
@@ -0,0 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/grove-core", "crates/grove"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
version = "0.1.0"
|
||||
license = "MIT"
|
||||
@@ -1,3 +1,7 @@
|
||||
# Lessons
|
||||
|
||||
- Forgejo push mirrors to localhost are blocked by default; set `ALLOW_LOCALNETWORKS` in throwaway test instances.
|
||||
- `git clone --bare` sets no `remote.origin.fetch`; without it `fetch` never creates `refs/remotes/*`. Use `receive::ensure_fetch_refspec`.
|
||||
- `Git::run` trims stdout, which also eats the leading space of the first `status --porcelain` line (` M x` becomes `M x`). Don't assert on that format via `run`.
|
||||
- Fetch other machines' snapshots into `refs/sync-remote/*`, never into `refs/sync/*`, or a fetch can clobber this machine's own refs.
|
||||
- Run tests that create many temp repos with unique dir names (pid + nanos); the shared `tests/common` helper does this.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Darío
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,4 +1,8 @@
|
||||
# Grove
|
||||
|
||||
Keeps your git repos in sync across machines without manual commit/push/pull, including
|
||||
work in progress. Early stage (spikes only). See `docs/` for details.
|
||||
work in progress. Early stage (Phase 1: core library and CLI). See `docs/` for details.
|
||||
|
||||
## License
|
||||
|
||||
MIT, see `LICENSE`.
|
||||
@@ -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"
|
||||
@@ -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}")),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "grove"
|
||||
description = "grove command line client"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.104"
|
||||
clap = { version = "4.6.7", features = ["derive"] }
|
||||
grove-core = { version = "0.1.0", path = "../grove-core" }
|
||||
@@ -0,0 +1,257 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use clap::{Parser, Subcommand};
|
||||
use grove_core::config::Config;
|
||||
use grove_core::git::Git;
|
||||
use grove_core::inspect::{state, worktrees};
|
||||
use grove_core::migrate::migrate;
|
||||
use grove_core::receive::{Applied, Archived, Received};
|
||||
use grove_core::snapshot::{Outcome, take};
|
||||
use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "grove", about = "Keep git workspaces in sync across machines")]
|
||||
struct Cli {
|
||||
/// Path to config.toml (default: $XDG_CONFIG_HOME/grove/config.toml)
|
||||
#[arg(long, global = true)]
|
||||
config: Option<PathBuf>,
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// Show the sync state of every worktree of the repo at PATH
|
||||
Status {
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
},
|
||||
/// Take a snapshot of the worktree at PATH into refs/sync/<machine>/<branch>
|
||||
Snapshot {
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
},
|
||||
/// Migrate the plain clone at PATH to bare + worktrees (backs up first)
|
||||
Add {
|
||||
path: PathBuf,
|
||||
/// Where to write the safety backup (default: <state dir>/backups)
|
||||
#[arg(long)]
|
||||
backup_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Run one full sync pass on the repo at PATH
|
||||
Sync {
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
/// Skip all network operations
|
||||
#[arg(long)]
|
||||
offline: bool,
|
||||
},
|
||||
/// Check the local setup
|
||||
Doctor,
|
||||
}
|
||||
|
||||
fn load_config(arg: &Option<PathBuf>) -> Result<Config> {
|
||||
let path = arg
|
||||
.clone()
|
||||
.or_else(Config::default_path)
|
||||
.context("cannot determine config path (set --config)")?;
|
||||
Config::load(&path).with_context(|| format!("loading {}", path.display()))
|
||||
}
|
||||
|
||||
fn stamp() -> String {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs())
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
match &cli.cmd {
|
||||
Cmd::Status { path } => status(path),
|
||||
Cmd::Snapshot { path } => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
match take(path, &cfg.machine.name, &stamp())? {
|
||||
Outcome::Created(s) => println!("created {} {}", s.refname, s.commit),
|
||||
Outcome::Unchanged(c) => println!("unchanged {c}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Cmd::Add { path, backup_dir } => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
let dir = backup_dir
|
||||
.clone()
|
||||
.or_else(|| Config::state_dir().map(|d| d.join("backups")))
|
||||
.context("cannot determine backup dir (set --backup-dir)")?;
|
||||
let r = migrate(path, &cfg.machine.name, &dir, &stamp())?;
|
||||
println!("migrated: {}", r.worktree.display());
|
||||
println!(
|
||||
"backup: {} (ref {})",
|
||||
r.backup_tar.display(),
|
||||
r.backup_ref
|
||||
);
|
||||
println!("note: shells whose cwd was inside the old checkout must `cd` again");
|
||||
Ok(())
|
||||
}
|
||||
Cmd::Sync { path, offline } => {
|
||||
let cfg = load_config(&cli.config)?;
|
||||
let rep = sync_repo(
|
||||
path,
|
||||
&Options {
|
||||
machine: cfg.machine.name.clone(),
|
||||
stamp: stamp(),
|
||||
remote: "origin".into(),
|
||||
offline: *offline,
|
||||
materialize: true,
|
||||
},
|
||||
)?;
|
||||
print_report(&rep)
|
||||
}
|
||||
Cmd::Doctor => doctor(&cli.config),
|
||||
}
|
||||
}
|
||||
|
||||
fn status(path: &Path) -> Result<()> {
|
||||
for wt in worktrees(&git_dir_for(path))? {
|
||||
let branch = wt.branch.as_deref().unwrap_or("(detached)");
|
||||
println!(
|
||||
"{:<24} {:?} {}",
|
||||
branch,
|
||||
state(&wt.path),
|
||||
wt.path.display()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_report(rep: &SyncReport) -> Result<()> {
|
||||
let mut failed = false;
|
||||
if let Some(e) = &rep.fetch_error {
|
||||
println!("fetch: ERROR {e}");
|
||||
failed = true;
|
||||
}
|
||||
for p in &rep.materialized {
|
||||
println!("materialized {}", p.display());
|
||||
}
|
||||
for a in &rep.archived {
|
||||
match a {
|
||||
Archived::Removed { branch, backup_ref } => {
|
||||
println!("archived {branch} (backup {backup_ref})")
|
||||
}
|
||||
Archived::KeptDirty { branch } => {
|
||||
println!("kept {branch}: gone upstream but has local changes")
|
||||
}
|
||||
}
|
||||
}
|
||||
for w in &rep.worktrees {
|
||||
let branch = w.branch.as_deref().unwrap_or("(detached)");
|
||||
let mut notes = Vec::new();
|
||||
if let Some(s) = w.snapshot {
|
||||
notes.push(format!("snapshot {s}"));
|
||||
}
|
||||
match &w.received {
|
||||
Some(Received::FastForwarded { .. }) => notes.push("fast-forwarded".into()),
|
||||
Some(Received::Declined(why)) => notes.push(format!("not fast-forwarded: {why}")),
|
||||
_ => {}
|
||||
}
|
||||
if let Some((m, a)) = &w.applied {
|
||||
match a {
|
||||
Applied::Applied => notes.push(format!("applied snapshot from {m}")),
|
||||
Applied::Declined(why) => {
|
||||
notes.push(format!("snapshot from {m} not applied: {why}"))
|
||||
}
|
||||
Applied::Nothing => {}
|
||||
}
|
||||
}
|
||||
println!("{:<24} {:?} {}", branch, w.state, notes.join("; "));
|
||||
for e in &w.errors {
|
||||
println!(" error: {e}");
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
bail!("sync finished with errors");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn doctor(cfg_arg: &Option<PathBuf>) -> Result<()> {
|
||||
let mut bad = 0;
|
||||
let mut line = |ok: Option<bool>, msg: String| {
|
||||
let tag = match ok {
|
||||
Some(true) => "ok ",
|
||||
Some(false) => {
|
||||
bad += 1;
|
||||
"FAIL"
|
||||
}
|
||||
None => "warn",
|
||||
};
|
||||
println!("[{tag}] {msg}");
|
||||
};
|
||||
match Git::new(".").run(&["--version"]) {
|
||||
Ok(v) => line(Some(true), v),
|
||||
Err(e) => line(Some(false), format!("git not usable: {e}")),
|
||||
}
|
||||
let cfg = match load_config(cfg_arg) {
|
||||
Ok(c) => {
|
||||
line(
|
||||
Some(true),
|
||||
format!("config valid (machine {:?})", c.machine.name),
|
||||
);
|
||||
Some(c)
|
||||
}
|
||||
Err(e) => {
|
||||
line(Some(false), format!("{e:#}"));
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(c) = &cfg {
|
||||
let root = c.root_path();
|
||||
line(Some(root.is_dir()), format!("root {}", root.display()));
|
||||
for g in &c.groups {
|
||||
let gdir = root.join(&g.name);
|
||||
let Ok(rd) = std::fs::read_dir(&gdir) else {
|
||||
line(
|
||||
None,
|
||||
format!("group {:?}: {} missing", g.name, gdir.display()),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
for e in rd.filter_map(Result::ok) {
|
||||
let bare = e.path().join(".bare");
|
||||
if !bare.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let git = Git::new(&bare);
|
||||
let has_remote = matches!(
|
||||
git.probe(&["config", "--get", "remote.origin.url"]),
|
||||
Ok(Some(_))
|
||||
);
|
||||
let has_refspec = matches!(
|
||||
git.probe(&["config", "--get", "remote.origin.fetch"]),
|
||||
Ok(Some(_))
|
||||
);
|
||||
line(
|
||||
Some(has_remote && has_refspec),
|
||||
format!("{}: origin remote and fetch refspec", e.path().display()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
match std::fs::read_to_string("/proc/sys/fs/inotify/max_user_watches")
|
||||
.ok()
|
||||
.and_then(|s| s.trim().parse::<u64>().ok())
|
||||
{
|
||||
Some(n) if n >= 65536 => line(Some(true), format!("inotify max_user_watches = {n}")),
|
||||
Some(n) => line(
|
||||
None,
|
||||
format!("inotify max_user_watches = {n} (raise fs.inotify.max_user_watches)"),
|
||||
),
|
||||
None => line(None, "cannot read inotify limit".into()),
|
||||
}
|
||||
if bad > 0 {
|
||||
bail!("{bad} check(s) failed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
fn tmp(tag: &str) -> PathBuf {
|
||||
let p = std::env::temp_dir().join(format!("grove-cli-{tag}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&p);
|
||||
fs::create_dir_all(&p).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let o = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
o.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&o.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn gs(cfg: &Path, dir: &Path, args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_grove"))
|
||||
.current_dir(dir)
|
||||
.arg("--config")
|
||||
.arg(cfg)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn out(o: &Output) -> String {
|
||||
format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&o.stdout),
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_then_sync_then_doctor() {
|
||||
let base = tmp("e2e");
|
||||
let cfg = base.join("config.toml");
|
||||
fs::write(
|
||||
&cfg,
|
||||
format!(
|
||||
"[machine]\nname=\"desk\"\n[root]\npath=\"{}\"\n",
|
||||
base.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let remote = base.join("r.git");
|
||||
git(
|
||||
&base,
|
||||
&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
let repo = base.join("proj");
|
||||
fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "user.email", "t@t"]);
|
||||
git(&repo, &["config", "user.name", "t"]);
|
||||
git(
|
||||
&repo,
|
||||
&["remote", "add", "origin", remote.to_str().unwrap()],
|
||||
);
|
||||
fs::write(repo.join("a.txt"), "1\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-qm", "init"]);
|
||||
git(&repo, &["push", "-q", "-u", "origin", "main"]);
|
||||
fs::write(repo.join("wip.txt"), "wip\n").unwrap();
|
||||
|
||||
let o = gs(
|
||||
&cfg,
|
||||
&base,
|
||||
&[
|
||||
"add",
|
||||
repo.to_str().unwrap(),
|
||||
"--backup-dir",
|
||||
base.join("bk").to_str().unwrap(),
|
||||
],
|
||||
);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
assert!(repo.join("main/wip.txt").exists());
|
||||
assert!(repo.join(".bare").is_dir());
|
||||
|
||||
let o = gs(&cfg, &base, &["sync", repo.to_str().unwrap()]);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
assert!(out(&o).contains("snapshot created"), "{}", out(&o));
|
||||
assert!(git(&remote, &["for-each-ref", "refs/sync"]).contains("refs/sync/desk/main"));
|
||||
|
||||
let o = gs(&cfg, &base, &["status", repo.to_str().unwrap()]);
|
||||
assert!(out(&o).contains("Dirty"), "{}", out(&o));
|
||||
|
||||
let o = gs(&cfg, &base, &["doctor"]);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
|
||||
// Bad config is a clear failure, not a panic.
|
||||
fs::write(&cfg, "[machine]\nname=\"a b\"\n[root]\npath=\"/x\"\n").unwrap();
|
||||
let o = gs(&cfg, &base, &["doctor"]);
|
||||
assert!(!o.status.success());
|
||||
assert!(out(&o).contains("machine.name"), "{}", out(&o));
|
||||
}
|
||||
+4
-1
@@ -1,4 +1,7 @@
|
||||
# Decisions
|
||||
|
||||
1. Custom refs on Gitea/Forgejo: supported on Forgejo 11, no fallback needed (see `phase0-spike.md`). Also confirmed on git.zenvairo.es (Gitea 1.25.4); mirror exclusion still to verify there.
|
||||
2-5. Open.
|
||||
2. Snapshots are auto-applied only when the target worktree is clean, has no unpushed commits and HEAD can fast-forward to the snapshot's base; otherwise declined and reported (implemented in `receive::apply_snapshot`).
|
||||
3. Config: TOML for user intent (implemented); runtime state storage still open.
|
||||
4. License: MIT (decided).
|
||||
5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`).
|
||||
@@ -0,0 +1,84 @@
|
||||
# Phase 1: core + CLI
|
||||
|
||||
Crates: `grove-core` (library) and `grove` (CLI). Everything shells out to the system `git`.
|
||||
|
||||
## CLI
|
||||
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `grove status [path]` | State of every worktree (`Synced`, `Dirty`, `Ahead`, `Behind`, `BehindDirty`, `Diverged`, `Error`) |
|
||||
| `grove snapshot [path]` | Snapshot the worktree into `refs/sync/<machine>/<branch>` (local only) |
|
||||
| `grove add <path>` | Migrate a plain clone to `.bare/` + one worktree per branch, in place |
|
||||
| `grove sync [path] [--offline]` | One full pass (below) |
|
||||
| `grove doctor` | Checks git, config, root, repo remotes and refspecs, inotify limit |
|
||||
|
||||
Config: `~/.config/grove/config.toml` (or `--config`). Machine names are embedded in ref names, so
|
||||
they may only contain letters, digits, `-` and `_`.
|
||||
|
||||
## Sync pass (`sync_repo`)
|
||||
|
||||
1. `fetch --prune` plus `+refs/sync/*:refs/sync-remote/*` (other machines' snapshots land in a
|
||||
separate namespace so a machine's own `refs/sync/*` is never overwritten).
|
||||
2. Bare layout only: archive worktrees whose upstream branch is gone, then materialize worktrees for
|
||||
new remote branches.
|
||||
3. Per worktree: snapshot (if dirty, or if an older snapshot ref exists so a stale WIP never lingers)
|
||||
and force-push the machine's own snapshot ref; fast-forward if clean and strictly behind;
|
||||
apply another machine's snapshot as working changes if clean, not ahead, and HEAD can fast-forward
|
||||
to the snapshot's base commit.
|
||||
4. Step failures are reported per worktree and never abort the pass. Dirty or diverged worktrees
|
||||
are never modified.
|
||||
|
||||
## Safety mechanisms
|
||||
|
||||
- `add`: full tar backup + `refs/sync-backup/<machine>/<ts>` first; refuses detached HEAD, no commits,
|
||||
merge/rebase/cherry-pick/bisect in progress, submodules, existing linked worktrees, backup dir
|
||||
inside the repo. Staged state, stashes, untracked and ignored files are preserved (the index is
|
||||
carried over). Status, stashes and refs are compared before/after; any failure triggers rollback
|
||||
to the original layout (tested by injecting a failure after every step).
|
||||
- Every operation that rewrites a worktree writes a backup ref first.
|
||||
- `apply_snapshot` declines (changing nothing) on any local work; `read-tree -m -u` additionally
|
||||
refuses to overwrite untracked files. Both it and the fast-forward in `receive` also decline when
|
||||
the incoming change would overwrite a local *ignored* file (`ignored_conflicts`).
|
||||
- `archive_gone` keeps any worktree whose `status --porcelain --ignored` is non-empty (so `.env`
|
||||
and similar are never deleted), never archives when the remote lists no branches, and writes a
|
||||
backup ref before deleting a branch.
|
||||
- Backup refs live in per-kind namespaces (`refs/sync-backup/<machine>/<stamp>/<kind>`, kinds
|
||||
`add`, `receive/<branch>`, `apply/<branch>`, `archive/<branch>`) so several in one pass cannot
|
||||
collide as ref directory/file.
|
||||
- `add` also refuses sparse checkouts and `extensions.worktreeConfig`.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Nested untracked git repos are snapshotted only as gitlinks (their content is not synced).
|
||||
- No crash-resume: a hard kill in the middle of `add` leaves `.grove-stage`; the error says where
|
||||
the files are, but recovery is manual (the backup tar and ref exist).
|
||||
- Machine-name uniqueness across machines is not enforced.
|
||||
- Split-index repos are untested.
|
||||
|
||||
## Not done yet (later phases)
|
||||
|
||||
- Real two-PC validation by the author (acceptance criterion of this phase).
|
||||
- Daemon, file watching, scheduling, IPC (Phase 2). Locking against concurrent user git commands.
|
||||
- Migration of repos with submodules or existing linked worktrees; `new` and provider code (Phase 4).
|
||||
- Resolve actions for `Diverged` (Phase 5): today it is only detected and left intact.
|
||||
|
||||
## Validation on the real Gitea (2026-11-16)
|
||||
|
||||
Two simulated machines (`pca` as a plain clone, `pcb` migrated with `grove add`) against a
|
||||
throwaway private repo on git.zenvairo.es (Gitea 1.25.4, HTTPS), deleted afterwards. All via the
|
||||
`grove` binary:
|
||||
|
||||
| Scenario | Result |
|
||||
|---|---|
|
||||
| `add` on a plain clone | Migrated, backup tar + ref created |
|
||||
| Uncommitted + untracked work on A, `sync` on both | Snapshot pushed to `refs/sync/pca/main`, applied on B |
|
||||
| B has local edits when A's work arrives | `BehindDirty`, local edits untouched, snapshot declined |
|
||||
| A commits and pushes, B clean | B fast-forwarded |
|
||||
| Branch created then deleted upstream | Worktree materialized, then archived with a backup ref |
|
||||
| B has an unpushed commit, A pushes | `Diverged`, nothing modified |
|
||||
|
||||
Not covered: real two-PC run (same code paths, but different machines/filesystems), push-mirror
|
||||
exclusion of `refs/sync/*` on this Gitea (needs a mirror target and credentials).
|
||||
|
||||
Observed UX noise: a stale snapshot from another machine is reported as "not applied" on every
|
||||
pass until that machine syncs again.
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start a throwaway Forgejo (dev only) on localhost:3300 with an admin user.
|
||||
set -euo pipefail
|
||||
podman rm -f gitsync-forgejo >/dev/null 2>&1 || true
|
||||
podman run -d --name gitsync-forgejo -p 3300:3000 \
|
||||
podman rm -f grove-forgejo >/dev/null 2>&1 || true
|
||||
podman run -d --name grove-forgejo -p 3300:3000 \
|
||||
-e FORGEJO__security__INSTALL_LOCK=true \
|
||||
-e FORGEJO__server__ROOT_URL=http://localhost:3300/ \
|
||||
-e FORGEJO__server__DISABLE_SSH=true \
|
||||
@@ -10,5 +10,5 @@ podman run -d --name gitsync-forgejo -p 3300:3000 \
|
||||
-e FORGEJO__mirror__ENABLED=true -e FORGEJO__migrations__ALLOW_LOCALNETWORKS=true -e FORGEJO__migrations__ALLOWED_DOMAINS=localhost \
|
||||
codeberg.org/forgejo/forgejo:11 >/dev/null
|
||||
for i in $(seq 60); do curl -fs localhost:3300/api/healthz >/dev/null && break; sleep 1; done
|
||||
podman exec --user git gitsync-forgejo forgejo admin user create --admin \
|
||||
podman exec --user git grove-forgejo forgejo admin user create --admin \
|
||||
--username spike --password spike-pass-123 --email spike@example.invalid --must-change-password=false
|
||||
+1
-1
@@ -16,6 +16,6 @@ tree=$(git write-tree)
|
||||
prev=$(git rev-parse -q --verify "$ref" || true)
|
||||
if [ -n "$prev" ] && [ "$(git rev-parse "$prev^{tree}")" = "$tree" ]; then echo "unchanged $prev"; exit 0; fi
|
||||
parents=(-p HEAD); [ -n "$prev" ] && parents+=(-p "$prev")
|
||||
commit=$(git commit-tree "$tree" "${parents[@]}" -m "gitsync snapshot $machine $(date -u +%FT%TZ)")
|
||||
commit=$(git commit-tree "$tree" "${parents[@]}" -m "grove snapshot $machine $(date -u +%FT%TZ)")
|
||||
git update-ref "$ref" "$commit"
|
||||
echo "$commit"
|
||||
Reference in new issue
Block a user