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 -2
View File
@@ -4,7 +4,7 @@
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 in progress**: `gitsync-core` has the git runner, snapshots and state classification; config, migration, receive logic, CLI are pending. Do not start a
**Phase 0 done, Phase 1 in progress**: `gitsync-core` has the git runner, snapshots and state classification; config loading, worktree inspection and a minimal CLI (`status`, `snapshot`) exist; migration (`add`), receive logic, `doctor` and two-machine tests are pending. Do not start a
new phase before its predecessor's results are written to `docs/`.
## Commands
@@ -18,7 +18,7 @@ system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touch
user's branch or index.
## Conventions
- `gitsync-core` has no external dependencies yet; ask before adding any.
- 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
+301
View File
@@ -2,6 +2,307 @@
# 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 = "gitsync"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"gitsync-core",
]
[[package]]
name = "gitsync-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"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/gitsync-core"]
members = ["crates/gitsync-core", "crates/gitsync"]
[workspace.package]
edition = "2024"
+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(())
}