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

+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();
}
}