feat: add config loading, worktree inspection and CLI status/snapshot

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 12:00:28 +01:00
1 parent 753bd2c267
commit 5291c3e671
10 files changed
+844 -4

No files matched your search

+2
View File
@@ -5,3 +5,5 @@ edition.workspace = true
version.workspace = true
[dependencies]
serde = { version = "1.0.229", features = ["derive"] }
toml = "1.2.1"
+272
View File
@@ -0,0 +1,272 @@
//! `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/gitsync/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("gitsync/config.toml"))
}
/// `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 = "gitsync-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(_))));
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Read-only inspection of worktrees: gathers `Facts` and classifies them.
use crate::git::{Git, GitError};
use crate::state::{Facts, State, classify};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Worktree {
pub path: PathBuf,
/// `None` for detached HEAD.
pub branch: Option<String>,
}
/// Non-bare worktrees of the repository containing `path` (adopts foreign ones too).
pub fn worktrees(path: &Path) -> Result<Vec<Worktree>, GitError> {
let out = Git::new(path).run(&["worktree", "list", "--porcelain"])?;
let mut list = Vec::new();
for block in out.split("\n\n").filter(|b| !b.trim().is_empty()) {
let mut wt = None;
let mut branch = None;
let mut bare = false;
for line in block.lines() {
if let Some(p) = line.strip_prefix("worktree ") {
wt = Some(PathBuf::from(p));
} else if let Some(b) = line.strip_prefix("branch refs/heads/") {
branch = Some(b.to_string());
} else if line == "bare" {
bare = true;
}
}
if let (Some(path), false) = (wt, bare) {
list.push(Worktree { path, branch });
}
}
Ok(list)
}
/// Collect facts for one worktree. Without an upstream, ahead/behind are false.
pub fn facts(worktree: &Path) -> Result<Facts, GitError> {
let git = Git::new(worktree);
let dirty = !git.run(&["status", "--porcelain"])?.is_empty();
let (mut ahead, mut behind) = (false, false);
if git
.probe(&["rev-parse", "--abbrev-ref", "@{upstream}"])?
.is_some()
{
let counts = git.run(&["rev-list", "--left-right", "--count", "HEAD...@{upstream}"])?;
let mut it = counts.split_whitespace();
ahead = it.next().is_some_and(|n| n != "0");
behind = it.next().is_some_and(|n| n != "0");
}
Ok(Facts {
dirty,
ahead,
behind,
error: None,
})
}
/// Classify a worktree; git failures become `State::Error` instead of propagating.
pub fn state(worktree: &Path) -> State {
match facts(worktree) {
Ok(f) => classify(&f),
Err(e) => State::Error(e.to_string()),
}
}
+3 -1
View File
@@ -1,5 +1,7 @@
//! Sync engine core: git plumbing wrapper, snapshots and state classification.
//! Sync engine core: git plumbing wrapper, config, snapshots and state classification.
pub mod config;
pub mod git;
pub mod inspect;
pub mod snapshot;
pub mod state;
+117
View File
@@ -0,0 +1,117 @@
use gitsync_core::git::Git;
use gitsync_core::inspect::{state, worktrees};
use gitsync_core::state::State;
use std::fs;
use std::path::{Path, PathBuf};
fn tmpdir(tag: &str) -> PathBuf {
let p = std::env::temp_dir().join(format!(
"gitsync-test-{tag}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
fs::create_dir_all(&p).unwrap();
p
}
fn 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"));
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "gitsync"
description = "gitsync command line client"
edition.workspace = true
version.workspace = true
[dependencies]
anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive"] }
gitsync-core = { version = "0.1.0", path = "../gitsync-core" }
+70
View File
@@ -0,0 +1,70 @@
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use gitsync_core::config::Config;
use gitsync_core::inspect::{state, worktrees};
use gitsync_core::snapshot::{Outcome, take};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Parser)]
#[command(
name = "gitsync",
about = "Keep git workspaces in sync across machines"
)]
struct Cli {
/// Path to config.toml (default: $XDG_CONFIG_HOME/gitsync/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,
},
}
fn load_config(arg: Option<PathBuf>) -> Result<Config> {
let path = arg
.or_else(Config::default_path)
.context("cannot determine config path (set --config)")?;
Config::load(&path).with_context(|| format!("loading {}", path.display()))
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.cmd {
Cmd::Status { path } => {
for wt in worktrees(&path)? {
let branch = wt.branch.as_deref().unwrap_or("(detached)");
println!(
"{:<24} {:?} {}",
branch,
state(&wt.path),
wt.path.display()
);
}
}
Cmd::Snapshot { path } => {
let cfg = load_config(cli.config)?;
let stamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
.to_string();
match take(&path, &cfg.machine.name, &stamp)? {
Outcome::Created(s) => println!("created {} {}", s.refname, s.commit),
Outcome::Unchanged(c) => println!("unchanged {c}"),
}
}
}
Ok(())
}