feat(daemon): add groved with inotify watching, scheduler and IPC

Debounced per-repo passes, periodic full pass, exponential backoff, pause and
resume, JSON protocol over a Unix socket, activity log, grove daemon CLI client
and a systemd user unit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 13:01:30 +01:00
1 parent a631d0a90f
commit 41ef589e58
13 files changed
+1480 -1

No files matched your search

Generated
+195
View File
@@ -58,6 +58,12 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "clap"
version = "4.6.7"
@@ -117,6 +123,8 @@ dependencies = [
"anyhow",
"clap",
"grove-core",
"grove-daemon",
"serde_json",
]
[[package]]
@@ -127,6 +135,17 @@ dependencies = [
"toml",
]
[[package]]
name = "grove-daemon"
version = "0.1.0"
dependencies = [
"anyhow",
"grove-core",
"notify",
"serde",
"serde_json",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -149,12 +168,135 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "inotify"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
dependencies = [
"bitflags",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
dependencies = [
"libc",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "kqueue"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
dependencies = [
"kqueue-sys",
"libc",
]
[[package]]
name = "kqueue-sys"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
dependencies = [
"bitflags",
"libc",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mio"
version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys",
]
[[package]]
name = "notify"
version = "8.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab"
dependencies = [
"bitflags",
"inotify",
"kqueue",
"libc",
"log",
"mio",
"notify-types",
"objc2-core-foundation",
"objc2-core-services",
"walkdir",
"windows-sys",
]
[[package]]
name = "notify-types"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f"
dependencies = [
"bitflags",
]
[[package]]
name = "objc2-core-foundation"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
dependencies = [
"bitflags",
]
[[package]]
name = "objc2-core-services"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"
dependencies = [
"libc",
"objc2-core-foundation",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
@@ -179,6 +321,15 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.229"
@@ -209,6 +360,19 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
@@ -286,6 +450,31 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
@@ -306,3 +495,9 @@ name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/grove-core", "crates/grove"]
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon"]
[workspace.package]
edition = "2024"
+13
View File
@@ -0,0 +1,13 @@
[Unit]
Description=grove daemon (keeps git repos in sync across machines)
Documentation=https://git.zenvairo.es/dasemu/Grove
[Service]
Type=simple
ExecStart=%h/.local/bin/groved
Restart=on-failure
RestartSec=5
# Nothing to flush on stop: all durable state lives in git, so a plain SIGTERM is safe.
[Install]
WantedBy=default.target
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "grove-daemon"
description = "grove user daemon: file watching, scheduler and IPC server"
edition.workspace = true
version.workspace = true
license.workspace = true
[lib]
name = "grove_daemon"
[[bin]]
name = "groved"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
grove-core = { version = "0.1.0", path = "../grove-core" }
notify = "8.2.2"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
+93
View File
@@ -0,0 +1,93 @@
//! Activity log: JSON lines on disk (rotated at 5 MiB), a ring buffer in memory and live
//! subscribers (the IPC `subscribe` command).
use serde::Serialize;
use std::collections::VecDeque;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
const RING: usize = 500;
const MAX_FILE: u64 = 5 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Event {
pub ts: u64,
pub kind: String,
pub repo: Option<String>,
pub msg: String,
}
pub struct Activity {
file: Option<PathBuf>,
ring: Mutex<VecDeque<Event>>,
subs: Mutex<Vec<Sender<Event>>>,
}
pub fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
impl Activity {
pub fn new(file: Option<PathBuf>) -> Arc<Activity> {
Arc::new(Activity {
file,
ring: Mutex::new(VecDeque::new()),
subs: Mutex::new(Vec::new()),
})
}
pub fn log(&self, kind: &str, repo: Option<&str>, msg: impl Into<String>) {
let ev = Event {
ts: now_secs(),
kind: kind.to_string(),
repo: repo.map(str::to_string),
msg: msg.into(),
};
self.append(&ev);
{
let mut ring = self.ring.lock().unwrap();
if ring.len() == RING {
ring.pop_front();
}
ring.push_back(ev.clone());
}
self.subs
.lock()
.unwrap()
.retain(|s| s.send(ev.clone()).is_ok());
}
fn append(&self, ev: &Event) {
let Some(path) = &self.file else { return };
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
if std::fs::metadata(path).is_ok_and(|m| m.len() > MAX_FILE) {
let _ = std::fs::rename(path, path.with_extension("jsonl.1"));
}
if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(path)
&& let Ok(line) = serde_json::to_string(ev)
{
let _ = writeln!(f, "{line}");
}
}
pub fn recent(&self, limit: usize) -> Vec<Event> {
let ring = self.ring.lock().unwrap();
let skip = ring.len().saturating_sub(limit);
ring.iter().skip(skip).cloned().collect()
}
pub fn subscribe(&self) -> Receiver<Event> {
let (tx, rx) = channel();
self.subs.lock().unwrap().push(tx);
rx
}
}
+430
View File
@@ -0,0 +1,430 @@
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes,
//! so passes never overlap.
use crate::activity::{Activity, now_secs};
use crate::discover::discover;
use crate::ipc;
use grove_core::config::Config;
use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
const MAX_BACKOFF: Duration = Duration::from_secs(300);
#[derive(Debug, Clone)]
pub struct Settings {
pub socket: PathBuf,
pub activity_log: Option<PathBuf>,
pub remote: String,
}
impl Settings {
/// Standard locations: socket in `$XDG_RUNTIME_DIR/grove`, log in the state dir.
pub fn standard() -> Settings {
let state = Config::state_dir().unwrap_or_else(|| std::env::temp_dir().join("grove"));
Settings {
socket: ipc::default_socket_path(),
activity_log: Some(state.join("activity.jsonl")),
remote: "origin".into(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct WtStatus {
pub branch: Option<String>,
pub state: String,
}
#[derive(Debug, Clone)]
pub struct RepoStatus {
/// `idle`, `pending`, `syncing` or `error`.
pub phase: &'static str,
pub last_sync: Option<u64>,
pub last_error: Option<String>,
pub worktrees: Vec<WtStatus>,
pub failures: u32,
}
impl Default for RepoStatus {
fn default() -> Self {
RepoStatus {
phase: "idle",
last_sync: None,
last_error: None,
worktrees: Vec::new(),
failures: 0,
}
}
}
#[derive(Debug, Default)]
pub struct Shared {
pub paused: bool,
pub repos: BTreeMap<PathBuf, RepoStatus>,
}
pub enum Msg {
Changed(PathBuf),
/// Sync one repo (or all) as soon as possible.
SyncNow(Option<PathBuf>),
Shutdown,
}
#[derive(Clone)]
pub struct Ctx {
pub shared: Arc<Mutex<Shared>>,
pub activity: Arc<Activity>,
pub tx: Sender<Msg>,
pub machine: String,
}
pub struct Daemon {
pub ctx: Ctx,
socket: PathBuf,
stop: Arc<AtomicBool>,
worker: Option<JoinHandle<()>>,
server: Option<JoinHandle<()>>,
}
impl Daemon {
pub fn start(cfg: Config, st: Settings) -> std::io::Result<Daemon> {
let (tx, rx) = channel();
let ctx = Ctx {
shared: Arc::default(),
activity: Activity::new(st.activity_log.clone()),
tx,
machine: cfg.machine.name.clone(),
};
let stop = Arc::new(AtomicBool::new(false));
let server = ipc::serve(&st.socket, ctx.clone(), stop.clone())?;
let worker = {
let ctx = ctx.clone();
std::thread::spawn(move || run(cfg, st, rx, ctx))
};
ctx.activity.log("start", None, "daemon started");
Ok(Daemon {
socket: server.socket.clone(),
ctx,
stop,
worker: Some(worker),
server: Some(server.handle),
})
}
/// Stop the worker and the IPC server. Work in progress is never lost: the worker finishes
/// the pass it is running and everything else lives in git.
pub fn shutdown(mut self) {
self.stop.store(true, Ordering::SeqCst);
let _ = self.ctx.tx.send(Msg::Shutdown);
if let Some(h) = self.worker.take() {
let _ = h.join();
}
if let Some(h) = self.server.take() {
let _ = h.join();
}
let _ = std::fs::remove_file(&self.socket);
}
}
fn stamp() -> String {
static SEQ: AtomicU64 = AtomicU64::new(0);
let ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
format!("{ms}-{}", SEQ.fetch_add(1, Ordering::SeqCst))
}
/// Matches one path component against an ignore pattern: exact name or `*suffix`.
fn pattern_matches(pat: &str, name: &str) -> bool {
match pat.strip_prefix('*') {
Some(suffix) => name.ends_with(suffix),
None => name == pat,
}
}
/// True for paths whose changes must not trigger a sync: git internals and user-ignored names.
pub fn ignored(rel: &Path, extra: &[String]) -> bool {
rel.components().any(|c| {
let n = c.as_os_str().to_string_lossy();
n == ".git"
|| n == ".bare"
|| n == ".grove-stage"
|| extra.iter().any(|p| pattern_matches(p, &n))
})
}
fn repo_of<'a>(path: &Path, repos: &'a [PathBuf]) -> Option<&'a PathBuf> {
repos.iter().find(|r| path.starts_with(r))
}
struct Watch {
watcher: Option<notify::RecommendedWatcher>,
repos: Arc<Mutex<Vec<PathBuf>>>,
watched: Vec<PathBuf>,
}
fn make_watch(tx: Sender<Msg>, extra: Vec<String>, ctx: &Ctx) -> Watch {
let repos: Arc<Mutex<Vec<PathBuf>>> = Arc::default();
let cb_repos = repos.clone();
let handler = move |res: notify::Result<notify::Event>| {
let Ok(ev) = res else { return };
if matches!(ev.kind, EventKind::Access(_)) {
return;
}
let repos = cb_repos.lock().unwrap();
for p in &ev.paths {
if let Some(r) = repo_of(p, &repos)
&& let Ok(rel) = p.strip_prefix(r)
&& !ignored(rel, &extra)
{
let _ = tx.send(Msg::Changed(r.clone()));
}
}
};
let watcher = match notify::recommended_watcher(handler) {
Ok(w) => Some(w),
Err(e) => {
ctx.activity.log(
"watch_error",
None,
format!("file watching unavailable, periodic passes only: {e}"),
);
None
}
};
Watch {
watcher,
repos,
watched: Vec::new(),
}
}
impl Watch {
fn add(&mut self, repo: &Path, ctx: &Ctx) {
if self.watched.iter().any(|w| w == repo) {
return;
}
self.watched.push(repo.to_path_buf());
self.repos.lock().unwrap().push(repo.to_path_buf());
if let Some(w) = &mut self.watcher
&& let Err(e) = w.watch(repo, RecursiveMode::Recursive)
{
ctx.activity.log(
"watch_error",
Some(&repo.display().to_string()),
format!(
"cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes"
),
);
}
}
}
fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
let found = discover(root);
let mut shared = ctx.shared.lock().unwrap();
for r in &found {
shared.repos.entry(r.clone()).or_default();
}
drop(shared);
for r in &found {
watch.add(r, ctx);
}
found
}
fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let debounce = Duration::from_millis(cfg.sync.snapshot_debounce_ms);
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
let root = cfg.root_path();
let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx);
rescan(&root, &mut watch, &ctx);
let materialize = cfg.groups.iter().all(|g| g.auto_materialize);
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
let mut backoff_until: HashMap<PathBuf, Instant> = HashMap::new();
let mut next_full = Instant::now();
loop {
let now = Instant::now();
let wake = due_at
.values()
.copied()
.chain([next_full])
.min()
.unwrap_or(next_full);
let timeout = wake
.saturating_duration_since(now)
.min(Duration::from_secs(1));
match rx.recv_timeout(timeout) {
Ok(Msg::Changed(r)) => {
let at = Instant::now() + debounce;
due_at.insert(r.clone(), at);
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(&r)
&& s.phase == "idle"
{
s.phase = "pending";
}
}
Ok(Msg::SyncNow(Some(r))) => {
backoff_until.remove(&r);
due_at.insert(r, Instant::now());
}
Ok(Msg::SyncNow(None)) => {
backoff_until.clear();
next_full = Instant::now();
}
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
}
if ctx.shared.lock().unwrap().paused {
continue;
}
let now = Instant::now();
if now >= next_full {
for r in rescan(&root, &mut watch, &ctx) {
due_at.insert(r, now);
}
next_full = now + fetch_every;
}
let mut due: Vec<PathBuf> = due_at
.iter()
.filter(|(_, t)| **t <= now)
.map(|(r, _)| r.clone())
.collect();
due.sort();
for r in due {
if let Some(until) = backoff_until.get(&r).filter(|u| **u > now) {
due_at.insert(r, *until);
continue;
}
due_at.remove(&r);
let failures = pass(&r, &cfg, &st, materialize, &ctx);
if failures == 0 {
backoff_until.remove(&r);
} else {
let wait =
Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF);
backoff_until.insert(r, Instant::now() + wait);
}
if ctx.shared.lock().unwrap().paused {
break;
}
}
}
ctx.activity.log("stop", None, "daemon stopped");
}
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) -> u32 {
let name = repo.display().to_string();
set_phase(ctx, repo, "syncing");
let opts = Options {
machine: cfg.machine.name.clone(),
stamp: stamp(),
remote: st.remote.clone(),
offline: false,
materialize,
};
let result = sync_repo(repo, &opts);
let mut shared = ctx.shared.lock().unwrap();
let status = shared.repos.entry(repo.to_path_buf()).or_default();
let mut errors: Vec<String> = Vec::new();
match result {
Err(e) => errors.push(e.to_string()),
Ok(rep) => {
errors.extend(rep.fetch_error.clone());
let mut now_wts = Vec::new();
for w in &rep.worktrees {
let branch = w.branch.clone().unwrap_or_else(|| "(detached)".into());
let state = format!("{:?}", w.state).to_lowercase();
if let Some(kind) = w.snapshot {
ctx.activity
.log("snapshot", Some(&name), format!("{branch}: {kind}"));
}
match &w.received {
Some(Received::FastForwarded { .. }) => {
ctx.activity
.log("fast_forward", Some(&name), branch.clone())
}
Some(Received::Declined(why)) => ctx.activity.log(
"declined",
Some(&name),
format!("{branch}: not fast-forwarded: {why}"),
),
_ => {}
}
if let Some((m, a)) = &w.applied {
ctx.activity
.log("applied", Some(&name), format!("{branch}: {a:?} from {m}"));
}
let prev = status
.worktrees
.iter()
.find(|p| p.branch.as_deref() == Some(&branch))
.map(|p| p.state.clone());
if prev.as_deref() != Some(&state) {
ctx.activity
.log("state", Some(&name), format!("{branch}: {state}"));
}
errors.extend(w.errors.iter().map(|e| format!("{branch}: {e}")));
now_wts.push(WtStatus {
branch: w.branch.clone(),
state,
});
}
status.worktrees = now_wts;
for p in &rep.materialized {
ctx.activity
.log("materialized", Some(&name), p.display().to_string());
}
for a in &rep.archived {
ctx.activity.log("archived", Some(&name), format!("{a:?}"));
}
}
}
if errors.is_empty() {
status.phase = "idle";
status.failures = 0;
status.last_error = None;
status.last_sync = Some(now_secs());
} else {
status.phase = "error";
status.failures += 1;
status.last_error = Some(errors.join("; "));
ctx.activity.log("error", Some(&name), errors.join("; "));
}
status.failures
}
fn set_phase(ctx: &Ctx, repo: &Path, phase: &'static str) {
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(repo) {
s.phase = phase;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ignores_git_internals_and_patterns() {
let extra = vec!["node_modules".to_string(), "*.swp".to_string()];
assert!(ignored(Path::new(".bare/objects/ab"), &extra));
assert!(ignored(Path::new("main/.git"), &extra));
assert!(ignored(Path::new("main/node_modules/x/y.js"), &extra));
assert!(ignored(Path::new("main/src/.a.rs.swp"), &extra));
assert!(!ignored(Path::new("main/src/a.rs"), &extra));
}
}
+59
View File
@@ -0,0 +1,59 @@
//! Finds the repos managed under the workspace root: `root/<repo>` or `root/<group>/<repo>`,
//! where a repo has a `.bare` directory (bare + worktrees layout) or a `.git`.
use std::path::{Path, PathBuf};
fn is_repo(p: &Path) -> bool {
p.join(".bare").is_dir() || p.join(".git").exists()
}
fn subdirs(p: &Path) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = std::fs::read_dir(p)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path())
.collect();
v.sort();
v
}
pub fn discover(root: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
for child in subdirs(root) {
if is_repo(&child) {
out.push(child);
} else {
out.extend(subdirs(&child).into_iter().filter(|g| is_repo(g)));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_repos_at_depth_one_and_two_and_skips_hidden() {
let base = std::env::temp_dir().join(format!("grove-disc-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for d in [
"a/.git",
"grp/b/.bare",
"grp/plain",
".hidden/.git",
"c/inner/.git",
] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
let found = discover(&base);
assert_eq!(
found,
vec![base.join("a"), base.join("c/inner"), base.join("grp/b")]
);
std::fs::remove_dir_all(&base).unwrap();
}
}
+211
View File
@@ -0,0 +1,211 @@
//! Local IPC: a Unix socket speaking line-delimited JSON, protocol version 1.
//!
//! Request: `{"v":1,"cmd":"status"|"ping"|"pause"|"resume"|"sync"|"log"|"subscribe", ...}`
//! Response: `{"v":1,"ok":true,"data":...}` or `{"v":1,"ok":false,"error":"..."}`.
//! After `subscribe` the server keeps the connection open and streams `{"v":1,"event":{...}}`.
use crate::activity::now_secs;
use crate::daemon::{Ctx, Msg};
use serde::Deserialize;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::DirBuilderExt;
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;
use std::time::Duration;
pub const PROTOCOL: u32 = 1;
pub struct Server {
pub socket: PathBuf,
pub handle: JoinHandle<()>,
}
/// `$XDG_RUNTIME_DIR/grove/grove.sock`, falling back to the state dir.
pub fn default_socket_path() -> PathBuf {
let base = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.or_else(grove_core::config::Config::state_dir)
.unwrap_or_else(std::env::temp_dir);
base.join("grove").join("grove.sock")
}
#[derive(Deserialize)]
struct Request {
v: u32,
cmd: String,
#[serde(default)]
repo: Option<String>,
#[serde(default)]
limit: Option<usize>,
}
pub fn serve(socket: &Path, ctx: Ctx, stop: Arc<AtomicBool>) -> std::io::Result<Server> {
if let Some(dir) = socket.parent() {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
}
if socket.exists() {
if UnixStream::connect(socket).is_ok() {
return Err(std::io::Error::new(
std::io::ErrorKind::AddrInUse,
format!(
"another daemon is already listening on {}",
socket.display()
),
));
}
std::fs::remove_file(socket)?; // stale socket from a crashed daemon
}
let listener = UnixListener::bind(socket)?;
listener.set_nonblocking(true)?;
let handle = std::thread::spawn(move || {
while !stop.load(Ordering::SeqCst) {
match listener.accept() {
Ok((conn, _)) => {
let ctx = ctx.clone();
let stop = stop.clone();
std::thread::spawn(move || connection(conn, ctx, stop));
}
Err(_) => std::thread::sleep(Duration::from_millis(50)),
}
}
});
Ok(Server {
socket: socket.to_path_buf(),
handle,
})
}
fn reply(conn: &mut UnixStream, v: Value) -> bool {
writeln!(conn, "{v}").is_ok()
}
fn err(msg: &str) -> Value {
json!({"v": PROTOCOL, "ok": false, "error": msg})
}
fn ok(data: Value) -> Value {
json!({"v": PROTOCOL, "ok": true, "data": data})
}
fn connection(mut conn: UnixStream, ctx: Ctx, stop: Arc<AtomicBool>) {
let _ = conn.set_nonblocking(false);
let Ok(read_half) = conn.try_clone() else {
return;
};
for line in BufReader::new(read_half).lines() {
let Ok(line) = line else { return };
if line.trim().is_empty() {
continue;
}
let req: Request = match serde_json::from_str(&line) {
Ok(r) => r,
Err(e) => {
if !reply(&mut conn, err(&format!("bad request: {e}"))) {
return;
}
continue;
}
};
if req.v != PROTOCOL {
let msg = format!(
"unsupported protocol version {} (server speaks {PROTOCOL})",
req.v
);
if !reply(&mut conn, err(&msg)) {
return;
}
continue;
}
if req.cmd == "subscribe" {
let rx = ctx.activity.subscribe();
if !reply(&mut conn, ok(json!("subscribed"))) {
return;
}
while !stop.load(Ordering::SeqCst) {
if let Ok(ev) = rx.recv_timeout(Duration::from_secs(1))
&& !reply(&mut conn, json!({"v": PROTOCOL, "event": ev}))
{
return;
}
}
return;
}
if !reply(&mut conn, handle(&req, &ctx)) {
return;
}
}
}
fn handle(req: &Request, ctx: &Ctx) -> Value {
match req.cmd.as_str() {
"ping" => ok(json!("pong")),
"status" => {
let s = ctx.shared.lock().unwrap();
let repos: Vec<Value> = s
.repos
.iter()
.map(|(p, r)| {
json!({
"path": p.display().to_string(),
"phase": r.phase,
"last_sync": r.last_sync,
"last_error": r.last_error,
"failures": r.failures,
"worktrees": r.worktrees.iter()
.map(|w| json!({"branch": w.branch, "state": w.state}))
.collect::<Vec<_>>(),
})
})
.collect();
ok(
json!({"machine": ctx.machine, "paused": s.paused, "now": now_secs(), "repos": repos}),
)
}
"pause" | "resume" => {
let paused = req.cmd == "pause";
ctx.shared.lock().unwrap().paused = paused;
ctx.activity.log(
&req.cmd,
None,
if paused {
"sync paused"
} else {
"sync resumed"
},
);
if !paused {
let _ = ctx.tx.send(Msg::SyncNow(None));
}
ok(json!({"paused": paused}))
}
"sync" => {
let target = req.repo.as_ref().map(PathBuf::from);
if let Some(t) = &target
&& !ctx.shared.lock().unwrap().repos.contains_key(t)
{
return err("unknown repo");
}
let _ = ctx.tx.send(Msg::SyncNow(target));
ok(json!("queued"))
}
"log" => ok(json!(ctx.activity.recent(req.limit.unwrap_or(50)))),
other => err(&format!("unknown command {other:?}")),
}
}
/// Send one request and read one response. For use by the CLI and tests.
pub fn request(socket: &Path, req: &Value) -> std::io::Result<Value> {
let mut conn = UnixStream::connect(socket)?;
conn.set_read_timeout(Some(Duration::from_secs(10)))?;
writeln!(conn, "{req}")?;
let mut line = String::new();
BufReader::new(conn).read_line(&mut line)?;
serde_json::from_str(&line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
+11
View File
@@ -0,0 +1,11 @@
//! grove user daemon: watches managed repos, debounces changes, runs sync passes on a schedule
//! and serves a small JSON protocol over a Unix socket. All durable state lives in git; the
//! daemon itself holds nothing that a crash could lose.
pub mod activity;
pub mod daemon;
pub mod discover;
pub mod ipc;
pub use activity::{Activity, Event};
pub use daemon::{Daemon, Settings};
+36
View File
@@ -0,0 +1,36 @@
//! `groved`: the grove user daemon (run it as a systemd user service, see `contrib/`).
use anyhow::{Context, Result};
use grove_core::config::Config;
use grove_daemon::{Daemon, Settings};
use std::path::PathBuf;
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let mut config: Option<PathBuf> = None;
while let Some(a) = args.next() {
match a.as_str() {
"--config" => config = Some(args.next().context("--config needs a path")?.into()),
"-h" | "--help" => {
println!("groved [--config PATH]\nKeeps the repos under root.path in sync.");
return Ok(());
}
other => anyhow::bail!("unknown argument {other:?}"),
}
}
let path = config
.or_else(Config::default_path)
.context("cannot determine config path")?;
let cfg = Config::load(&path)?;
let st = Settings::standard();
eprintln!(
"groved: machine {:?}, root {}, socket {}",
cfg.machine.name,
cfg.root_path().display(),
st.socket.display()
);
let _daemon = Daemon::start(cfg, st).context("cannot start daemon")?;
loop {
std::thread::park();
}
}
+309
View File
@@ -0,0 +1,309 @@
use grove_core::config::Config;
use grove_daemon::{Daemon, Settings, ipc};
use serde_json::json;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args(args)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@t")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@t")
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?} in {}: {}",
dir.display(),
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn wait_until(what: &str, secs: u64, mut f: impl FnMut() -> bool) {
let end = Instant::now() + Duration::from_secs(secs);
while Instant::now() < end {
if f() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
panic!("timed out waiting for {what}");
}
struct World {
base: PathBuf,
remote: PathBuf,
}
fn tmpdir(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("grove-dt-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
fs::create_dir_all(&d).unwrap();
d
}
/// A bare remote plus one seeded clone per machine under `<base>/<machine>/repo`.
fn world(tag: &str, machines: &[&str]) -> World {
let base = tmpdir(tag);
let remote = base.join("remote.git");
fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "-b", "main"]);
let seed = base.join("seed");
fs::create_dir_all(&seed).unwrap();
git(&seed, &["init", "-q", "-b", "main"]);
fs::write(seed.join("a.txt"), "one\n").unwrap();
git(&seed, &["add", "-A"]);
git(&seed, &["commit", "-qm", "init"]);
git(
&seed,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&seed, &["push", "-q", "origin", "main"]);
for m in machines {
let dir = base.join(m);
fs::create_dir_all(&dir).unwrap();
git(&dir, &["clone", "-q", remote.to_str().unwrap(), "repo"]);
}
World { base, remote }
}
fn config(w: &World, machine: &str, debounce_ms: u64, fetch_s: u64) -> Config {
Config::parse(&format!(
"[machine]\nname = \"{machine}\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = {debounce_ms}\nfetch_interval_s = {fetch_s}\n",
w.base.join(machine).display()
))
.unwrap()
}
fn settings(w: &World, machine: &str) -> Settings {
Settings {
socket: w.base.join(format!("{machine}.sock")),
activity_log: Some(w.base.join(format!("{machine}.jsonl"))),
remote: "origin".into(),
}
}
fn start(w: &World, machine: &str) -> Daemon {
Daemon::start(config(w, machine, 200, 2), settings(w, machine)).unwrap()
}
#[test]
fn edit_on_a_shows_up_on_b() {
let w = world("converge", &["pca", "pcb"]);
let a = start(&w, "pca");
let b = start(&w, "pcb");
let file_a = w.base.join("pca/repo/new.txt");
fs::write(&file_a, "hello\n").unwrap();
fs::write(w.base.join("pca/repo/a.txt"), "one\nedited\n").unwrap();
let on_b = w.base.join("pcb/repo/new.txt");
wait_until("new.txt on B", 30, || {
fs::read_to_string(&on_b).is_ok_and(|s| s == "hello\n")
});
assert_eq!(
fs::read_to_string(w.base.join("pcb/repo/a.txt")).unwrap(),
"one\nedited\n"
);
// The user's branch on A was never touched by the daemon.
assert_eq!(
git(&w.base.join("pca/repo"), &["log", "--oneline"])
.lines()
.count(),
1
);
a.shutdown();
b.shutdown();
}
#[test]
fn committed_work_fast_forwards_the_other_machine() {
let w = world("ff", &["pca", "pcb"]);
let a = start(&w, "pca");
let b = start(&w, "pcb");
let ra = w.base.join("pca/repo");
fs::write(ra.join("c.txt"), "committed\n").unwrap();
git(&ra, &["add", "-A"]);
git(&ra, &["commit", "-qm", "c"]);
git(&ra, &["push", "-q", "origin", "main"]);
let rb = w.base.join("pcb/repo");
wait_until("B fast-forwarded", 30, || rb.join("c.txt").exists());
wait_until("B synced", 30, || {
git(&rb, &["status", "--porcelain"]).is_empty()
&& git(&rb, &["log", "--oneline"]).lines().count() == 2
});
a.shutdown();
b.shutdown();
}
#[test]
fn ipc_status_pause_resume_log_and_subscribe() {
let w = world("ipc", &["pca"]);
let st = settings(&w, "pca");
let sock = st.socket.clone();
let d = Daemon::start(config(&w, "pca", 200, 2), st).unwrap();
assert_eq!(
ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).unwrap()["data"],
"pong"
);
let bad = ipc::request(&sock, &json!({"v":99,"cmd":"ping"})).unwrap();
assert_eq!(bad["ok"], false);
let unknown = ipc::request(&sock, &json!({"v":1,"cmd":"nope"})).unwrap();
assert_eq!(unknown["ok"], false);
let repo = w.base.join("pca/repo");
wait_until("status lists the repo", 10, || {
let s = ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap();
s["data"]["repos"].as_array().is_some_and(|r| r.len() == 1)
});
// While paused, edits must not produce a snapshot.
assert_eq!(
ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap()["data"]["paused"],
true
);
fs::write(repo.join("p.txt"), "paused\n").unwrap();
std::thread::sleep(Duration::from_secs(3));
assert!(
git(&repo, &["for-each-ref", "refs/sync/"]).is_empty(),
"snapshot while paused"
);
// Resume: the pending change is snapshotted; subscribers see it.
let mut sub = std::os::unix::net::UnixStream::connect(&sock).unwrap();
use std::io::{BufRead, BufReader, Write};
writeln!(sub, "{}", json!({"v":1,"cmd":"subscribe"})).unwrap();
sub.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
let mut rd = BufReader::new(sub);
let mut line = String::new();
rd.read_line(&mut line).unwrap();
assert!(line.contains("subscribed"));
ipc::request(&sock, &json!({"v":1,"cmd":"resume"})).unwrap();
let mut saw_snapshot = false;
for _ in 0..20 {
line.clear();
if rd.read_line(&mut line).unwrap() == 0 {
break;
}
if line.contains("\"kind\":\"snapshot\"") {
saw_snapshot = true;
break;
}
}
assert!(saw_snapshot, "no snapshot event streamed");
assert!(git(&repo, &["for-each-ref", "refs/sync/"]).contains("refs/sync/pca/main"));
let log = ipc::request(&sock, &json!({"v":1,"cmd":"log","limit":100})).unwrap();
let kinds: Vec<&str> = log["data"]
.as_array()
.unwrap()
.iter()
.map(|e| e["kind"].as_str().unwrap())
.collect();
assert!(
kinds.contains(&"pause") && kinds.contains(&"resume") && kinds.contains(&"snapshot"),
"{kinds:?}"
);
assert!(
w.base.join("pca.jsonl").exists(),
"activity log file written"
);
d.shutdown();
assert!(!sock.exists(), "socket removed on shutdown");
let _ = &w.remote;
}
#[test]
fn second_daemon_on_same_socket_is_refused_and_stale_socket_is_reused() {
let w = world("sock", &["pca"]);
let st = settings(&w, "pca");
let d = Daemon::start(config(&w, "pca", 200, 2), st.clone()).unwrap();
assert!(Daemon::start(config(&w, "pca", 200, 2), st.clone()).is_err());
d.shutdown();
// A leftover socket file with nobody listening must not block startup.
fs::write(&st.socket, "").unwrap();
let d = Daemon::start(config(&w, "pca", 200, 2), st).unwrap();
d.shutdown();
}
#[test]
fn killing_the_daemon_loses_nothing_and_a_restart_recovers() {
let w = world("crash", &["pca"]);
let repo = w.base.join("pca/repo");
let cfg_path = w.base.join("config.toml");
fs::write(
&cfg_path,
format!(
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
w.base.join("pca").display()
),
)
.unwrap();
let runtime = w.base.join("run");
fs::create_dir_all(&runtime).unwrap();
let spawn = || {
Command::new(env!("CARGO_BIN_EXE_groved"))
.arg("--config")
.arg(&cfg_path)
.env("XDG_RUNTIME_DIR", &runtime)
.env("XDG_STATE_HOME", w.base.join("state"))
.env("GIT_AUTHOR_NAME", "t")
.spawn()
.unwrap()
};
let mut child = spawn();
std::thread::sleep(Duration::from_millis(300));
fs::write(repo.join("wip.txt"), "precious\n").unwrap();
// Kill at an arbitrary moment: maybe before, during or after a pass.
std::thread::sleep(Duration::from_millis(400));
child.kill().unwrap();
child.wait().unwrap();
assert_eq!(
fs::read_to_string(repo.join("wip.txt")).unwrap(),
"precious\n"
);
assert!(
!repo.join(".git/index.lock").exists(),
"stale index.lock after kill"
);
git(&repo, &["fsck", "--no-dangling"]);
// Restart over the stale socket: the snapshot is (re)taken and the work is still there.
let mut child = spawn();
wait_until("snapshot after restart", 30, || {
git(&repo, &["for-each-ref", "refs/sync/"]).contains("refs/sync/pca/main")
});
assert_eq!(
fs::read_to_string(repo.join("wip.txt")).unwrap(),
"precious\n"
);
child.kill().unwrap();
child.wait().unwrap();
}
#[test]
fn work_in_progress_then_committed_on_a_leaves_b_clean() {
let w = world("wipcommit", &["pca", "pcb"]);
let a = start(&w, "pca");
let b = start(&w, "pcb");
let ra = w.base.join("pca/repo");
let rb = w.base.join("pcb/repo");
fs::write(ra.join("w.txt"), "wip\n").unwrap();
wait_until("WIP on B", 30, || rb.join("w.txt").exists());
git(&ra, &["add", "-A"]);
git(&ra, &["commit", "-qm", "w"]);
git(&ra, &["push", "-q", "origin", "main"]);
wait_until("B clean at the new commit", 30, || {
git(&rb, &["status", "--porcelain"]).is_empty()
&& git(&rb, &["log", "--oneline"]).lines().count() == 2
});
assert_eq!(fs::read_to_string(rb.join("w.txt")).unwrap(), "wip\n");
a.shutdown();
b.shutdown();
}
+2
View File
@@ -8,3 +8,5 @@ version.workspace = true
anyhow = "1.0.104"
clap = { version = "4.6.7", features = ["derive"] }
grove-core = { version = "0.1.0", path = "../grove-core" }
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
serde_json = "1.0.154"
+100
View File
@@ -49,6 +49,28 @@ enum Cmd {
},
/// Check the local setup
Doctor,
/// Talk to the running daemon (`groved`)
Daemon {
#[command(subcommand)]
action: DaemonCmd,
},
}
#[derive(Subcommand)]
enum DaemonCmd {
/// Show every managed repo and its state
Status,
/// Stop syncing until `resume`
Pause,
/// Resume syncing (runs a full pass right away)
Resume,
/// Sync now: one repo (path as shown by `status`) or all
Sync { repo: Option<PathBuf> },
/// Show recent activity
Log {
#[arg(long, default_value_t = 30)]
limit: usize,
},
}
fn load_config(arg: &Option<PathBuf>) -> Result<Config> {
@@ -66,9 +88,87 @@ fn stamp() -> String {
.to_string()
}
fn daemon(action: &DaemonCmd) -> Result<()> {
use serde_json::json;
let socket = grove_daemon::ipc::default_socket_path();
let ask = |req: serde_json::Value| -> Result<serde_json::Value> {
let resp = grove_daemon::ipc::request(&socket, &req).with_context(|| {
format!(
"cannot reach the daemon at {} (is groved running?)",
socket.display()
)
})?;
if resp["ok"] != true {
bail!(
"daemon error: {}",
resp["error"].as_str().unwrap_or("unknown")
);
}
Ok(resp["data"].clone())
};
match action {
DaemonCmd::Status => {
let d = ask(json!({"v": 1, "cmd": "status"}))?;
println!(
"machine {} {}",
d["machine"].as_str().unwrap_or("?"),
if d["paused"] == true {
"PAUSED"
} else {
"running"
}
);
for r in d["repos"].as_array().into_iter().flatten() {
println!(
"{} [{}]",
r["path"].as_str().unwrap_or("?"),
r["phase"].as_str().unwrap_or("?")
);
for w in r["worktrees"].as_array().into_iter().flatten() {
println!(
" {:<24} {}",
w["branch"].as_str().unwrap_or("(detached)"),
w["state"].as_str().unwrap_or("?")
);
}
if let Some(e) = r["last_error"].as_str() {
println!(" error: {e}");
}
}
}
DaemonCmd::Pause => {
ask(json!({"v": 1, "cmd": "pause"}))?;
println!("paused");
}
DaemonCmd::Resume => {
ask(json!({"v": 1, "cmd": "resume"}))?;
println!("resumed");
}
DaemonCmd::Sync { repo } => {
let repo = repo.as_ref().map(|p| p.display().to_string());
ask(json!({"v": 1, "cmd": "sync", "repo": repo}))?;
println!("queued");
}
DaemonCmd::Log { limit } => {
let d = ask(json!({"v": 1, "cmd": "log", "limit": limit}))?;
for e in d.as_array().into_iter().flatten() {
println!(
"{} {:<12} {} {}",
e["ts"],
e["kind"].as_str().unwrap_or("?"),
e["repo"].as_str().unwrap_or("-"),
e["msg"].as_str().unwrap_or("")
);
}
}
}
Ok(())
}
fn main() -> Result<()> {
let cli = Cli::parse();
match &cli.cmd {
Cmd::Daemon { action } => daemon(action),
Cmd::Status { path } => status(path),
Cmd::Snapshot { path } => {
let cfg = load_config(&cli.config)?;