mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat: add sync orchestrator and CLI add/sync/doctor
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e731c691f8
commit
81d8142c57
5 files changed
+590
-21
No files matched your search
@@ -8,3 +8,4 @@ pub mod migrate;
|
|||||||
pub mod receive;
|
pub mod receive;
|
||||||
pub mod snapshot;
|
pub mod snapshot;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
pub mod sync;
|
||||||
@@ -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,116 @@
|
|||||||
|
mod common;
|
||||||
|
use common::*;
|
||||||
|
use gitsync_core::git::Git;
|
||||||
|
use gitsync_core::receive::Applied;
|
||||||
|
use gitsync_core::state::State;
|
||||||
|
use gitsync_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);
|
||||||
|
}
|
||||||
+209
-21
@@ -1,9 +1,13 @@
|
|||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result, bail};
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
use gitsync_core::config::Config;
|
use gitsync_core::config::Config;
|
||||||
|
use gitsync_core::git::Git;
|
||||||
use gitsync_core::inspect::{state, worktrees};
|
use gitsync_core::inspect::{state, worktrees};
|
||||||
|
use gitsync_core::migrate::migrate;
|
||||||
|
use gitsync_core::receive::{Applied, Archived, Received};
|
||||||
use gitsync_core::snapshot::{Outcome, take};
|
use gitsync_core::snapshot::{Outcome, take};
|
||||||
use std::path::PathBuf;
|
use gitsync_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
@@ -31,40 +35,224 @@ enum Cmd {
|
|||||||
#[arg(default_value = ".")]
|
#[arg(default_value = ".")]
|
||||||
path: PathBuf,
|
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> {
|
fn load_config(arg: &Option<PathBuf>) -> Result<Config> {
|
||||||
let path = arg
|
let path = arg
|
||||||
|
.clone()
|
||||||
.or_else(Config::default_path)
|
.or_else(Config::default_path)
|
||||||
.context("cannot determine config path (set --config)")?;
|
.context("cannot determine config path (set --config)")?;
|
||||||
Config::load(&path).with_context(|| format!("loading {}", path.display()))
|
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<()> {
|
fn main() -> Result<()> {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
match cli.cmd {
|
match &cli.cmd {
|
||||||
Cmd::Status { path } => {
|
Cmd::Status { path } => 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 } => {
|
Cmd::Snapshot { path } => {
|
||||||
let cfg = load_config(cli.config)?;
|
let cfg = load_config(&cli.config)?;
|
||||||
let stamp = SystemTime::now()
|
match take(path, &cfg.machine.name, &stamp())? {
|
||||||
.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::Created(s) => println!("created {} {}", s.refname, s.commit),
|
||||||
Outcome::Unchanged(c) => println!("unchanged {c}"),
|
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}"));
|
||||||
|
}
|
||||||
|
if let Some(Received::FastForwarded { .. }) = &w.received {
|
||||||
|
notes.push("fast-forwarded".into());
|
||||||
|
}
|
||||||
|
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(())
|
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!("gitsync-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_gitsync"))
|
||||||
|
.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));
|
||||||
|
}
|
||||||
Reference in new issue
Block a user