Merge pull request 'feat: phases 3-5 (providers, secrets, resolve, GUI, packaging)' (#3) from feat/providers into development

Reviewed-on: #3
This commit is contained in:
dasemu committed 2026-11-16 13:19:25 +00:00
commit 251bfe3685
49 files changed
+6129 -44

No files matched your search

+5 -1
View File
@@ -1 +1,5 @@
# No environment variables are read yet. Add names only (never values) as they appear.
# grove reads no .env file. Provider tokens normally live in the system keyring (`grove login`).
# Headless override (CI, servers without a Secret Service): GROVE_TOKEN_<ID>, where <ID> is the provider
# id upper-cased with non-alphanumerics replaced by `_`. Example for a provider called "home":
# GROVE_TOKEN_HOME=
# GROVE_BIN= # GUI shell only: path of the grove CLI (default: `grove` from PATH)
+9 -5
View File
@@ -3,23 +3,27 @@
## Overview
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 implemented and validated against the real Gitea with two simulated machines (real two-PC run still pending)**: `grove-core` + `grove` CLI (`status`, `snapshot`, `add`, `sync`, `doctor`); daemon (`groved`, Phase 2) implemented (not yet run on the real two PCs); GUI and providers do not exist yet. Do not start a
new phase before its predecessor's results are written to `docs/`.
Rust workspace: `grove-core`, `grove` (CLI), `grove-daemon` (`groved`), `grove-providers` (Gitea/Forgejo/GitHub),
`grove-bridge` (localhost HTTP bridge for the GUI), plus `gui/ui` (plain HTML/JS) and `gui/src-tauri` (Tauri shell,
outside the workspace, never compiled yet). Phases 0-5 are implemented; the real two-PC run is still pending.
Do not start new work before the previous results are written to `docs/`.
## Commands
- Check shell scripts: `for f in spikes/*.sh; do bash -n "$f"; done`
- Throwaway Forgejo (dev only, Podman): `spikes/forgejo-up.sh`, then `spikes/phase0.sh`
- Rust: `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, `cargo test`
- Daemon: `cargo run -p grove-daemon --bin groved -- --config PATH`; client `grove daemon status`
- GUI in a browser: `cargo run -p grove-bridge -- --ui gui/ui`; Tauri shell: see `docs/phase3.md`
- Package: `cargo build --release --workspace && cargo deb -p grove --no-build`
- Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
## Architecture
See `docs/` (`phase0-spike.md`, `phase1.md`, `phase2.md`, `DECISIONS.md`). Git is the storage layer; shell out to
See `docs/` (`phase0-spike.md` ... `phase5.md`, `DECISIONS.md`). Git is the storage layer; shell out to
system `git`; snapshots use a temp `GIT_INDEX_FILE` + `commit-tree`, never touching the
user's branch or index.
## Conventions
- Dependencies: serde+toml (config), clap+anyhow (CLI), notify+serde_json (daemon), approved. Ask before adding more.
- Dependencies: serde+toml, clap+anyhow, notify+serde_json, ureq, keyring, age, tauri v2 (GUI shell), 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
+2902 -8
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon"]
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon", "crates/grove-providers", "crates/grove-bridge"]
[workspace.package]
edition = "2024"
+3
View File
@@ -5,3 +5,6 @@
- `Git::run` trims stdout, which also eats the leading space of the first `status --porcelain` line (` M x` becomes `M x`). Don't assert on that format via `run`.
- Fetch other machines' snapshots into `refs/sync-remote/*`, never into `refs/sync/*`, or a fetch can clobber this machine's own refs.
- Run tests that create many temp repos with unique dir names (pid + nanos); the shared `tests/common` helper does this.
- Bare-layout clones must set upstream tracking per branch, or `status` silently reports Synced for Behind/Diverged. Assert tracking in tests of any clone path.
- Unix socket paths are limited to ~100 bytes: use a short `XDG_RUNTIME_DIR` (e.g. `/tmp/gd`) when running a daemon from deep scratch dirs.
- Mock-server tests must parse the JSON request body; pretty-printed JSON breaks string asserts.
+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=/usr/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
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "grove-bridge"
description = "Backend of the grove GUI: daemon IPC + allow-listed CLI calls, and a localhost dev server"
edition.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
anyhow = "1.0.104"
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
serde_json = "1.0.154"
toml = "1.2.1"
+175
View File
@@ -0,0 +1,175 @@
//! Everything the GUI needs from the machine, behind three calls. The Tauri shell and the
//! localhost dev server both expose exactly these.
use serde_json::{Value, json};
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
/// `grove` subcommands the GUI may run. Everything else is refused.
const ALLOWED: &[&str] = &[
"init",
"login",
"new",
"import",
"config-repo-init",
"bootstrap",
"resolve",
"secrets",
"sync",
"status",
];
pub struct Bridge {
pub grove_bin: PathBuf,
pub config: Option<PathBuf>,
pub socket: PathBuf,
}
impl Bridge {
/// Forwards one IPC request to the daemon. An unreachable daemon is a normal answer.
pub fn ipc(&self, req: &Value) -> Value {
grove_daemon::ipc::request(&self.socket, req).unwrap_or_else(
|e| json!({"v": 1, "ok": false, "offline": true, "error": format!("daemon not reachable: {e}")}),
)
}
/// Runs an allow-listed `grove` subcommand. `stdin` is passed through (used by `login`).
pub fn cli(&self, args: &[String], stdin: &str) -> Value {
let Some(sub) = args.first() else {
return json!({"ok": false, "output": "no command"});
};
if !ALLOWED.contains(&sub.as_str()) {
return json!({"ok": false, "output": format!("command {sub:?} is not allowed from the GUI")});
}
if let Err(e) = validate(args) {
return json!({"ok": false, "output": format!("rejected: {e}")});
}
let mut cmd = Command::new(&self.grove_bin);
if let Some(c) = &self.config {
cmd.arg("--config").arg(c);
}
cmd.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut run = || -> std::io::Result<std::process::Output> {
let mut child = cmd.spawn()?;
// Feed stdin from a thread so a chatty child cannot deadlock against a full pipe.
let writer = child.stdin.take().map(|mut si| {
let data = stdin.to_owned();
std::thread::spawn(move || {
let _ = si.write_all(data.as_bytes());
})
});
let out = child.wait_with_output();
if let Some(w) = writer {
let _ = w.join();
}
out
};
match run() {
Ok(o) => {
let mut text = String::from_utf8_lossy(&o.stdout).into_owned();
text.push_str(&String::from_utf8_lossy(&o.stderr));
json!({"ok": o.status.success(), "output": text.trim()})
}
Err(e) => {
json!({"ok": false, "output": format!("cannot run {}: {e}", self.grove_bin.display())})
}
}
}
/// `config.toml` as JSON (it holds no secrets), or `None` before onboarding.
pub fn config_json(&self) -> Option<Value> {
let p = self.config.clone().or_else(grove_core_default_config)?;
let t: toml::Value = toml::from_str(&std::fs::read_to_string(p).ok()?).ok()?;
serde_json::to_value(t).ok()
}
}
/// Per-command flag table: (flags without value, flags taking one value).
fn flag_spec(sub: &str) -> (&'static [&'static str], &'static [&'static str]) {
match sub {
"init" => (&[], &["--machine", "--root", "--provider", "--kind", "--group", "--config-repo", "--url"]),
"new" => (&["--public"], &[]),
"resolve" => (&["--take-remote", "--keep-local"], &["--save-as"]),
_ => (&[], &[]),
}
}
/// Strict argument shape: only known flags, no option-like positionals or values (so nothing can
/// smuggle in `--config`, `--force`, `--compare`, ...), and `secrets` limited to init/pull/rekey.
pub fn validate(args: &[String]) -> Result<(), String> {
let sub = args.first().map(String::as_str).unwrap_or("");
let (bools, valued) = flag_spec(sub);
let mut it = args[1..].iter().enumerate();
while let Some((i, a)) = it.next() {
if a.starts_with('-') {
if valued.contains(&a.as_str()) {
match it.next() {
Some((_, v)) if !v.starts_with('-') => {}
_ => return Err(format!("{a} needs a value")),
}
} else if !bools.contains(&a.as_str()) {
return Err(format!("flag {a:?} is not allowed from the GUI"));
}
} else if sub == "secrets" && i == 0 && !["init", "pull", "rekey"].contains(&a.as_str()) {
return Err(format!("secrets {a:?} is not allowed from the GUI"));
}
}
if sub == "secrets" && args.len() != 2 {
return Err("secrets takes exactly one action".into());
}
Ok(())
}
fn grove_core_default_config() -> 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("grove/config.toml"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_blocks_smuggled_flags() {
let v = |a: &[&str]| validate(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert!(v(&["sync", "--config", "/x"]).is_err());
assert!(v(&["init", "--force"]).is_err());
assert!(v(&["resolve", "/p", "--compare"]).is_err());
assert!(v(&["resolve", "/p", "--save-as", "--take-remote"]).is_err());
assert!(v(&["secrets", "push", "f"]).is_err());
assert!(v(&["new", "g", "-x"]).is_err());
assert!(v(&["resolve", "/p", "--save-as", "b", "--take-remote"]).is_ok());
assert!(v(&["new", "g", "n", "--public"]).is_ok());
assert!(v(&["secrets", "pull"]).is_ok());
}
fn bridge() -> Bridge {
Bridge {
grove_bin: "/nonexistent/grove".into(),
config: None,
socket: "/nonexistent/sock".into(),
}
}
#[test]
fn only_allow_listed_subcommands_run() {
let r = bridge().cli(&["daemon".into(), "pause".into()], "");
assert_eq!(r["ok"], false);
assert!(r["output"].as_str().unwrap().contains("not allowed"));
let r = bridge().cli(&["sync".into()], "");
assert!(r["output"].as_str().unwrap().contains("cannot run"));
}
#[test]
fn offline_daemon_is_a_regular_answer() {
let r = bridge().ipc(&json!({"v": 1, "cmd": "status"}));
assert_eq!(r["ok"], false);
assert_eq!(r["offline"], true);
}
}
+155
View File
@@ -0,0 +1,155 @@
//! Localhost dev server for the GUI frontend: static files plus the `Bridge` calls over HTTP.
//! Binds to 127.0.0.1 only. POSTs need the `X-Grove: 1` header (not sendable cross-origin
//! without a preflight, which is never answered); the Host must be exactly 127.0.0.1:<port> or
//! localhost:<port> and any Origin must match too (DNS rebinding).
use anyhow::{Context, Result};
use grove_bridge::Bridge;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::PathBuf;
use std::sync::Arc;
fn arg(name: &str) -> Option<String> {
let a: Vec<String> = std::env::args().collect();
a.iter()
.position(|x| x == name)
.and_then(|i| a.get(i + 1))
.cloned()
}
fn main() -> Result<()> {
let ui = PathBuf::from(arg("--ui").unwrap_or_else(|| "gui/ui".into()));
let port: u16 = arg("--port")
.map_or(Ok(4780), |p| p.parse())
.context("bad --port")?;
let bridge = Arc::new(Bridge {
grove_bin: arg("--grove-bin").map_or_else(|| "grove".into(), PathBuf::from),
config: arg("--config").map(PathBuf::from),
socket: arg("--socket")
.map(PathBuf::from)
.unwrap_or_else(grove_daemon::ipc::default_socket_path),
});
let l = TcpListener::bind(("127.0.0.1", port)).with_context(|| format!("port {port}"))?;
eprintln!(
"grove GUI dev server on http://127.0.0.1:{port}/ (ui: {})",
ui.display()
);
for s in l.incoming().filter_map(Result::ok) {
let (b, ui) = (bridge.clone(), ui.clone());
let _ = s.set_read_timeout(Some(std::time::Duration::from_secs(10)));
std::thread::spawn(move || {
let _ = handle(s, &b, &ui, port);
});
}
Ok(())
}
fn respond(s: &mut TcpStream, status: &str, ctype: &str, body: &[u8]) -> std::io::Result<()> {
write!(
s,
"HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
body.len()
)?;
s.write_all(body)
}
fn handle(mut s: TcpStream, b: &Bridge, ui: &std::path::Path, port: u16) -> std::io::Result<()> {
// Cap what a client can make us buffer while reading the request head.
let mut r = BufReader::new(s.try_clone()?.take(64 * 1024));
let mut line = String::new();
r.read_line(&mut line)?;
let mut it = line.split_whitespace();
let (method, path) = (
it.next().unwrap_or("").to_string(),
it.next().unwrap_or("/").to_string(),
);
let (mut len, mut host, mut marker, mut origin) = (0usize, String::new(), false, None);
loop {
let mut h = String::new();
if r.read_line(&mut h)? == 0 || h.trim().is_empty() {
break;
}
let lower = h.to_ascii_lowercase();
if let Some(v) = lower.strip_prefix("content-length:") {
len = v.trim().parse().unwrap_or(0);
} else if let Some(v) = lower.strip_prefix("host:") {
host = v.trim().to_string();
} else if let Some(v) = lower.strip_prefix("origin:") {
origin = Some(v.trim().to_string());
} else if lower.starts_with("x-grove:") {
marker = true;
}
}
// Exact match: a prefix check would accept `localhost.evil.com` (DNS rebinding).
let local = [format!("127.0.0.1:{port}"), format!("localhost:{port}")];
if !local.contains(&host) {
return respond(&mut s, "403 Forbidden", "text/plain", b"bad host");
}
if let Some(o) = &origin
&& !local.iter().any(|h| *o == format!("http://{h}"))
{
return respond(&mut s, "403 Forbidden", "text/plain", b"bad origin");
}
if method == "POST" {
if !marker || len > 1 << 20 {
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
}
r.get_mut().set_limit(1 << 20); // head parsed; allow the (capped) body
let mut body = vec![0u8; len];
r.read_exact(&mut body)?;
let req: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
let out = match path.as_str() {
"/api/ipc" => b.ipc(&req),
"/api/cli" => {
let args: Vec<String> = req["args"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
b.cli(&args, req["stdin"].as_str().unwrap_or(""))
}
_ => return respond(&mut s, "404 Not Found", "text/plain", b"not found"),
};
return respond(
&mut s,
"200 OK",
"application/json",
out.to_string().as_bytes(),
);
}
if path == "/api/config" {
let body = match b.config_json() {
Some(c) => json!({"exists": true, "config": c}),
None => json!({"exists": false}),
};
return respond(
&mut s,
"200 OK",
"application/json",
body.to_string().as_bytes(),
);
}
let name = match path.split('?').next().unwrap_or("/") {
"/" => "index.html",
p => p.trim_start_matches('/'),
};
if name.contains("..") {
return respond(&mut s, "403 Forbidden", "text/plain", b"forbidden");
}
let ctype = match name.rsplit('.').next() {
Some("html") => "text/html; charset=utf-8",
Some("js") => "text/javascript; charset=utf-8",
Some("css") => "text/css; charset=utf-8",
Some("svg") => "image/svg+xml",
_ => "application/octet-stream",
};
match std::fs::read(ui.join(name)) {
Ok(data) => respond(&mut s, "200 OK", ctype, &data),
Err(_) => respond(&mut s, "404 Not Found", "text/plain", b"not found"),
}
}
+31 -10
View File
@@ -1,11 +1,11 @@
//! `config.toml` model, loading and validation (section 6 of the plan).
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Config {
pub machine: Machine,
pub root: Root,
@@ -15,20 +15,21 @@ pub struct Config {
pub groups: Vec<Group>,
#[serde(default)]
pub sync: Sync,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_repo: Option<ConfigRepo>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Machine {
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Root {
pub path: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderKind {
Gitea,
@@ -36,13 +37,14 @@ pub enum ProviderKind {
Github,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Provider {
pub kind: ProviderKind,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Layout {
#[default]
@@ -50,7 +52,7 @@ pub enum Layout {
Plain,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Group {
pub name: String,
pub primary: String,
@@ -62,7 +64,7 @@ pub struct Group {
pub auto_materialize: bool,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Sync {
#[serde(default = "default_debounce")]
pub snapshot_debounce_ms: u64,
@@ -70,6 +72,9 @@ pub struct Sync {
pub fetch_interval_s: u64,
#[serde(default)]
pub ignore_extra: Vec<String>,
/// Changed files larger than this many MiB are not snapshotted (0 = no limit).
#[serde(default = "default_max_file_mb")]
pub max_file_mb: u64,
}
impl Default for Sync {
@@ -78,11 +83,12 @@ impl Default for Sync {
snapshot_debounce_ms: default_debounce(),
fetch_interval_s: default_fetch(),
ignore_extra: Vec::new(),
max_file_mb: default_max_file_mb(),
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct ConfigRepo {
pub provider: String,
pub name: String,
@@ -94,6 +100,9 @@ fn yes() -> bool {
fn default_debounce() -> u64 {
2000
}
fn default_max_file_mb() -> u64 {
50
}
fn default_fetch() -> u64 {
60
}
@@ -124,6 +133,18 @@ impl Config {
Ok(cfg)
}
/// Writes the config atomically (temp file + rename).
pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
let text = toml::to_string_pretty(self).map_err(|e| ConfigError::Parse(e.to_string()))?;
let io = |e| ConfigError::Io(path.to_path_buf(), e);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(io)?;
}
let tmp = path.with_extension("toml.tmp");
std::fs::write(&tmp, text).map_err(io)?;
std::fs::rename(&tmp, path).map_err(io)
}
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))?;
+2
View File
@@ -6,6 +6,8 @@ pub mod inspect;
pub mod layout;
pub mod migrate;
pub mod receive;
pub mod registry;
pub mod resolve;
pub mod snapshot;
pub mod state;
pub mod sync;
+2 -2
View File
@@ -15,13 +15,13 @@ pub const REMOTE_SYNC: &str = "refs/sync-remote";
/// Backup refs live in `refs/sync-backup/<machine>/<stamp>/<kind>`; each kind has its own
/// sub-namespace so refs of different operations in one pass can never collide (D/F conflict).
fn backup_ref(machine: &str, stamp: &str, kind: &str) -> String {
pub(crate) fn backup_ref(machine: &str, stamp: &str, kind: &str) -> String {
format!("refs/sync-backup/{machine}/{stamp}/{kind}")
}
/// Paths the incoming change would add that already exist locally as *ignored* files.
/// `git status` does not report those, but a merge/read-tree would silently overwrite them.
fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, GitError> {
pub(crate) fn ignored_conflicts(g: &Git, target: &str) -> Result<Vec<String>, GitError> {
let added = g.run(&[
"diff",
"--no-renames",
+126
View File
@@ -0,0 +1,126 @@
//! The config repo: a private git repo holding `repos.toml` (what to materialize) and one
//! heartbeat file per machine. A fresh machine needs nothing else to rebuild its workspace.
use crate::git::{Git, GitError};
use crate::layout::dir_name;
use crate::receive::{ensure_fetch_refspec, materialize};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
pub struct Registry {
#[serde(default)]
pub repos: Vec<Entry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Entry {
pub group: String,
pub name: String,
/// Clone URL on the group's primary remote.
pub url: String,
}
impl Registry {
pub fn parse(text: &str) -> Result<Registry, String> {
toml::from_str(text).map_err(|e| e.to_string())
}
pub fn to_text(&self) -> String {
toml::to_string_pretty(self).unwrap_or_default()
}
/// Adds or updates an entry (same group + name).
pub fn upsert(&mut self, e: Entry) {
match self
.repos
.iter_mut()
.find(|x| x.group == e.group && x.name == e.name)
{
Some(x) => *x = e,
None => self.repos.push(e),
}
self.repos
.sort_by(|a, b| (&a.group, &a.name).cmp(&(&b.group, &b.name)));
}
}
/// Creates `<dir>/.bare` as a clone of `url` and a worktree per remote branch.
/// `envs` are extra git environment variables (credentials).
pub fn clone_bare_layout(
url: &str,
dir: &Path,
envs: &[(String, String)],
) -> Result<Vec<PathBuf>, GitError> {
fs::create_dir_all(dir)?;
let bare = dir.join(".bare");
let mut g = Git::new(dir);
for (k, v) in envs {
g = g.with_env(k, v);
}
g.run(&["clone", "-q", "--bare", url, &bare.to_string_lossy()])?;
Git::new(&bare).run(&["config", "core.bare", "true"])?;
ensure_fetch_refspec(&bare, "origin")?;
let mut f = Git::new(&bare);
for (k, v) in envs {
f = f.with_env(k, v);
}
f.run(&["fetch", "-q", "--prune", "origin"])?;
// `clone --bare` creates local branches without upstream config; worktrees made from them
// would then never be classified as ahead/behind.
let b = Git::new(&bare);
let heads = b.run(&["for-each-ref", "--format=%(refname:short)", "refs/heads"])?;
for br in heads.lines() {
let up = format!("origin/{br}");
if b.probe(&["rev-parse", "-q", "--verify", &format!("refs/remotes/{up}")])?
.is_some()
{
b.run(&["branch", "-q", &format!("--set-upstream-to={up}"), br])?;
}
}
materialize(dir, "origin")
}
/// Creates a brand new local repo in the bare layout with an initial empty commit on `main`,
/// pointing at `url`. Nothing is pushed here.
pub fn init_bare_layout(dir: &Path, url: &str) -> Result<PathBuf, GitError> {
fs::create_dir_all(dir)?;
let bare = dir.join(".bare");
let g = Git::new(dir);
g.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
&bare.to_string_lossy(),
])?;
let b = Git::new(&bare);
b.run(&["remote", "add", "origin", url])?;
ensure_fetch_refspec(&bare, "origin")?;
// `hash-object -t tree` on an empty file writes the empty tree object.
let tree = b.run(&["hash-object", "-t", "tree", "-w", "/dev/null"])?;
let commit = b
.with_env("GIT_AUTHOR_NAME", "grove")
.with_env("GIT_AUTHOR_EMAIL", "grove@localhost")
.with_env("GIT_COMMITTER_NAME", "grove")
.with_env("GIT_COMMITTER_EMAIL", "grove@localhost")
.run(&["commit-tree", &tree, "-m", "chore: initial commit"])?;
let b = Git::new(&bare);
b.run(&["update-ref", "refs/heads/main", &commit])?;
let name = dir_name("main", &[]);
let wt = dir.join(&name);
b.run(&["worktree", "add", "-q", &wt.to_string_lossy(), "main"])?;
Ok(wt)
}
/// Pushes `main` of a freshly initialised layout and sets the upstream.
pub fn push_initial(dir: &Path, envs: &[(String, String)]) -> Result<(), GitError> {
let mut g = Git::new(dir.join(".bare"));
for (k, v) in envs {
g = g.with_env(k, v);
}
g.run(&["push", "-q", "-u", "origin", "main"])?;
Ok(())
}
+107
View File
@@ -0,0 +1,107 @@
//! Resolution of a `Diverged` worktree. Always an explicit choice by the user; every action
//! writes a backup ref first so nothing is ever lost.
use crate::git::{Git, GitError};
use crate::inspect::facts;
use crate::layout::dir_name;
use crate::receive::{backup_ref, ignored_conflicts};
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Choice {
/// Discard the local commits and move to the remote tip.
TakeRemote,
/// Overwrite the remote branch with the local one (force-with-lease on the observed tip).
KeepLocal,
/// Keep the local commits on a new branch (own worktree), then move this one to the remote tip.
SaveAsBranch(String),
}
fn fail<T>(msg: impl Into<String>) -> Result<T, GitError> {
Err(GitError::Other(msg.into()))
}
/// Applies `choice` to the diverged worktree. Returns a one-line description of what happened.
pub fn resolve(
worktree: &Path,
machine: &str,
stamp: &str,
choice: &Choice,
) -> Result<String, GitError> {
let g = Git::new(worktree);
let f = facts(worktree)?;
if !(f.ahead && f.behind) {
return fail("worktree is not diverged: nothing to resolve");
}
let branch = g
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD".into()))?;
let upstream = g.run(&["rev-parse", "@{upstream}"])?;
let head = g.run(&["rev-parse", "HEAD"])?;
match choice {
Choice::KeepLocal => {
g.run(&[
"update-ref",
&backup_ref(machine, stamp, &format!("resolve-remote/{branch}")),
&upstream,
])?;
let remote = g.run(&["config", "--get", &format!("branch.{branch}.remote")])?;
g.run(&[
"push",
"-q",
&format!("--force-with-lease={branch}:{upstream}"),
&remote,
&format!("HEAD:refs/heads/{branch}"),
])?;
Ok(format!(
"remote {branch} overwritten with local (old tip kept at backup ref)"
))
}
Choice::TakeRemote | Choice::SaveAsBranch(_) => {
if f.dirty {
return fail("worktree has uncommitted changes: commit or stash them first");
}
let clash = ignored_conflicts(&g, &upstream)?;
if !clash.is_empty() {
return fail(format!(
"would overwrite ignored local files: {}",
clash.join(", ")
));
}
g.run(&[
"update-ref",
&backup_ref(machine, stamp, &format!("resolve-local/{branch}")),
&head,
])?;
let mut msg =
format!("{branch} moved to the remote tip (local tip kept at backup ref)");
if let Choice::SaveAsBranch(name) = choice {
if g.probe(&["rev-parse", "-q", "--verify", &format!("refs/heads/{name}")])?
.is_some()
{
return fail(format!("branch {name:?} already exists"));
}
let root = worktree
.parent()
.ok_or_else(|| GitError::Other("worktree has no parent dir".into()))?;
if !root.join(".bare").is_dir() {
return fail("saving as a branch needs the bare + worktrees layout");
}
let taken: Vec<String> = std::fs::read_dir(root)?
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
let dest = root.join(dir_name(name, &refs));
g.run(&["branch", name, &head])?;
g.run(&["worktree", "add", "-q", &dest.to_string_lossy(), name])?;
msg = format!(
"local commits saved on branch {name} ({}); {msg}",
dest.display()
);
}
g.run(&["reset", "-q", "--hard", &upstream])?;
Ok(msg)
}
}
}
+56 -3
View File
@@ -3,6 +3,7 @@
use crate::git::{Git, GitError};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -10,6 +11,16 @@ pub struct Snapshot {
pub commit: String,
pub tree: String,
pub refname: String,
/// Changed files left out because they exceed the size limit.
pub skipped: Vec<String>,
}
static MAX_FILE_BYTES: AtomicU64 = AtomicU64::new(0);
/// Process-wide limit: changed files larger than this are left out of snapshots (0 = no limit).
/// Set once at startup from `sync.max_file_mb`.
pub fn set_max_file_bytes(n: u64) {
MAX_FILE_BYTES.store(n, Ordering::Relaxed);
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -43,7 +54,7 @@ fn temp_index_path() -> PathBuf {
/// built in a temporary copy of the index so the real index is never modified. The returned
/// guard keeps the temporary index alive; `Git` has it set as `GIT_INDEX_FILE` and the author
/// identity forced.
fn stage(git: &Git) -> Result<(TempIndex, Git, String), GitError> {
fn stage(git: &Git) -> Result<(TempIndex, Git, String, Vec<String>), GitError> {
let gitdir = PathBuf::from(git.run(&["rev-parse", "--absolute-git-dir"])?);
let tmp = TempIndex(temp_index_path());
let real_index = gitdir.join("index");
@@ -58,8 +69,49 @@ fn stage(git: &Git) -> Result<(TempIndex, Git, String), GitError> {
.with_env("GIT_COMMITTER_NAME", "grove")
.with_env("GIT_COMMITTER_EMAIL", "grove@localhost");
snap.run(&["add", "-A"])?;
let skipped = drop_oversized(&snap, git.dir())?;
let tree = snap.run(&["write-tree"])?;
Ok((tmp, snap, tree))
Ok((tmp, snap, tree, skipped))
}
/// Reverts oversized changed files in the temporary index to their HEAD version (or removes them
/// when HEAD has none). Returns their paths.
fn drop_oversized(snap: &Git, worktree: &Path) -> Result<Vec<String>, GitError> {
let limit = MAX_FILE_BYTES.load(Ordering::Relaxed);
if limit == 0 {
return Ok(Vec::new());
}
let has_head = snap
.probe(&["rev-parse", "-q", "--verify", "HEAD"])?
.is_some();
let changed = if has_head {
snap.run(&[
"diff",
"--cached",
"--name-only",
"-z",
"--no-renames",
"HEAD",
])?
} else {
snap.run(&["ls-files", "-z"])?
};
let mut skipped = Vec::new();
for rel in changed.split('\0').filter(|p| !p.is_empty()) {
let big = std::fs::symlink_metadata(worktree.join(rel))
.map(|m| m.is_file() && m.len() > limit)
.unwrap_or(false);
if !big {
continue;
}
if has_head {
snap.run(&["reset", "-q", "HEAD", "--", rel])?;
} else {
snap.run(&["rm", "--cached", "-q", "--ignore-unmatch", "--", rel])?;
}
skipped.push(rel.to_string());
}
Ok(skipped)
}
/// The tree a snapshot of `worktree` would have, without creating any object besides the tree.
@@ -75,7 +127,7 @@ pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result<Outco
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?
.ok_or_else(|| GitError::Other("detached HEAD: cannot snapshot".into()))?;
let refname = ref_name(machine, &branch);
let (_tmp, snap, tree) = stage(&git)?;
let (_tmp, snap, tree, skipped) = stage(&git)?;
let prev = snap.probe(&["rev-parse", "-q", "--verify", &refname])?;
if let Some(p) = &prev {
@@ -101,5 +153,6 @@ pub fn take(worktree: &Path, machine: &str, message_stamp: &str) -> Result<Outco
commit,
tree,
refname,
skipped,
}))
}
+7 -1
View File
@@ -31,6 +31,8 @@ pub struct WorktreeReport {
pub applied: Option<(String, Applied)>,
pub state: State,
pub errors: Vec<String>,
/// Large files left out of the snapshot (see `sync.max_file_mb`).
pub skipped: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq)]
@@ -81,6 +83,7 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
applied: None,
state: State::Synced,
errors: Vec::new(),
skipped: Vec::new(),
};
if let Some(branch) = &wt.branch {
sync_worktree(&mut r, branch, o, rep.fetch_error.is_none());
@@ -109,7 +112,10 @@ fn sync_worktree(r: &mut WorktreeReport, branch: &str, o: &Options, fetched: boo
// 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::Created(s)) => {
r.snapshot = Some("created");
r.skipped = s.skipped;
}
Ok(Outcome::Unchanged(_)) => r.snapshot = Some("unchanged"),
Err(e) => {
r.errors.push(format!("snapshot: {e}"));
+76
View File
@@ -0,0 +1,76 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::registry::*;
use std::fs;
#[test]
fn new_repo_pushes_and_a_fresh_machine_clones_it_into_the_bare_layout() {
let base = tmpdir("reg");
let remote = base.join("r.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let url = remote.to_str().unwrap();
let a = base.join("A/g/proj");
let wt = init_bare_layout(&a, url).unwrap();
assert!(wt.ends_with("main") && wt.join(".git").exists());
push_initial(&a, &[]).unwrap();
let g = Git::new(&wt);
assert_eq!(g.run(&["status", "--porcelain"]).unwrap(), "");
assert_eq!(
g.run(&["rev-parse", "--abbrev-ref", "@{upstream}"])
.unwrap(),
"origin/main"
);
let b = base.join("B/g/proj");
let made = clone_bare_layout(url, &b, &[]).unwrap();
assert_eq!(made.len(), 1);
assert_eq!(
Git::new(b.join("main"))
.run(&["rev-parse", "--abbrev-ref", "@{upstream}"])
.unwrap(),
"origin/main",
"cloned worktrees must track their remote branch"
);
assert!(b.join("main/.git").exists() && b.join(".bare").is_dir());
assert_eq!(
Git::new(b.join("main"))
.run(&["rev-parse", "HEAD"])
.unwrap(),
g.run(&["rev-parse", "HEAD"]).unwrap()
);
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn registry_roundtrip_and_upsert() {
let mut r = Registry::default();
r.upsert(Entry {
group: "z".into(),
name: "b".into(),
url: "u1".into(),
});
r.upsert(Entry {
group: "a".into(),
name: "x".into(),
url: "u2".into(),
});
r.upsert(Entry {
group: "z".into(),
name: "b".into(),
url: "u3".into(),
});
assert_eq!(r.repos.len(), 2);
assert_eq!(r.repos[0].group, "a");
assert_eq!(Registry::parse(&r.to_text()).unwrap(), r);
}
+107
View File
@@ -0,0 +1,107 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::inspect::state;
use grove_core::registry::{clone_bare_layout, init_bare_layout, push_initial};
use grove_core::resolve::{Choice, resolve};
use grove_core::state::State;
use std::fs;
use std::path::PathBuf;
/// Two machines on the bare layout, both committed on main: diverged on B.
fn diverged() -> (PathBuf, PathBuf, PathBuf) {
let base = tmpdir("resolve");
let remote = base.join("r.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let url = remote.to_str().unwrap().to_string();
let a = base.join("A");
init_bare_layout(&a, &url).unwrap();
push_initial(&a, &[]).unwrap();
let b = base.join("B");
clone_bare_layout(&url, &b, &[]).unwrap();
for (root, who) in [(&a, "a"), (&b, "b")] {
let g = Git::new(root.join("main"));
g.run(&["config", "user.email", "t@t"]).unwrap();
g.run(&["config", "user.name", "t"]).unwrap();
let _ = who;
}
// A commits and pushes; B commits locally and fetches.
let ga = Git::new(a.join("main"));
fs::write(a.join("main/f.txt"), "from A\n").unwrap();
ga.run(&["add", "-A"]).unwrap();
ga.run(&["commit", "-qm", "a"]).unwrap();
ga.run(&["push", "-q"]).unwrap();
let gb = Git::new(b.join("main"));
fs::write(b.join("main/g.txt"), "from B\n").unwrap();
gb.run(&["add", "-A"]).unwrap();
gb.run(&["commit", "-qm", "b"]).unwrap();
gb.run(&["fetch", "-q"]).unwrap();
assert_eq!(state(&b.join("main")), State::Diverged);
(base, a, b)
}
#[test]
fn take_remote_discards_local_commits_but_keeps_a_backup_ref() {
let (_base, _a, b) = diverged();
let wt = b.join("main");
let msg = resolve(&wt, "B", "s1", &Choice::TakeRemote).unwrap();
assert!(msg.contains("backup"));
let g = Git::new(&wt);
assert_eq!(state(&wt), State::Synced);
assert!(wt.join("f.txt").exists() && !wt.join("g.txt").exists());
let backup = g
.run(&["rev-parse", "refs/sync-backup/B/s1/resolve-local/main"])
.unwrap();
assert!(g.run(&["show", &format!("{backup}:g.txt")]).is_ok());
}
#[test]
fn save_as_branch_keeps_the_local_work_in_its_own_worktree() {
let (_base, _a, b) = diverged();
let wt = b.join("main");
resolve(&wt, "B", "s1", &Choice::SaveAsBranch("b-work".into())).unwrap();
assert_eq!(state(&wt), State::Synced);
assert!(!wt.join("g.txt").exists());
assert_eq!(
fs::read_to_string(b.join("b-work/g.txt")).unwrap(),
"from B\n"
);
}
#[test]
fn keep_local_force_pushes_with_lease_and_backs_up_the_remote_tip() {
let (_base, a, b) = diverged();
let wt = b.join("main");
resolve(&wt, "B", "s1", &Choice::KeepLocal).unwrap();
assert_eq!(state(&wt), State::Synced);
let ga = Git::new(a.join("main"));
ga.run(&["fetch", "-q"]).unwrap();
let remote_tree = ga.run(&["ls-tree", "--name-only", "origin/main"]).unwrap();
assert!(remote_tree.contains("g.txt") && !remote_tree.contains("f.txt"));
let g = Git::new(&wt);
assert!(
g.run(&["rev-parse", "refs/sync-backup/B/s1/resolve-remote/main"])
.is_ok()
);
}
#[test]
fn refuses_when_not_diverged_or_when_the_worktree_is_dirty() {
let (_base, _a, b) = diverged();
let wt = b.join("main");
fs::write(wt.join("wip.txt"), "x\n").unwrap();
let e = resolve(&wt, "B", "s", &Choice::TakeRemote)
.unwrap_err()
.to_string();
assert!(e.contains("uncommitted"), "{e}");
assert!(wt.join("wip.txt").exists() && wt.join("g.txt").exists());
}
+43
View File
@@ -0,0 +1,43 @@
//! Own test binary: the limit is process-wide.
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::snapshot::{Outcome, set_max_file_bytes, take};
use std::fs;
#[test]
fn oversized_changes_are_left_out_but_small_ones_and_head_content_stay() {
let base = tmpdir("size");
let g = init(&base.join("p"));
commit(&g, "tracked.bin", "old\n");
set_max_file_bytes(1000);
let p = base.join("p");
fs::write(p.join("small.txt"), "ok\n").unwrap();
fs::write(p.join("big.bin"), vec![b'x'; 5000]).unwrap(); // untracked, too big
fs::write(p.join("tracked.bin"), vec![b'y'; 5000]).unwrap(); // tracked, modified, too big
let Outcome::Created(s) = take(&p, "A", "t").unwrap() else {
panic!("expected a snapshot")
};
let mut skipped = s.skipped.clone();
skipped.sort();
assert_eq!(skipped, ["big.bin", "tracked.bin"]);
let show = |f: &str| Git::new(&p).run(&["show", &format!("{}:{f}", s.commit)]);
assert_eq!(show("small.txt").unwrap(), "ok");
assert!(
show("big.bin").is_err(),
"big untracked file must not be in the snapshot"
);
assert_eq!(
show("tracked.bin").unwrap(),
"old",
"tracked file keeps its HEAD content"
);
// The user's real index and files are untouched.
assert_eq!(fs::read(p.join("big.bin")).unwrap().len(), 5000);
assert!(
Git::new(&p)
.run(&["status", "--porcelain"])
.unwrap()
.contains("big.bin")
);
}
+10 -2
View File
@@ -42,6 +42,7 @@ impl Settings {
pub struct WtStatus {
pub branch: Option<String>,
pub state: String,
pub path: String,
}
#[derive(Debug, Clone)]
@@ -379,8 +380,14 @@ fn pass(
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}"));
let mut msg = format!("{branch}: {kind}");
if !w.skipped.is_empty() {
msg.push_str(&format!(
" (left out, over the size limit: {})",
w.skipped.join(", ")
));
}
ctx.activity.log("snapshot", Some(&name), msg);
}
match &w.received {
Some(Received::FastForwarded { .. }) => {
@@ -411,6 +418,7 @@ fn pass(
now_wts.push(WtStatus {
branch: w.branch.clone(),
state,
path: w.path.display().to_string(),
});
}
status.worktrees = now_wts;
+1 -1
View File
@@ -161,7 +161,7 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
"last_error": r.last_error,
"failures": r.failures,
"worktrees": r.worktrees.iter()
.map(|w| json!({"branch": w.branch, "state": w.state}))
.map(|w| json!({"branch": w.branch, "state": w.state, "path": w.path}))
.collect::<Vec<_>>(),
})
})
+1
View File
@@ -22,6 +22,7 @@ fn main() -> Result<()> {
.or_else(Config::default_path)
.context("cannot determine config path")?;
let cfg = Config::load(&path)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
let st = Settings::standard();
eprintln!(
"groved: machine {:?}, root {}, socket {}",
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "grove-providers"
description = "Forge providers (Gitea/Forgejo, GitHub) and token storage for grove"
edition.workspace = true
version.workspace = true
license.workspace = true
[dependencies]
grove-core = { version = "0.1.0", path = "../grove-core" }
keyring = "4.2.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
ureq = { version = "3", features = ["json"] }
+97
View File
@@ -0,0 +1,97 @@
use crate::http::Http;
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
/// Gitea and Forgejo share the same `/api/v1`.
pub struct Gitea {
kind: ProviderKind,
http: Http,
}
impl Gitea {
pub fn new(kind: ProviderKind, url: &str, token: String) -> Self {
Gitea {
kind,
http: Http::new(
&format!("{}/api/v1", url.trim_end_matches('/')),
format!("token {token}"),
),
}
}
}
fn repo(v: &Value) -> RemoteRepo {
let s = |k: &str| v[k].as_str().unwrap_or_default().to_string();
RemoteRepo {
owner: v["owner"]["login"].as_str().unwrap_or_default().to_string(),
name: s("name"),
private: v["private"].as_bool().unwrap_or(false),
clone_url: s("clone_url"),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
impl Provider for Gitea {
fn kind(&self) -> ProviderKind {
self.kind
}
fn capabilities(&self) -> Capabilities {
Capabilities {
push_mirror: true,
orgs: true,
}
}
fn test_connection(&self) -> Result<String> {
let u = self.http.ok("GET", "/user", None)?;
u["login"]
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Other("response has no login".into()))
}
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
let mut out = Vec::new();
for page in 1..=200 {
let v = self
.http
.ok("GET", &format!("/user/repos?limit=50&page={page}"), None)?;
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items.iter().map(repo));
if n < 50 {
break;
}
}
Ok(out)
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
let path = match &new.owner {
Some(o) => format!("/orgs/{o}/repos"),
None => "/user/repos".to_string(),
};
let body = json!({"name": new.name, "private": new.private,
"description": new.description, "default_branch": "main"});
Ok(repo(&self.http.ok("POST", &path, Some(&body))?))
}
fn configure_mirror(&self, owner: &str, name: &str, spec: &MirrorSpec) -> Result<()> {
let body = json!({
"remote_address": spec.remote_url,
"remote_username": spec.remote_username,
"remote_password": spec.remote_token,
"interval": spec.interval,
"sync_on_commit": spec.sync_on_commit,
});
self.http
.ok(
"POST",
&format!("/repos/{owner}/{name}/push_mirrors"),
Some(&body),
)
.map(|_| ())
}
}
+87
View File
@@ -0,0 +1,87 @@
use crate::http::Http;
use crate::{Capabilities, Error, MirrorSpec, NewRepo, Provider, RemoteRepo, Result};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
pub struct GitHub {
http: Http,
}
impl GitHub {
/// `url` empty means github.com; set it for GitHub Enterprise (`https://host/api/v3`) or tests.
pub fn new(url: &str, token: String) -> Self {
let base = if url.is_empty() || url == "https://github.com" {
"https://api.github.com"
} else {
url
};
GitHub {
http: Http::new(base, format!("Bearer {token}")),
}
}
}
fn repo(v: &Value) -> RemoteRepo {
RemoteRepo {
owner: v["owner"]["login"].as_str().unwrap_or_default().to_string(),
name: v["name"].as_str().unwrap_or_default().to_string(),
private: v["private"].as_bool().unwrap_or(false),
clone_url: v["clone_url"].as_str().unwrap_or_default().to_string(),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
impl Provider for GitHub {
fn kind(&self) -> ProviderKind {
ProviderKind::Github
}
fn capabilities(&self) -> Capabilities {
Capabilities {
push_mirror: false,
orgs: true,
}
}
fn test_connection(&self) -> Result<String> {
let u = self.http.ok("GET", "/user", None)?;
u["login"]
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Other("response has no login".into()))
}
fn list_repos(&self) -> Result<Vec<RemoteRepo>> {
let mut out = Vec::new();
for page in 1..=200 {
let v = self.http.ok(
"GET",
&format!("/user/repos?per_page=100&page={page}"),
None,
)?;
let items = v.as_array().cloned().unwrap_or_default();
let n = items.len();
out.extend(items.iter().map(repo));
if n < 100 {
break;
}
}
Ok(out)
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
let path = match &new.owner {
Some(o) => format!("/orgs/{o}/repos"),
None => "/user/repos".to_string(),
};
let body =
json!({"name": new.name, "private": new.private, "description": new.description});
Ok(repo(&self.http.ok("POST", &path, Some(&body))?))
}
fn configure_mirror(&self, _: &str, _: &str, _: &MirrorSpec) -> Result<()> {
Err(Error::Unsupported(
"GitHub has no push mirrors; use a Gitea pull mirror or the daemon's branch push",
))
}
}
+63
View File
@@ -0,0 +1,63 @@
use crate::{Error, Result};
use serde_json::Value;
use std::time::Duration;
pub struct Http {
base: String,
auth: String,
agent: ureq::Agent,
}
impl Http {
pub fn new(base: &str, auth: String) -> Self {
let agent: ureq::Agent = ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(Duration::from_secs(30)))
.build()
.into();
Http {
base: base.trim_end_matches('/').to_string(),
auth,
agent,
}
}
/// Returns the status and the parsed JSON body (`Null` when empty or not JSON).
pub fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<(u16, Value)> {
let url = format!("{}{}", self.base, path);
let net = |e: ureq::Error| Error::Network(e.to_string());
let mut resp = match (method, body) {
("GET", _) => self
.agent
.get(&url)
.header("Authorization", &self.auth)
.header("Accept", "application/json")
.call(),
("POST", Some(b)) => self
.agent
.post(&url)
.header("Authorization", &self.auth)
.header("Accept", "application/json")
.send_json(b),
_ => return Err(Error::Other(format!("unsupported request {method}"))),
}
.map_err(net)?;
let status = resp.status().as_u16();
let text = resp.body_mut().read_to_string().map_err(net)?;
let json = serde_json::from_str(&text).unwrap_or(Value::Null);
Ok((status, json))
}
/// Like [`send`], but maps non-2xx statuses to [`Error::Api`].
pub fn ok(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value> {
let (status, json) = self.send(method, path, body)?;
if (200..300).contains(&status) {
return Ok(json);
}
let message = json["message"]
.as_str()
.unwrap_or("(no message)")
.to_string();
Err(Error::Api { status, message })
}
}
+108
View File
@@ -0,0 +1,108 @@
//! Forge providers (Gitea/Forgejo, GitHub) and token storage.
//!
//! Providers only talk to the forge's REST API. Nothing here ever deletes a remote repository.
mod gitea;
mod github;
mod http;
pub mod token;
pub use gitea::Gitea;
pub use github::GitHub;
use grove_core::config::{Provider as ProviderCfg, ProviderKind};
use std::fmt;
#[derive(Debug)]
pub enum Error {
/// Transport problem (DNS, TLS, timeout...).
Network(String),
/// The forge answered with an error status.
Api {
status: u16,
message: String,
},
/// The forge cannot do what was asked (see [`Capabilities`]).
Unsupported(&'static str),
/// No token stored for the provider.
NoToken(String),
Other(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Network(m) => write!(f, "network error: {m}"),
Error::Api { status, message } => write!(f, "forge returned {status}: {message}"),
Error::Unsupported(m) => write!(f, "not supported by this forge: {m}"),
Error::NoToken(id) => write!(
f,
"no token for provider {id:?} (run `grove login {id}` or set GROVE_TOKEN_*)"
),
Error::Other(m) => f.write_str(m),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteRepo {
pub owner: String,
pub name: String,
pub private: bool,
pub clone_url: String,
pub default_branch: String,
}
#[derive(Debug, Clone)]
pub struct NewRepo {
pub name: String,
/// Create under this organisation instead of the authenticated user.
pub owner: Option<String>,
pub private: bool,
pub description: String,
}
/// Push mirror from the primary forge to a secondary one.
#[derive(Debug, Clone)]
pub struct MirrorSpec {
pub remote_url: String,
pub remote_username: String,
pub remote_token: String,
/// Go-style duration (`8h0m0s`); `0` disables the periodic sync.
pub interval: String,
pub sync_on_commit: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities {
/// The forge can push-mirror a repo to another forge by itself.
pub push_mirror: bool,
pub orgs: bool,
}
pub trait Provider {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
/// Verifies the token and returns the authenticated login.
fn test_connection(&self) -> Result<String>;
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
}
/// Builds the provider described by `cfg`, using `token`.
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
match cfg.kind {
ProviderKind::Gitea | ProviderKind::Forgejo => Box::new(Gitea::new(
cfg.kind,
cfg.url.as_deref().unwrap_or_default(),
token,
)),
ProviderKind::Github => {
Box::new(GitHub::new(cfg.url.as_deref().unwrap_or_default(), token))
}
}
}
+47
View File
@@ -0,0 +1,47 @@
//! Token storage: `GROVE_TOKEN_<ID>` env var first (headless machines, tests), then the
//! desktop Secret Service. Tokens are never written to the config file.
use crate::{Error, Result};
const SERVICE: &str = "grove";
pub fn env_name(provider_id: &str) -> String {
let id: String = provider_id
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_uppercase()
} else {
'_'
}
})
.collect();
format!("GROVE_TOKEN_{id}")
}
pub fn get(provider_id: &str) -> Result<String> {
if let Ok(t) = std::env::var(env_name(provider_id))
&& !t.trim().is_empty()
{
return Ok(t.trim().to_string());
}
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
match e.get_password() {
Ok(t) => Ok(t),
Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())),
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
}
}
pub fn set(provider_id: &str, token: &str) -> Result<()> {
keyring::Entry::new(SERVICE, provider_id)
.and_then(|e| e.set_password(token))
.map_err(|e| Error::Other(format!("secret service: {e}")))
}
pub fn delete(provider_id: &str) -> Result<()> {
match keyring::Entry::new(SERVICE, provider_id).and_then(|e| e.delete_credential()) {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
}
}
+185
View File
@@ -0,0 +1,185 @@
use grove_core::config::ProviderKind;
use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, token};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::mpsc;
use std::thread;
/// Serves the scripted `(status, body)` replies in order, one connection each, and reports
/// every raw request it received.
fn mock(replies: Vec<(u16, &'static str)>) -> (String, mpsc::Receiver<String>) {
let l = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}", l.local_addr().unwrap());
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
for (status, body) in replies {
let (mut s, _) = l.accept().unwrap();
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let n = s.read(&mut chunk).unwrap();
buf.extend_from_slice(&chunk[..n]);
let text = String::from_utf8_lossy(&buf).to_string();
if let Some(h) = text.find("\r\n\r\n") {
let len = text[..h]
.lines()
.find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("content-length:")
.map(|v| v.trim().parse::<usize>().unwrap())
})
.unwrap_or(0);
if buf.len() >= h + 4 + len {
break;
}
}
if n == 0 {
break;
}
}
tx.send(String::from_utf8_lossy(&buf).to_string()).unwrap();
let resp = format!(
"HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(resp.as_bytes()).unwrap();
}
});
(url, rx)
}
fn body(req: &str) -> serde_json::Value {
serde_json::from_str(req.split("\r\n\r\n").nth(1).unwrap()).unwrap()
}
#[test]
fn gitea_connection_list_create_and_mirror() {
let (url, rx) = mock(vec![
(200, r#"{"login":"dasemu"}"#),
(
200,
r#"[{"name":"a","private":true,"clone_url":"u/a.git","default_branch":"main","owner":{"login":"dasemu"}}]"#,
),
(
201,
r#"{"name":"n","private":true,"clone_url":"u/n.git","default_branch":"main","owner":{"login":"dasemu"}}"#,
),
(200, "{}"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "secret".into());
assert_eq!(g.test_connection().unwrap(), "dasemu");
let first = rx.recv().unwrap();
assert!(first.starts_with("GET /api/v1/user "), "{first}");
assert!(first.to_lowercase().contains("authorization: token secret"));
let repos = g.list_repos().unwrap();
assert_eq!(
(repos.len(), repos[0].name.as_str(), repos[0].private),
(1, "a", true)
);
let r = g
.create_repo(&NewRepo {
name: "n".into(),
owner: None,
private: true,
description: "d".into(),
})
.unwrap();
assert_eq!(r.clone_url, "u/n.git");
rx.recv().unwrap();
let create = rx.recv().unwrap();
assert!(create.starts_with("POST /api/v1/user/repos "), "{create}");
assert_eq!(body(&create)["private"], true);
g.configure_mirror(
"dasemu",
"n",
&MirrorSpec {
remote_url: "https://github.com/x/n.git".into(),
remote_username: "x".into(),
remote_token: "t".into(),
interval: "8h0m0s".into(),
sync_on_commit: true,
},
)
.unwrap();
let m = rx.recv().unwrap();
assert!(
m.starts_with("POST /api/v1/repos/dasemu/n/push_mirrors "),
"{m}"
);
assert_eq!(body(&m)["sync_on_commit"], true);
}
#[test]
fn gitea_org_create_uses_org_endpoint_and_api_errors_carry_status() {
let (url, rx) = mock(vec![
(409, r#"{"message":"repository already exists"}"#),
(401, r#"{"message":"bad token"}"#),
]);
let g = Gitea::new(ProviderKind::Forgejo, &url, "t".into());
let e = g
.create_repo(&NewRepo {
name: "n".into(),
owner: Some("org".into()),
private: false,
description: String::new(),
})
.unwrap_err();
assert!(matches!(e, Error::Api { status: 409, .. }), "{e}");
assert!(
rx.recv()
.unwrap()
.starts_with("POST /api/v1/orgs/org/repos ")
);
assert!(matches!(
g.test_connection().unwrap_err(),
Error::Api { status: 401, .. }
));
}
#[test]
fn github_uses_bearer_and_has_no_push_mirror() {
let (url, rx) = mock(vec![(200, r#"{"login":"me"}"#)]);
let g = GitHub::new(&url, "tok".into());
assert_eq!(g.test_connection().unwrap(), "me");
assert!(
rx.recv()
.unwrap()
.to_lowercase()
.contains("authorization: bearer tok")
);
assert!(!g.capabilities().push_mirror);
let e = g
.configure_mirror(
"o",
"r",
&MirrorSpec {
remote_url: String::new(),
remote_username: String::new(),
remote_token: String::new(),
interval: String::new(),
sync_on_commit: false,
},
)
.unwrap_err();
assert!(matches!(e, Error::Unsupported(_)));
}
#[test]
fn unreachable_forge_is_a_network_error() {
let g = Gitea::new(ProviderKind::Gitea, "http://127.0.0.1:1", "t".into());
assert!(matches!(
g.test_connection().unwrap_err(),
Error::Network(_)
));
}
#[test]
fn env_var_overrides_the_keyring() {
assert_eq!(token::env_name("gitea-main"), "GROVE_TOKEN_GITEA_MAIN");
// SAFETY: tests in this binary that touch this variable run in this single test.
unsafe { std::env::set_var("GROVE_TOKEN_ENV_TEST", " abc ") };
assert_eq!(token::get("env-test").unwrap(), "abc");
}
+15
View File
@@ -5,8 +5,23 @@ edition.workspace = true
version.workspace = true
[dependencies]
age = "0.12.1"
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" }
grove-providers = { version = "0.1.0", path = "../grove-providers" }
serde_json = "1.0.154"
toml = "1.2.1"
# `cargo build --release --workspace && cargo deb -p grove --no-build` packages CLI + daemon + user unit.
[package.metadata.deb]
name = "grove"
section = "devel"
depends = "$auto, git"
extended-description = "Keeps chosen git repos continuously in sync across machines, including uncommitted work."
assets = [
["../../target/release/grove", "usr/bin/", "755"],
["../../target/release/groved", "usr/bin/", "755"],
["../../contrib/groved.deb.service", "usr/lib/systemd/user/groved.service", "644"],
]
+225 -10
View File
@@ -1,15 +1,20 @@
use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use grove_core::config::Config;
use grove_core::config::{Config, ProviderKind};
use grove_core::git::Git;
use grove_core::inspect::{state, worktrees};
use grove_core::migrate::migrate;
use grove_core::receive::{Applied, Archived, Received};
use grove_core::resolve::{Choice, resolve};
use grove_core::snapshot::{Outcome, take};
use grove_core::state::State;
use grove_core::sync::{Options, SyncReport, git_dir_for, sync_repo};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
mod secrets;
mod workflow;
#[derive(Parser)]
#[command(name = "grove", about = "Keep git workspaces in sync across machines")]
struct Cli {
@@ -26,6 +31,26 @@ enum Cmd {
Status {
#[arg(default_value = ".")]
path: PathBuf,
/// Also say what the next sync pass would do (no network, nothing changed)
#[arg(long)]
plan: bool,
},
/// Resolve a diverged worktree (an explicit choice; backups are always written)
Resolve {
/// The worktree directory
path: PathBuf,
/// Discard local commits, move to the remote tip
#[arg(long, group = "how")]
take_remote: bool,
/// Overwrite the remote branch with the local one
#[arg(long, group = "how")]
keep_local: bool,
/// Keep local commits on a new branch (own worktree), then take the remote tip
#[arg(long, value_name = "BRANCH", group = "how")]
save_as: Option<String>,
/// Open both sides in your difftool and change nothing
#[arg(long, group = "how")]
compare: bool,
},
/// Take a snapshot of the worktree at PATH into refs/sync/<machine>/<branch>
Snapshot {
@@ -49,6 +74,47 @@ enum Cmd {
},
/// Check the local setup
Doctor,
/// Write a first config file for this machine
Init {
#[arg(long)]
machine: Option<String>,
#[arg(long, default_value = "~/Workspace")]
root: String,
/// Provider id (name used in the config and for the token)
#[arg(long, default_value = "main")]
provider: String,
#[arg(long, default_value = "gitea")]
kind: String,
#[arg(long)]
url: Option<String>,
#[arg(long, default_value = "default")]
group: String,
/// Name of the private config repo to keep the repo registry in
#[arg(long)]
config_repo: Option<String>,
#[arg(long)]
force: bool,
},
/// Store the API token for a provider (read from stdin, never from argv)
Login { provider: String },
/// Create a repo on the group's primary forge and set it up locally
New {
group: String,
name: String,
#[arg(long)]
public: bool,
},
/// List (or, with names, clone) remote repos that are not on this machine
Import { group: String, names: Vec<String> },
/// Create the config repo and register every repo already on disk
ConfigRepoInit,
/// Fresh machine: clone every repo listed in the config repo
Bootstrap,
/// Encrypted sync of files git must not hold (.env, ...), via the config repo
Secrets {
#[command(subcommand)]
action: SecretsCmd,
},
/// Talk to the running daemon (`groved`)
Daemon {
#[command(subcommand)]
@@ -56,6 +122,18 @@ enum Cmd {
},
}
#[derive(Subcommand)]
enum SecretsCmd {
/// Create this machine's age key and publish the public half
Init,
/// Encrypt FILE (inside a workspace worktree) to every machine key and store it
Push { file: PathBuf },
/// Decrypt stored files into the worktrees that lack them (never overwrites)
Pull,
/// Re-encrypt everything to the current set of machine keys
Rekey,
}
#[derive(Subcommand)]
enum DaemonCmd {
/// Show every managed repo and its state
@@ -169,11 +247,47 @@ fn main() -> Result<()> {
let cli = Cli::parse();
match &cli.cmd {
Cmd::Daemon { action } => daemon(action),
Cmd::Status { path } => status(path),
Cmd::Status { path, plan } => status(path, *plan),
Cmd::Resolve {
path,
take_remote,
keep_local,
save_as,
compare,
} => {
let cfg = load_config(&cli.config)?;
let choice = match (take_remote, keep_local, save_as, compare) {
(true, ..) => Choice::TakeRemote,
(_, true, ..) => Choice::KeepLocal,
(_, _, Some(b), _) => Choice::SaveAsBranch(b.clone()),
(.., true) => {
let ok = std::process::Command::new("git")
.current_dir(path)
.args(["difftool", "-d", "HEAD", "@{upstream}"])
.status()?
.success();
if !ok {
bail!("git difftool failed (is a difftool configured?)");
}
return Ok(());
}
_ => bail!(
"choose one of --take-remote, --keep-local, --save-as <branch>, --compare"
),
};
println!("{}", resolve(path, &cfg.machine.name, &stamp(), &choice)?);
Ok(())
}
Cmd::Snapshot { path } => {
let cfg = load_config(&cli.config)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
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);
for f in &s.skipped {
println!("left out (over the size limit): {f}");
}
}
Outcome::Unchanged(c) => println!("unchanged {c}"),
}
Ok(())
@@ -196,6 +310,7 @@ fn main() -> Result<()> {
}
Cmd::Sync { path, offline } => {
let cfg = load_config(&cli.config)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
let rep = sync_repo(
path,
&Options {
@@ -209,18 +324,115 @@ fn main() -> Result<()> {
print_report(&rep)
}
Cmd::Doctor => doctor(&cli.config),
Cmd::Init {
machine,
root,
provider,
kind,
url,
group,
config_repo,
force,
} => {
let path = cli
.config
.clone()
.or_else(Config::default_path)
.context("cannot determine config path (set --config)")?;
let kind = match kind.as_str() {
"gitea" => ProviderKind::Gitea,
"forgejo" => ProviderKind::Forgejo,
"github" => ProviderKind::Github,
k => bail!("unknown provider kind {k:?} (gitea, forgejo, github)"),
};
let machine = machine
.clone()
.or_else(|| {
std::fs::read_to_string("/etc/hostname")
.ok()
.map(|h| h.trim().to_string())
})
.context("cannot determine the machine name (set --machine)")?;
workflow::init(
&path,
workflow::InitArgs {
machine,
root: root.clone(),
provider: provider.clone(),
kind,
url: url.clone(),
group: group.clone(),
config_repo: config_repo.clone(),
},
*force,
)?;
println!("wrote {}", path.display());
println!("next: `grove login {provider}` to store the API token");
Ok(())
}
Cmd::Login { provider } => {
let cfg = load_config(&cli.config)?;
let mut tok = String::new();
std::io::stdin().read_line(&mut tok)?;
let who = workflow::login(&cfg, provider, tok.trim())?;
println!("logged in to {provider} as {who}; token stored in the Secret Service");
Ok(())
}
Cmd::New {
group,
name,
public,
} => {
let wt = workflow::new_repo(&load_config(&cli.config)?, group, name, !public)?;
println!("ready: {}", wt.display());
Ok(())
}
Cmd::Import { group, names } => workflow::import(&load_config(&cli.config)?, group, names),
Cmd::ConfigRepoInit => {
let n = workflow::config_repo_init(&load_config(&cli.config)?)?;
println!("config repo up to date ({n} repos registered)");
Ok(())
}
Cmd::Secrets { action } => {
let cfg = load_config(&cli.config)?;
match action {
SecretsCmd::Init => secrets::init(&cfg),
SecretsCmd::Push { file } => secrets::push(&cfg, file),
SecretsCmd::Pull => secrets::pull(&cfg),
SecretsCmd::Rekey => secrets::rekey(&cfg),
}
}
Cmd::Bootstrap => {
let (done, skipped) = workflow::bootstrap(&load_config(&cli.config)?)?;
println!("bootstrap finished: {done} cloned, {skipped} already present");
Ok(())
}
}
}
fn status(path: &Path) -> Result<()> {
fn plan_for(s: &State) -> &'static str {
match s {
State::Synced => "nothing to do",
State::Dirty => "snapshot the working changes and push the snapshot ref",
State::Ahead => "nothing automatic: push your commits yourself",
State::Behind => "fast-forward to the remote tip",
State::BehindDirty => {
"keep your edits; adopt the remote tip only if the content is identical"
}
State::Diverged => "nothing automatic: run `grove resolve` to choose",
State::Error(_) => "retry; see the error",
}
}
fn status(path: &Path, plan: bool) -> 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()
);
let st = state(&wt.path);
print!("{:<24} {:?} {}", branch, st, wt.path.display());
if plan {
print!("\n next: {}", plan_for(&st));
}
println!();
}
Ok(())
}
@@ -250,6 +462,9 @@ fn print_report(rep: &SyncReport) -> Result<()> {
if let Some(s) = w.snapshot {
notes.push(format!("snapshot {s}"));
}
if !w.skipped.is_empty() {
notes.push(format!("left out (too large): {}", w.skipped.join(", ")));
}
match &w.received {
Some(Received::FastForwarded { .. }) => notes.push("fast-forwarded".into()),
Some(Received::Declined(why)) => notes.push(format!("not fast-forwarded: {why}")),
+239
View File
@@ -0,0 +1,239 @@
//! Encrypted channel for files git must never hold in clear (`.env` and similar).
//!
//! Each machine has an age identity in its state dir; the public keys live in the config repo
//! (`machines/<name>.age.pub`). A pushed file is encrypted to every machine's key and stored as
//! `secrets/<group>/<repo>/<file>.age` in the config repo. Decrypted copies are only ever written
//! to worktrees, mode 0600, and never overwrite a file whose content differs.
use crate::workflow::{commit_and_push, config_repo_open};
use age::secrecy::ExposeSecret;
use age::x25519::{Identity, Recipient};
use anyhow::{Context, Result, bail};
use grove_core::config::Config;
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
fn identity_path() -> Result<PathBuf> {
Ok(Config::state_dir()
.context("cannot determine state dir")?
.join("age-identity.txt"))
}
fn load_identity() -> Result<Identity> {
let p = identity_path()?;
let text = fs::read_to_string(&p)
.with_context(|| format!("no identity at {} (run `grove secrets init`)", p.display()))?;
text.trim()
.parse::<Identity>()
.map_err(|e| anyhow::anyhow!("bad identity file: {e}"))
}
pub fn encrypt(recipients: &[Recipient], data: &[u8]) -> Result<Vec<u8>> {
if recipients.is_empty() {
bail!("no recipients: run `grove secrets init` on each machine first");
}
let enc = age::Encryptor::with_recipients(recipients.iter().map(|r| r as &dyn age::Recipient))
.map_err(|e| anyhow::anyhow!("{e}"))?;
let mut out = Vec::new();
let mut w = enc.wrap_output(&mut out)?;
w.write_all(data)?;
w.finish()?;
Ok(out)
}
pub fn decrypt(id: &Identity, blob: &[u8]) -> Result<Vec<u8>> {
age::decrypt(id, blob)
.map_err(|e| anyhow::anyhow!("cannot decrypt (not encrypted to this machine?): {e}"))
}
fn recipients(dir: &Path) -> Result<Vec<Recipient>> {
let mut out = Vec::new();
let Ok(rd) = fs::read_dir(dir.join("machines")) else {
return Ok(out);
};
for e in rd.filter_map(Result::ok) {
if e.file_name().to_string_lossy().ends_with(".age.pub") {
let t = fs::read_to_string(e.path())?;
out.push(
t.trim()
.parse::<Recipient>()
.map_err(|e| anyhow::anyhow!("bad key: {e}"))?,
);
}
}
Ok(out)
}
pub fn init(cfg: &Config) -> Result<()> {
let p = identity_path()?;
if !p.exists() {
fs::create_dir_all(p.parent().unwrap())?;
let id = Identity::generate();
fs::write(&p, format!("{}\n", id.to_string().expose_secret()))?;
fs::set_permissions(&p, fs::Permissions::from_mode(0o600))?;
println!("generated identity {}", p.display());
}
let id = load_identity()?;
let (dir, forge) = config_repo_open(cfg, true)?;
fs::create_dir_all(dir.join("machines"))?;
fs::write(
dir.join("machines")
.join(format!("{}.age.pub", cfg.machine.name)),
format!("{}\n", id.to_public()),
)?;
commit_and_push(cfg, &dir, &forge, "publish age key")?;
println!("public key published for machine {}", cfg.machine.name);
println!(
"note: files pushed earlier are not readable here until another machine runs `grove secrets rekey`"
);
Ok(())
}
/// `<root>/<group>/<repo>/<worktree>/<rel...>` -> (group, repo, worktree dir name, rel path).
fn locate(cfg: &Config, file: &Path) -> Result<(String, String, PathBuf, String)> {
let file = fs::canonicalize(file).with_context(|| format!("{} not found", file.display()))?;
let root = fs::canonicalize(cfg.root_path())?;
let rel = file
.strip_prefix(&root)
.context("file is not under the workspace root")?;
let parts: Vec<_> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
if parts.len() < 4 {
bail!("expected <root>/<group>/<repo>/<worktree>/<file>");
}
Ok((
parts[0].clone(),
parts[1].clone(),
root.join(&parts[0]).join(&parts[1]),
parts[3..].join("/"),
))
}
fn blob_path(dir: &Path, group: &str, repo: &str, rel: &str) -> PathBuf {
dir.join("secrets")
.join(group)
.join(repo)
.join(format!("{}.age", rel.replace('/', "%2F")))
}
pub fn push(cfg: &Config, file: &Path) -> Result<()> {
let (group, repo, _, rel) = locate(cfg, file)?;
let (dir, forge) = config_repo_open(cfg, false)?;
let blob = encrypt(&recipients(&dir)?, &fs::read(file)?)?;
let dest = blob_path(&dir, &group, &repo, &rel);
fs::create_dir_all(dest.parent().unwrap())?;
fs::write(&dest, blob)?;
commit_and_push(cfg, &dir, &forge, &format!("secret {group}/{repo}/{rel}"))?;
println!("encrypted and stored {group}/{repo}/{rel}");
Ok(())
}
pub fn pull(cfg: &Config) -> Result<()> {
let id = load_identity()?;
let (dir, _) = config_repo_open(cfg, false)?;
let sroot = dir.join("secrets");
let (mut wrote, mut same, mut conflict) = (0, 0, 0);
for g in fs::read_dir(&sroot)
.into_iter()
.flatten()
.filter_map(Result::ok)
{
for r in fs::read_dir(g.path())?.filter_map(Result::ok) {
let repo_dir = cfg.root_path().join(g.file_name()).join(r.file_name());
for b in fs::read_dir(r.path())?.filter_map(Result::ok) {
let name = b.file_name().to_string_lossy().into_owned();
let Some(rel) = name.strip_suffix(".age").map(|n| n.replace("%2F", "/")) else {
continue;
};
let plain = match decrypt(&id, &fs::read(b.path())?) {
Ok(p) => p,
Err(e) => {
println!("skip {}/{}: {e}", g.file_name().to_string_lossy(), rel);
continue;
}
};
for wt in fs::read_dir(&repo_dir)
.into_iter()
.flatten()
.filter_map(Result::ok)
{
if !wt.path().join(".git").exists() {
continue;
}
let target = wt.path().join(&rel);
match fs::read(&target) {
Ok(cur) if cur == plain => same += 1,
Ok(_) => {
conflict += 1;
println!(
"kept local {} (differs from the stored copy)",
target.display()
);
}
Err(_) => {
fs::create_dir_all(target.parent().unwrap())?;
fs::write(&target, &plain)?;
fs::set_permissions(&target, fs::Permissions::from_mode(0o600))?;
wrote += 1;
println!("wrote {}", target.display());
}
}
}
}
}
}
println!("{wrote} written, {same} already identical, {conflict} kept (differ)");
Ok(())
}
/// Re-encrypts every stored secret to the current set of machine keys.
pub fn rekey(cfg: &Config) -> Result<()> {
let id = load_identity()?;
let (dir, forge) = config_repo_open(cfg, false)?;
let rec = recipients(&dir)?;
let mut n = 0;
let mut stack = vec![dir.join("secrets")];
while let Some(d) = stack.pop() {
for e in fs::read_dir(&d)
.into_iter()
.flatten()
.filter_map(Result::ok)
{
let p = e.path();
if p.is_dir() {
stack.push(p);
} else if p.extension().is_some_and(|x| x == "age") {
let plain = decrypt(&id, &fs::read(&p)?)?;
fs::write(&p, encrypt(&rec, &plain)?)?;
n += 1;
}
}
}
commit_and_push(cfg, &dir, &forge, "rekey secrets")?;
println!("re-encrypted {n} file(s) to {} machine key(s)", rec.len());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_recipient_can_decrypt_and_strangers_cannot() {
let (a, b, c) = (
Identity::generate(),
Identity::generate(),
Identity::generate(),
);
let blob = encrypt(&[a.to_public(), b.to_public()], b"TOKEN=1\n").unwrap();
assert!(!String::from_utf8_lossy(&blob).contains("TOKEN"));
assert_eq!(decrypt(&a, &blob).unwrap(), b"TOKEN=1\n");
assert_eq!(decrypt(&b, &blob).unwrap(), b"TOKEN=1\n");
assert!(decrypt(&c, &blob).is_err());
assert!(encrypt(&[], b"x").is_err());
}
}
+389
View File
@@ -0,0 +1,389 @@
//! Onboarding, new-repo, import and bootstrap flows (Phase 4).
use anyhow::{Context, Result, bail};
use grove_core::config::{
Config, Group, Layout, Machine, Provider as ProviderCfg, ProviderKind, Root,
};
use grove_core::git::Git;
use grove_core::registry::{Entry, Registry, clone_bare_layout, init_bare_layout, push_initial};
use grove_providers::{MirrorSpec, NewRepo, Provider, build, token};
use std::fs;
use std::path::{Path, PathBuf};
pub struct Forge {
pub api: Box<dyn Provider>,
pub login: String,
/// Git environment that authenticates HTTPS operations with the stored token.
pub git_env: Vec<(String, String)>,
}
pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
let pc = cfg
.providers
.get(id)
.with_context(|| format!("provider {id:?} is not in the config"))?;
let tok = token::get(id)?;
let api = build(pc, tok.clone());
let login = api.test_connection()?;
let git_env = match pc.kind {
ProviderKind::Gitea | ProviderKind::Forgejo => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!("Authorization: token {tok}"),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
// GitHub git-over-HTTPS needs Basic auth; leave it to the user's credential helper.
ProviderKind::Github => vec![("GIT_TERMINAL_PROMPT".into(), "0".into())],
};
Ok(Forge {
api,
login,
git_env,
})
}
fn group<'a>(cfg: &'a Config, name: &str) -> Result<&'a Group> {
cfg.groups
.iter()
.find(|g| g.name == name)
.with_context(|| format!("group {name:?} is not in the config"))
}
fn with_env(g: Git, envs: &[(String, String)]) -> Git {
envs.iter().fold(g, |g, (k, v)| g.with_env(k, v))
}
pub struct InitArgs {
pub machine: String,
pub root: String,
pub provider: String,
pub kind: ProviderKind,
pub url: Option<String>,
pub group: String,
pub config_repo: Option<String>,
}
pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
if path.exists() && !force {
bail!(
"{} already exists (use --force to overwrite)",
path.display()
);
}
let mut providers = std::collections::BTreeMap::new();
providers.insert(
a.provider.clone(),
ProviderCfg {
kind: a.kind,
url: a.url,
},
);
let cfg = Config {
machine: Machine { name: a.machine },
root: Root { path: a.root },
providers,
groups: vec![Group {
name: a.group,
primary: a.provider.clone(),
mirror_to: vec![],
layout: Layout::BareWorktrees,
auto_materialize: true,
}],
sync: Default::default(),
config_repo: a.config_repo.map(|name| grove_core::config::ConfigRepo {
provider: a.provider,
name,
}),
};
// Validate by round-tripping through the parser before writing anything.
let text = toml::to_string_pretty(&cfg)?;
Config::parse(&text)?;
cfg.save(path)?;
Ok(cfg)
}
pub fn login(cfg: &Config, id: &str, tok: &str) -> Result<String> {
let pc = cfg
.providers
.get(id)
.with_context(|| format!("provider {id:?} is not in the config"))?;
let who = build(pc, tok.to_string()).test_connection()?;
// Keep the secret out of the store when the env override is in use.
token::set(id, tok)?;
Ok(who)
}
/// Creates the remote repo, the local bare layout, the mirrors and the registry entry.
pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Result<PathBuf> {
let grp = group(cfg, group_name)?;
let dir = cfg.root_path().join(&grp.name).join(name);
if dir.exists() {
bail!("{} already exists", dir.display());
}
let primary = connect(cfg, &grp.primary)?;
let remote = primary.api.create_repo(&NewRepo {
name: name.into(),
owner: None,
private,
description: String::new(),
})?;
println!(
"created {}/{} on {}",
remote.owner, remote.name, grp.primary
);
let wt = init_bare_layout(&dir, &remote.clone_url)?;
push_initial(&dir, &primary.git_env)?;
println!("pushed initial commit; worktree {}", wt.display());
for mid in &grp.mirror_to {
match configure_mirror(cfg, &primary, mid, &remote.owner, name, private) {
Ok(()) => println!("push mirror to {mid} configured"),
Err(e) => println!("warning: mirror to {mid} not configured: {e}"),
}
}
register(
cfg,
&Entry {
group: grp.name.clone(),
name: name.into(),
url: remote.clone_url,
},
)?;
Ok(wt)
}
fn configure_mirror(
cfg: &Config,
primary: &Forge,
mirror_id: &str,
owner: &str,
name: &str,
private: bool,
) -> Result<()> {
let m = connect(cfg, mirror_id)?;
let target = m.api.create_repo(&NewRepo {
name: name.into(),
owner: None,
private,
description: "Mirror managed by grove".into(),
})?;
primary.api.configure_mirror(
owner,
name,
&MirrorSpec {
remote_url: target.clone_url,
remote_username: m.login,
remote_token: token::get(mirror_id)?,
interval: "8h0m0s".into(),
sync_on_commit: true,
},
)?;
Ok(())
}
/// Lists remote repos of the group's primary that are not on disk; clones the named ones.
pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
let grp = group(cfg, group_name)?;
let primary = connect(cfg, &grp.primary)?;
let gdir = cfg.root_path().join(&grp.name);
let missing: Vec<_> = primary
.api
.list_repos()?
.into_iter()
.filter(|r| !gdir.join(&r.name).join(".bare").exists())
.collect();
if wanted.is_empty() {
println!("repos on {} not yet in {}:", grp.primary, gdir.display());
for r in &missing {
println!(
" {}/{}{}",
r.owner,
r.name,
if r.private { " (private)" } else { "" }
);
}
println!("run `grove import {group_name} <name>...` to clone them");
return Ok(());
}
for w in wanted {
let r = missing
.iter()
.find(|r| &r.name == w)
.with_context(|| format!("{w:?} is not a remote repo missing locally"))?;
let dir = gdir.join(&r.name);
clone_bare_layout(&r.clone_url, &dir, &primary.git_env)?;
println!("imported {} -> {}", r.name, dir.display());
register(
cfg,
&Entry {
group: grp.name.clone(),
name: r.name.clone(),
url: r.clone_url.clone(),
},
)?;
}
Ok(())
}
// ---- config repo -------------------------------------------------------------------------
fn config_repo_dir() -> Result<PathBuf> {
Ok(Config::state_dir()
.context("cannot determine state dir")?
.join("config-repo"))
}
/// Makes sure the local clone of the config repo exists and is current. Returns its path.
pub(crate) fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, Forge)> {
let cr = cfg
.config_repo
.as_ref()
.context("no [config_repo] in the config")?;
let forge = connect(cfg, &cr.provider)?;
let dir = config_repo_dir()?;
if !dir.join(".git").exists() {
let exists = forge
.api
.list_repos()?
.into_iter()
.find(|r| r.name == cr.name);
let url = match exists {
Some(r) => r.clone_url,
None if create => {
let r = forge.api.create_repo(&NewRepo {
name: cr.name.clone(),
owner: None,
private: true,
description: "grove configuration (managed repos, machines)".into(),
})?;
r.clone_url
}
None => bail!(
"config repo {:?} does not exist on {}",
cr.name,
cr.provider
),
};
fs::create_dir_all(dir.parent().unwrap())?;
let g = with_env(Git::new(dir.parent().unwrap()), &forge.git_env);
g.run(&["clone", "-q", &url, &dir.to_string_lossy()])?;
} else {
// An empty remote has nothing to pull yet.
let _ = with_env(Git::new(&dir), &forge.git_env).run(&["pull", "-q", "--ff-only"]);
}
Ok((dir, forge))
}
fn read_registry(dir: &Path) -> Result<Registry> {
match fs::read_to_string(dir.join("repos.toml")) {
Ok(t) => Registry::parse(&t).map_err(anyhow::Error::msg),
Err(_) => Ok(Registry::default()),
}
}
pub(crate) fn commit_and_push(cfg: &Config, dir: &Path, forge: &Forge, msg: &str) -> Result<()> {
let g = Git::new(dir)
.with_env("GIT_AUTHOR_NAME", "grove")
.with_env("GIT_AUTHOR_EMAIL", "grove@localhost")
.with_env("GIT_COMMITTER_NAME", "grove")
.with_env("GIT_COMMITTER_EMAIL", "grove@localhost");
g.run(&["add", "-A"])?;
if g.run(&["status", "--porcelain"])?.is_empty() {
return Ok(());
}
let machine = &cfg.machine.name;
g.run(&["commit", "-q", "-m", &format!("{msg} (from {machine})")])?;
let branch = g.run(&["rev-parse", "--abbrev-ref", "HEAD"])?;
with_env(g, &forge.git_env).run(&["push", "-q", "-u", "origin", &branch])?;
Ok(())
}
fn write_heartbeat(cfg: &Config, dir: &Path) -> Result<()> {
let m = dir.join("machines");
fs::create_dir_all(&m)?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let body = serde_json::json!({"machine": cfg.machine.name, "last_registered": now});
fs::write(
m.join(format!("{}.json", cfg.machine.name)),
serde_json::to_string_pretty(&body)?,
)?;
Ok(())
}
/// Adds a repo to the config repo, if one is configured (silently skipped otherwise).
pub fn register(cfg: &Config, e: &Entry) -> Result<()> {
if cfg.config_repo.is_none() {
return Ok(());
}
let (dir, forge) = config_repo_open(cfg, true)?;
let mut reg = read_registry(&dir)?;
reg.upsert(e.clone());
fs::write(dir.join("repos.toml"), reg.to_text())?;
write_heartbeat(cfg, &dir)?;
commit_and_push(
cfg,
&dir,
&forge,
&format!("register {}/{}", e.group, e.name),
)
}
/// First machine: creates the config repo (if needed) and registers every repo already on disk.
pub fn config_repo_init(cfg: &Config) -> Result<usize> {
let (dir, forge) = config_repo_open(cfg, true)?;
let mut reg = read_registry(&dir)?;
for grp in &cfg.groups {
let gdir = cfg.root_path().join(&grp.name);
let Ok(rd) = fs::read_dir(&gdir) else {
continue;
};
for e in rd.filter_map(Result::ok) {
let bare = e.path().join(".bare");
if !bare.is_dir() {
continue;
}
let Some(url) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])?
else {
continue;
};
reg.upsert(Entry {
group: grp.name.clone(),
name: e.file_name().to_string_lossy().into_owned(),
url,
});
}
}
fs::write(dir.join("repos.toml"), reg.to_text())?;
write_heartbeat(cfg, &dir)?;
commit_and_push(cfg, &dir, &forge, "update registry")?;
Ok(reg.repos.len())
}
/// Fresh machine: materializes every repo of the config repo under the root.
pub fn bootstrap(cfg: &Config) -> Result<(usize, usize)> {
let (dir, forge) = config_repo_open(cfg, false)?;
let reg = read_registry(&dir)?;
let (mut done, mut skipped) = (0, 0);
for e in &reg.repos {
let target = cfg.root_path().join(&e.group).join(&e.name);
if target.join(".bare").exists() {
skipped += 1;
continue;
}
match clone_bare_layout(&e.url, &target, &forge.git_env) {
Ok(_) => {
println!("cloned {}/{}", e.group, e.name);
done += 1;
}
Err(err) => println!("FAILED {}/{}: {err}", e.group, e.name),
}
}
write_heartbeat(cfg, &dir)?;
commit_and_push(cfg, &dir, &forge, "machine heartbeat")?;
Ok((done, skipped))
}
+6
View File
@@ -82,3 +82,9 @@ exclusion of `refs/sync/*` on this Gitea (needs a mirror target and credentials)
Observed UX noise: a stale snapshot from another machine is reported as "not applied" on every
pass until that machine syncs again.
## Bug found later (Phase 5 tests)
`clone_bare_layout` created worktrees without upstream tracking, so `Diverged` and `Behind` were
reported as `Synced` on repos cloned by grove itself. Fixed: every local branch with an `origin/<br>`
counterpart gets `--set-upstream-to` before worktrees are materialized (asserted in `tests/registry.rs`).
+55
View File
@@ -0,0 +1,55 @@
# Phase 3: GUI
## Layout
| Part | Where | Status |
|---|---|---|
| Frontend (plain HTML/CSS/JS, no build step) | `gui/ui/` | Implemented, exercised in a browser against a live daemon |
| Dev bridge (`grove-bridge`, std-only HTTP server on 127.0.0.1) | `crates/grove-bridge/` | Implemented, unit-tested, exercised end to end |
| Tauri v2 shell with tray | `gui/src-tauri/` | **Written but never compiled** (see below) |
The frontend talks to a backend through one adapter in `gui/ui/app.js`: `window.__TAURI__` commands
(`ipc`, `cli`, `config`) when running inside Tauri, otherwise `fetch('/api/...')` against the bridge.
The GUI contains no sync logic: state comes from the daemon over its Unix socket, and every action
(new, import, resolve, login, secrets, bootstrap) shells out to the allow-listed `grove` subcommands.
## Screens
Repositories (aggregate pill: all synced / syncing / paused / needs attention / daemon offline),
repository detail (per-worktree state and what the next pass will do, resolve panel for `Diverged`),
Activity (live log, filter), New repository, Import, Settings (config, token login, config repo,
secrets), and onboarding when no config exists. Toasts (and browser notifications when permitted)
fire on a transition into `Diverged` or `Error`.
Resolve actions (save as branch / take remote / keep mine) always ask for confirmation and write a
backup ref first. Comparing both sides stays in the CLI (`grove resolve --compare`).
## Dev bridge safety
Binds 127.0.0.1 only, rejects non-local `Host` headers (DNS rebinding) and POSTs without
`X-Grove: 1` (cross-site forms cannot set it). Only these subcommands are forwarded: `init login new
import config-repo-init bootstrap resolve secrets sync status`. Verified: a POST without the header gets 403.
```bash
cargo run -p grove-bridge -- --ui gui/ui # then open http://127.0.0.1:4780
```
## Tauri shell: not verified
Needs system packages that were missing on the dev machine and no root was available:
```bash
sudo dnf install webkit2gtk4.1-devel libsoup3-devel librsvg2-devel # Fedora
cd gui/src-tauri && cargo install tauri-cli --locked && cargo tauri dev
```
The shell is ~80 lines: three commands reusing `grove-bridge`, a tray (open / pause-resume / quit),
and close-to-tray. The CSP allows only `self`; the capability file grants `core:default` only.
Expect small compile fixes on the first build. It is intentionally outside the workspace so that
`cargo test` works without webkit installed.
## Not done
- Screenshots/visual QA inside the real Tauri window.
- Side-by-side compare view for `Diverged` (CLI only).
- Native notifications from the Tauri side (the web Notification API is used).
+52
View File
@@ -0,0 +1,52 @@
# Phase 4: providers and wizards
Crate `grove-providers`: `Provider` trait with Gitea/Forgejo (`/api/v1`) and GitHub clients over
`ureq`, plus token storage. The CLI (`crates/grove/src/workflow.rs`) composes them.
## Tokens
`GROVE_TOKEN_<ID>` (id upper-cased, non-alphanumerics to `_`) wins; otherwise the desktop Secret
Service via `keyring` (service `grove`, user = provider id). Tokens are never written to the config
file. `grove login <id>` reads the token from stdin (never argv), checks it against the forge and
stores it. HTTPS git operations of the wizards authenticate through `http.extraHeader` set in the
process environment only (Gitea/Forgejo); for GitHub they use the user's credential helper.
## Commands
| Command | What it does |
|---|---|
| `grove init` | Writes a first `config.toml` (machine, root, one provider, one group, optional config repo) |
| `grove login <provider>` | Stores the API token after verifying it |
| `grove new <group> <name> [--public]` | Creates the repo on the group's primary forge, the local bare+worktree layout, an initial commit, pushes, configures push mirrors, registers it in the config repo |
| `grove import <group> [names...]` | Lists remote repos not on this machine; with names, clones them into the layout |
| `grove config-repo-init` | Creates the private config repo and registers every repo already on disk |
| `grove bootstrap` | Fresh machine: clones every repo in the config repo under the root |
## Config repo
A private repo (name from `[config_repo]`) holding `repos.toml` (`group`, `name`, `url` per repo) and
`machines/<name>.json` (written only when the registry changes, so no commit noise). The local
clone lives in `<state dir>/config-repo`. It is created on the first registration if missing.
## Mirrors
Gitea/Forgejo: the primary creates a push mirror via `POST /repos/{o}/{r}/push_mirrors`
(`sync_on_commit`, 8 h interval) to a repo created on the mirror provider. GitHub has no push
mirrors: `configure_mirror` reports `Unsupported` and `new` warns. The daemon-side fallback (push
branches and tags only, never `refs/sync/*`) is **not implemented**.
## Validation
- Unit/mock tests: `crates/grove-providers/tests/api.rs` (requests, auth headers, error mapping,
org endpoint, no-push-mirror on GitHub, env token override), `grove-core/tests/registry.rs`
(bare layout creation, push, clone into layout, registry round trip).
- End to end against a local Forgejo 11: `spikes/phase4-e2e.sh` (new x2, config repo, a second
machine rebuilds the workspace with `login` env token + `bootstrap`). Passed; repos cleaned up.
- Also exercised there: `import` (list, clone, unknown name rejected), invalid token rejected (401).
## Not done / not verified
- Mirror creation against a real forge pair (only the API call shape is mock-tested).
- Secret Service storage on a real desktop session (the sandbox has none; env override used).
- GitHub provider against github.com (mock only). GitHub git auth relies on the credential helper.
- Deleting remote repos is deliberately not implemented.
+26
View File
@@ -0,0 +1,26 @@
# Phase 5: resolve, safety, packaging
## Done
- **Resolve** (`grove resolve <worktree> --take-remote | --keep-local | --save-as BRANCH | --compare`,
also in the GUI). Every choice writes a backup ref first (`refs/sync-backup/<machine>/<stamp>/resolve-local/<branch>`
or `resolve-remote/<branch>`). `--keep-local` uses force-with-lease on the observed upstream tip.
`--take-remote` and `--save-as` refuse on a dirty worktree or when ignored files would be overwritten.
`--save-as` needs the bare + worktrees layout. `status --plan` explains what the next pass will do.
Covered by `crates/grove-core/tests/resolve.rs` (4 tests).
- **Size limit**: `sync.max_file_mb` (default 50, 0 = unlimited). Oversized changed files are left out of
the snapshot (reset to their HEAD version, or absent), reported in the pass result and the daemon log.
Covered by `tests/size_limit.rs`.
- **Encrypted files** (`grove secrets init|push|pull|rekey`, age x25519): see `phase4.md`.
- **Packaging**: `cargo build --release --workspace && cargo deb -p grove --no-build` produces
`target/debian/grove_*.deb` (CLI, daemon, systemd *user* unit `/usr/lib/systemd/user/groved.service`).
The package was built; it was **not installed or run**. `dpkg-shlibdeps` is unavailable here, so `$auto`
dependencies were not computed.
## Not done
- AppImage (no `appimagetool`) and Flatpak: not attempted. The Tauri bundle config requests `deb` and
`appimage`, untested.
- Daemon-side mirroring fallback for GitHub (GitHub has no push mirrors; `configure_mirror` returns `Unsupported`).
- Syncing agent sessions (optional item in the plan): not implemented.
- A real two-PC run, a real cross-forge mirror, Secret Service on a desktop, github.com: unverified.
+2
View File
@@ -0,0 +1,2 @@
/target
/gen
+19
View File
@@ -0,0 +1,19 @@
# Tauri shell for the grove GUI. Deliberately NOT a member of the root workspace: it needs the
# webkit2gtk/libsoup system packages (see docs/phase3.md) and must not break `cargo test` without them.
[package]
name = "grove-gui"
version = "0.1.0"
edition = "2024"
license = "MIT"
description = "grove desktop GUI (Tauri shell around gui/ui)"
[workspace]
[dependencies]
grove-bridge = { path = "../../crates/grove-bridge" }
grove-daemon = { path = "../../crates/grove-daemon" }
serde_json = "1"
tauri = { version = "2", features = ["tray-icon"] }
[build-dependencies]
tauri-build = "2"
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Main window: only the app's own commands, no filesystem or shell access.",
"windows": ["main"],
"permissions": ["core:default"]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 209 B

+79
View File
@@ -0,0 +1,79 @@
//! Tauri shell: serves `gui/ui` and exposes the same three calls the dev bridge offers
//! (`ipc`, `cli`, `config`) as Tauri commands, backed by the shared `grove-bridge` library.
//! Also a tray icon with open / pause-resume / quit so the window can be closed.
use grove_bridge::Bridge;
use serde_json::{Value, json};
use tauri::menu::{Menu, MenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{Manager, WindowEvent};
fn bridge() -> Bridge {
Bridge {
grove_bin: std::env::var_os("GROVE_BIN")
.map(Into::into)
.unwrap_or_else(|| "grove".into()),
config: None,
socket: grove_daemon::ipc::default_socket_path(),
}
}
#[tauri::command]
fn ipc(req: Value) -> Value {
bridge().ipc(&req)
}
#[tauri::command]
fn cli(args: Vec<String>, stdin: Option<String>) -> Value {
bridge().cli(&args, &stdin.unwrap_or_default())
}
#[tauri::command]
fn config() -> Value {
match bridge().config_json() {
Some(c) => json!({"exists": true, "config": c}),
None => json!({"exists": false}),
}
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![ipc, cli, config])
.setup(|app| {
let open = MenuItem::with_id(app, "open", "Open Grove", true, None::<&str>)?;
let pause = MenuItem::with_id(app, "pause", "Pause / resume sync", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Quit GUI (daemon keeps running)", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&open, &pause, &quit])?;
TrayIconBuilder::new()
.icon(app.default_window_icon().cloned().expect("window icon"))
.menu(&menu)
.on_menu_event(|app, ev| match ev.id.as_ref() {
"open" => {
if let Some(w) = app.get_webview_window("main") {
let _ = w.show();
let _ = w.set_focus();
}
}
"pause" => {
let b = bridge();
let paused = b.ipc(&json!({"v":1,"cmd":"status"}))["data"]["paused"]
.as_bool()
.unwrap_or(false);
b.ipc(&json!({"v":1,"cmd": if paused {"resume"} else {"pause"}}));
}
"quit" => app.exit(0),
_ => {}
})
.build(app)?;
Ok(())
})
// Closing the window hides it; the tray keeps the app (and its notifications) alive.
.on_window_event(|w, ev| {
if let WindowEvent::CloseRequested { api, .. } = ev {
api.prevent_close();
let _ = w.hide();
}
})
.run(tauri::generate_context!())
.expect("error while running grove-gui");
}
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Grove",
"version": "0.1.0",
"identifier": "es.zenvairo.grove",
"build": { "frontendDist": "../ui" },
"app": {
"withGlobalTauri": true,
"windows": [{ "title": "Grove", "width": 1100, "height": 720, "minWidth": 720, "minHeight": 480 }],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
}
},
"bundle": {
"active": true,
"targets": ["deb", "appimage"],
"icon": ["icons/icon.png"],
"category": "DeveloperTool"
}
}
+367
View File
@@ -0,0 +1,367 @@
'use strict';
// ---- backend adapter: Tauri shell (invoke) or the localhost dev bridge (fetch) ----------------
const tauri = window.__TAURI__ && window.__TAURI__.core;
async function post(path, body) {
const r = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Grove': '1' }, body: JSON.stringify(body) });
if (!r.ok) throw new Error(r.status + ' ' + (await r.text()));
return r.json();
}
// Backend failures never throw into the UI: they come back as {ok:false, ...}.
const safe = (p, fail) => p.catch((e) => fail(String((e && e.message) || e)));
const ipc = (req) => safe(tauri ? tauri.invoke('ipc', { req }) : post('/api/ipc', req), (m) => ({ ok: false, offline: true, error: m }));
const cli = (args, stdin = '') => safe(tauri ? tauri.invoke('cli', { args, stdin }) : post('/api/cli', { args, stdin }), (m) => ({ ok: false, output: m }));
async function getConfig() {
if (tauri) return tauri.invoke('config');
return (await fetch('/api/config')).json();
}
// ---- tiny DOM helper (text is always set via textContent, never innerHTML) --------------------
function h(tag, attrs, ...kids) {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (k === 'class') e.className = v;
else if (k.startsWith('on')) e.addEventListener(k.slice(2), v);
else if (v === true) e.setAttribute(k, '');
else if (v !== false && v != null) e.setAttribute(k, v);
}
for (const c of kids.flat()) if (c != null && c !== false) e.append(c.nodeType ? c : document.createTextNode(c));
return e;
}
const $ = (s) => document.querySelector(s);
// ---- state ---------------------------------------------------------------------------------
const S = { out: {}, branchName: {}, busy: false, status: null, offline: false, config: undefined, log: [], logFilter: '', lastStates: new Map() };
const stateName = (s) => (s.startsWith('error') ? 'error' : s);
const STATE_LABEL = { synced: 'Synced', dirty: 'Editing', ahead: 'Ahead', behind: 'Behind', behinddirty: 'Behind + editing', diverged: 'Diverged', error: 'Error' };
const PLAN = {
synced: 'Nothing to do.',
dirty: 'Snapshot the working changes and push the snapshot ref.',
ahead: 'Nothing automatic: push your commits yourself.',
behind: 'Fast-forward to the remote tip.',
behinddirty: 'Keep your edits; adopt the remote tip only if the content is identical.',
diverged: 'Nothing automatic: choose how to resolve it.',
error: 'Retry with backoff; see the error.',
};
const short = (p) => p.split('/').slice(-2).join('/');
function ago(ts, now) {
if (!ts) return 'never';
const d = Math.max(0, (now || Date.now() / 1000) - ts);
if (d < 5) return 'just now';
if (d < 60) return Math.round(d) + 's ago';
if (d < 3600) return Math.round(d / 60) + ' min ago';
if (d < 86400) return Math.round(d / 3600) + ' h ago';
return Math.round(d / 86400) + ' d ago';
}
function toast(msg, bad) {
const t = h('div', { class: 'toast' + (bad ? ' bad' : ''), role: 'status' }, msg);
$('#toasts').append(t);
setTimeout(() => t.remove(), 5000);
}
function notify(title, body) {
toast(title + ': ' + body, true);
try {
if ('Notification' in window && Notification.permission === 'granted') new Notification(title, { body });
} catch (_) { /* notifications are optional */ }
}
const badge = (st) => h('span', { class: 'badge b-' + stateName(st) }, STATE_LABEL[stateName(st)] || st);
// ---- aggregate -------------------------------------------------------------------------------
function aggregate() {
const s = S.status;
if (S.offline || !s) return { cls: 'pill-muted', text: S.offline ? 'Daemon offline' : 'Connecting…', bad: 0 };
let attention = 0, dirty = 0, total = 0;
for (const r of s.repos) {
if (r.last_error && !r.worktrees.some((w) => stateName(w.state) === 'error')) attention++;
for (const w of r.worktrees) {
total++;
const n = stateName(w.state);
if (n === 'diverged' || n === 'error') attention++;
else if (n !== 'synced') dirty++;
}
}
if (s.paused) return { cls: 'pill-muted', text: 'Paused', total, attention };
if (attention) return { cls: 'pill-bad', text: attention + ' need' + (attention === 1 ? 's' : '') + ' attention', total, attention };
if (dirty) return { cls: 'pill-warn', text: dirty + ' syncing', total, attention };
return { cls: 'pill-ok', text: 'All synced', total, attention };
}
function renderTop() {
const a = aggregate();
$('#pill').className = 'pill ' + a.cls;
$('#pill-text').textContent = a.text;
const paused = S.status && S.status.paused;
$('#btn-pause').textContent = paused ? 'Resume sync' : 'Pause sync';
$('#btn-pause').disabled = S.offline;
$('#btn-sync').disabled = S.offline || paused;
const m = $('#machine');
m.textContent = '';
if (S.status) m.append('Machine ', h('b', {}, S.status.machine));
document.title = (a.attention ? '(' + a.attention + ') ' : '') + 'Grove';
}
// ---- views ---------------------------------------------------------------------------------
const views = {};
views.repos = () => {
const s = S.status;
if (S.offline) return offline();
if (!s) return h('p', { class: 'muted' }, 'Loading…');
const a = aggregate();
const stats = h('div', { class: 'grid2' },
stat(s.repos.length, 'Repositories'),
stat(a.total || 0, 'Worktrees'),
stat(a.attention || 0, 'Need attention'));
if (!s.repos.length) return h('div', {}, head('Repositories', 'Everything grove keeps in sync on this machine.'), h('div', { class: 'card empty' }, 'No repositories yet. Create one under “New repository” or clone existing ones with “Import”.'));
const rows = s.repos.map((r) => h('tr', { class: 'row', tabindex: 0, onclick: () => (location.hash = '#/repo/' + encodeURIComponent(r.path)), onkeydown: (e) => { if (e.key === 'Enter') location.hash = '#/repo/' + encodeURIComponent(r.path); } },
h('td', {}, h('div', { class: 'repo-name' }, short(r.path)), h('div', { class: 'path' }, r.path)),
h('td', {}, r.worktrees.map((w) => h('span', { title: w.branch || '' }, badge(w.state), h('span', { class: 'muted' }, (w.branch || '(detached)') + ' ')))),
h('td', {}, h('span', { class: 'muted' }, r.phase)),
h('td', {}, h('span', { class: 'muted' }, ago(r.last_sync, s.now)), r.last_error && h('div', { class: 'err' }, r.last_error))));
return h('div', {}, head('Repositories', 'Everything grove keeps in sync on this machine.'), stats,
h('div', { class: 'card' }, h('table', { class: 'table' },
h('thead', {}, h('tr', {}, h('th', {}, 'Repository'), h('th', {}, 'Worktrees'), h('th', {}, 'Phase'), h('th', {}, 'Last sync'))),
h('tbody', {}, rows))));
};
const stat = (n, label) => h('div', { class: 'card stat' }, h('b', {}, String(n)), h('span', {}, label));
const head = (t, sub) => h('div', {}, h('h1', {}, t), h('p', { class: 'sub' }, sub));
const offline = () => h('div', { class: 'card empty' }, h('b', {}, 'The grove daemon is not running.'), h('p', {}, 'Start it with ', h('code', {}, 'systemctl --user start groved'), ' (or run ', h('code', {}, 'groved'), ' in a terminal).'));
views.repo = (path) => {
const r = S.status && S.status.repos.find((x) => x.path === path);
if (S.offline) return offline();
if (!r) return h('div', {}, h('a', { class: 'back', href: '#/repos' }, '← Repositories'), h('p', { class: 'muted' }, 'Repository not found.'));
const rows = r.worktrees.map((w) => {
const n = stateName(w.state);
return h('tr', {},
h('td', {}, h('div', { class: 'repo-name' }, w.branch || '(detached)'), h('div', { class: 'path' }, w.path || '')),
h('td', {}, badge(w.state)),
h('td', { class: 'muted' }, PLAN[n] || ''));
});
const diverged = r.worktrees.filter((w) => stateName(w.state) === 'diverged');
return h('div', {},
h('a', { class: 'back', href: '#/repos' }, '← Repositories'),
h('h1', {}, short(r.path)),
h('p', { class: 'sub path' }, r.path),
h('div', { class: 'actions' }, h('button', { class: 'btn', onclick: () => syncRepo(r.path) }, 'Sync this repository')),
r.last_error && h('div', { class: 'err' }, r.last_error),
h('h2', {}, 'Worktrees'),
h('div', { class: 'card' }, h('table', { class: 'table' },
h('thead', {}, h('tr', {}, h('th', {}, 'Branch'), h('th', {}, 'State'), h('th', {}, 'Next sync pass'))), h('tbody', {}, rows))),
diverged.map((w) => resolvePanel(w)),
r.worktrees.filter((w) => stateName(w.state) !== 'diverged' && S.out[w.path]).map((w) => h('div', { class: 'term' + (S.out[w.path].ok ? '' : ' fail') }, S.out[w.path].text)));
};
function resolvePanel(w) {
const out = h('div');
const run = async (flag, label) => {
if (!confirm(label + '\n\nA backup ref is written first, so nothing is lost. Continue?')) return;
const r = await cli(['resolve', w.path, ...flag]);
S.out[w.path] = { ok: r.ok, text: r.output };
render(true);
refresh();
};
if (!w.path) return h('div', { class: 'callout' }, 'Diverged, but this daemon does not report the worktree path. Update groved.');
const prev = S.out[w.path];
if (prev) out.append(h('div', { class: 'term' + (prev.ok ? '' : ' fail') }, prev.text));
const branchName = h('input', { type: 'text', id: 'brname', placeholder: 'branch name', 'aria-label': 'New branch name', value: S.branchName[w.path] ?? (w.branch || 'work') + '-local', oninput: (e) => { S.branchName[w.path] = e.target.value; } });
return h('div', { class: 'callout' },
h('h3', {}, 'Diverged: ' + (w.branch || '') + ' has commits here and on the remote'),
h('p', {}, 'Grove never merges for you. Pick what should win:'),
h('div', { class: 'actions' },
h('button', { class: 'btn', onclick: () => run(['--save-as', branchName.value], 'Keep your commits on branch “' + branchName.value + '” and move this branch to the remote tip') }, 'Save mine as a branch'), branchName,
h('button', { class: 'btn', onclick: () => run(['--take-remote'], 'Discard your local commits and take the remote tip') }, 'Take remote'),
h('button', { class: 'btn btn-danger', onclick: () => run(['--keep-local'], 'Overwrite the remote branch with your local commits') }, 'Keep mine (overwrite remote)')),
h('p', { class: 'muted' }, 'To inspect both sides first, run ', h('code', {}, 'grove resolve ' + w.path + ' --compare'), ' in a terminal.'),
out);
}
views.activity = () => {
if (S.offline) return offline();
const f = S.logFilter.toLowerCase();
const items = S.log.slice().reverse().filter((e) => !f || (e.kind + ' ' + (e.repo || '') + ' ' + e.msg).toLowerCase().includes(f));
const filter = h('input', { type: 'text', id: 'flt', placeholder: 'Filter…', 'aria-label': 'Filter activity', value: S.logFilter, oninput: (e) => { S.logFilter = e.target.value; render(true); } });
const body = items.length
? h('table', { class: 'table' }, h('thead', {}, h('tr', {}, h('th', {}, 'Time'), h('th', {}, 'Event'), h('th', {}, 'Repository'), h('th', {}, 'Details'))),
h('tbody', {}, items.map((e) => h('tr', {},
h('td', { class: 'muted' }, new Date(e.ts * 1000).toLocaleTimeString('en-GB')),
h('td', {}, h('span', { class: 'kind k-' + e.kind }, e.kind)),
h('td', { class: 'muted' }, e.repo || '–'),
h('td', {}, e.msg)))))
: h('div', { class: 'empty' }, 'No activity yet.');
return h('div', {}, head('Activity', 'What the daemon did, newest first.'), h('div', { class: 'actions' }, filter), h('div', { class: 'card', style: 'margin-top:12px' }, body));
};
function groupSelect() {
const groups = (S.config && S.config.groups) || [];
return h('select', { id: 'group', 'aria-label': 'Group' }, groups.map((g) => h('option', { value: g.name }, g.name + ' → ' + g.primary)));
}
function needConfig() {
return S.config && S.config.exists ? null : h('div', { class: 'card empty' }, 'Finish onboarding first (Settings).');
}
views.new = () => {
if (needConfig()) return needConfig();
const out = h('div');
const name = h('input', { type: 'text', id: 'name', placeholder: 'my-project', pattern: '[A-Za-z0-9._-]+' });
const pub = h('input', { type: 'checkbox', id: 'public' });
const btn = h('button', { class: 'btn btn-primary', type: 'submit' }, 'Create repository');
const form = h('form', { class: 'card form', onsubmit: async (e) => {
e.preventDefault();
if (!name.value.trim()) return;
btn.disabled = true; btn.textContent = 'Creating…';
const args = ['new', $('#group').value, name.value.trim()].concat(pub.checked ? ['--public'] : []);
const r = await cli(args);
out.replaceChildren(h('div', { class: 'term' + (r.ok ? '' : ' fail') }, r.output));
btn.disabled = false; btn.textContent = 'Create repository';
if (r.ok) { toast('Repository created'); name.value = ''; refresh(); }
} },
h('label', {}, 'Group', groupSelect()),
h('label', {}, 'Name', name, h('span', { class: 'hint' }, 'Created on the group’s primary forge, with an initial commit and the bare + worktrees layout.')),
h('label', { class: 'check' }, pub, 'Public repository'), btn);
return h('div', {}, head('New repository', 'Creates the remote, the local checkout, the mirrors and registers it for your other machines.'), form, out);
};
views.import = () => {
if (needConfig()) return needConfig();
const out = h('div'), list = h('div');
const sel = groupSelect();
const scan = async () => {
list.replaceChildren(h('p', { class: 'muted' }, 'Scanning…'));
out.replaceChildren();
const r = await cli(['import', sel.value]);
const names = (r.output.match(/^\s+\S+\/(\S+?)(?: \(private\))?$/gm) || []).map((l) => l.trim().split(/\s+/)[0].split('/')[1]);
if (!r.ok) return list.replaceChildren(h('div', { class: 'term fail' }, r.output));
if (!names.length) return list.replaceChildren(h('p', { class: 'muted' }, 'Nothing to import: every remote repository is already on this machine.'));
const boxes = names.map((n) => h('label', { class: 'check' }, h('input', { type: 'checkbox', value: n }), n));
const go = h('button', { class: 'btn btn-primary', onclick: async () => {
const picked = [...list.querySelectorAll('input:checked')].map((i) => i.value);
if (!picked.length) return;
go.disabled = true;
const res = await cli(['import', sel.value, ...picked]);
out.replaceChildren(h('div', { class: 'term' + (res.ok ? '' : ' fail') }, res.output));
go.disabled = false; refresh();
if (res.ok) scan();
} }, 'Import selected');
list.replaceChildren(h('div', { class: 'card form' }, boxes, go));
};
return h('div', {}, head('Import', 'Clone repositories that exist on your forge but not on this machine.'),
h('div', { class: 'actions' }, sel, h('button', { class: 'btn', onclick: scan }, 'Scan remote')), list, out);
};
views.settings = () => {
const c = S.config;
if (!c || !c.exists) return onboarding();
const cfg = c.config;
const kv = (rows) => h('dl', { class: 'kv card' }, rows.flatMap(([k, v]) => [h('dt', {}, k), h('dd', {}, v)]));
const provs = Object.entries(cfg.providers || {});
const out = h('div');
const prov = h('select', { id: 'tokprov', 'aria-label': 'Provider' }, provs.map(([id]) => h('option', { value: id }, id)));
const tok = h('input', { type: 'password', id: 'tok', autocomplete: 'off', placeholder: 'API token' });
const act = async (args, stdin) => { const r = await cli(args, stdin); out.replaceChildren(h('div', { class: 'term' + (r.ok ? '' : ' fail') }, r.output)); refresh(); };
return h('div', {}, head('Settings', 'Read from config.toml. Tokens live in the system keyring, never in the file.'),
h('h2', {}, 'This machine'),
kv([['Name', cfg.machine.name], ['Workspace root', cfg.root.path], ['Fetch interval', ((cfg.sync && cfg.sync.fetch_interval_s) || 60) + ' s'], ['Largest synced file', ((cfg.sync && cfg.sync.max_file_mb) ?? 50) + ' MiB']]),
h('h2', {}, 'Providers'),
kv(provs.map(([id, p]) => [id, p.kind + (p.url ? ' · ' + p.url : '')])),
h('h2', {}, 'Groups'),
kv((cfg.groups || []).map((g) => [g.name, 'primary ' + g.primary + (g.mirror_to && g.mirror_to.length ? ' · mirrors: ' + g.mirror_to.join(', ') : '') + ' · ' + (g.layout || 'bare-worktrees')])),
h('h2', {}, 'Config repository'),
kv([['Repository', cfg.config_repo ? cfg.config_repo.name + ' on ' + cfg.config_repo.provider : 'not configured']]),
h('div', { class: 'actions' },
h('button', { class: 'btn', onclick: () => act(['config-repo-init']) }, 'Register repos on disk'),
h('button', { class: 'btn', onclick: () => act(['bootstrap']) }, 'Bootstrap from config repo')),
h('h2', {}, 'Sign in to a provider'),
h('form', { class: 'card form', onsubmit: (e) => { e.preventDefault(); if (tok.value) { act(['login', prov.value], tok.value + '\n'); tok.value = ''; } } },
h('label', {}, 'Provider', prov), h('label', {}, 'Token', tok, h('span', { class: 'hint' }, 'Needs repository read/write scope. Sent to the forge only.')),
h('button', { class: 'btn btn-primary', type: 'submit' }, 'Verify and store')),
h('h2', {}, 'Encrypted files (.env)'),
h('div', { class: 'actions' },
h('button', { class: 'btn', onclick: () => act(['secrets', 'init']) }, 'Create this machine’s key'),
h('button', { class: 'btn', onclick: () => act(['secrets', 'pull']) }, 'Pull secrets'),
h('button', { class: 'btn', onclick: () => act(['secrets', 'rekey']) }, 'Re-encrypt for all machines')),
out);
};
function onboarding() {
const f = {};
const field = (id, label, value, hint) => { f[id] = h('input', { type: 'text', id, value }); return h('label', {}, label, f[id], hint && h('span', { class: 'hint' }, hint)); };
f.kind = h('select', { id: 'kind' }, ['gitea', 'forgejo', 'github'].map((k) => h('option', { value: k }, k)));
f.token = h('input', { type: 'password', id: 'token', autocomplete: 'off' });
const out = h('div');
const btn = h('button', { class: 'btn btn-primary', type: 'submit' }, 'Set up grove');
const form = h('form', { class: 'card form', onsubmit: async (e) => {
e.preventDefault(); btn.disabled = true;
const lines = [];
const step = async (args, stdin) => { const r = await cli(args, stdin); lines.push('$ grove ' + args[0] + '\n' + r.output); out.replaceChildren(h('div', { class: 'term' + (r.ok ? '' : ' fail') }, lines.join('\n\n'))); return r.ok; };
const a = ['init', '--machine', f.machine.value, '--root', f.root.value, '--provider', f.provider.value, '--kind', f.kind.value, '--group', f.group.value, '--config-repo', f.crepo.value];
if (f.url.value) a.push('--url', f.url.value);
const existing = await getConfig(); // a previous attempt may already have written the config
if ((existing.exists || await step(a)) && await step(['login', f.provider.value], f.token.value + '\n') && await step(['bootstrap'])) { toast('All set'); S.config = undefined; await refresh(); location.hash = '#/repos'; }
btn.disabled = false;
} },
field('machine', 'Machine name', 'my-laptop', 'Letters, digits, - and _. Unique per computer.'),
field('root', 'Workspace folder', '~/Workspace'),
h('label', {}, 'Forge type', f.kind),
field('provider', 'Provider id', 'main'),
field('url', 'Forge URL', 'https://git.example.com', 'Empty for github.com.'),
field('group', 'First group', 'work'),
field('crepo', 'Config repository', 'grove-config', 'Private repo holding the list of your repos, so a new machine only needs to sign in.'),
h('label', {}, 'API token', f.token), btn);
return h('div', {}, head('Welcome to Grove', 'Set up this machine. On a second computer this is all you do: sign in and your workspace appears.'), form, out);
}
// ---- router / render -------------------------------------------------------------------------
function route() {
const hash = location.hash.replace(/^#\/?/, '') || 'repos';
const [name, ...rest] = hash.split('/');
return { name, arg: rest.length ? decodeURIComponent(rest.join('/')) : null };
}
let lastKey = '';
function render(force) {
const { name, arg } = route();
document.querySelectorAll('#nav a').forEach((a) => a.classList.toggle('active', a.dataset.route === (name === 'repo' ? 'repos' : name)));
renderTop();
// Avoid clobbering forms while the user types: re-render form views only on navigation.
const formView = ['new', 'import', 'settings'].includes(name);
const key = name + '|' + arg;
if (!force && formView && key === lastKey) return;
lastKey = key;
// Never rebuild under the user's cursor on a background poll.
const ae = document.activeElement;
const typing = ae && $('#view').contains(ae) && /^(INPUT|SELECT|TEXTAREA)$/.test(ae.tagName);
if (!force && typing) return;
const keep = typing && ae.id ? { id: ae.id, pos: ae.selectionStart } : null;
const v = name === 'repo' ? views.repo(arg) : (views[name] || views.repos)();
$('#view').replaceChildren(v);
if (keep) { const e = document.getElementById(keep.id); if (e) { e.focus(); try { e.setSelectionRange(keep.pos, keep.pos); } catch (_) { /* not a text input */ } } }
}
// ---- actions & polling -----------------------------------------------------------------------
async function syncRepo(path) {
const r = await ipc({ v: 1, cmd: 'sync', repo: path });
toast(r.ok ? 'Sync queued' : r.error, !r.ok);
}
$('#btn-sync').addEventListener('click', async () => { const r = await ipc({ v: 1, cmd: 'sync' }); toast(r.ok ? 'Sync queued for all repositories' : r.error, !r.ok); });
$('#btn-pause').addEventListener('click', async () => {
const paused = S.status && S.status.paused;
await ipc({ v: 1, cmd: paused ? 'resume' : 'pause' });
refresh();
});
function watchTransitions() {
if (!S.status) return;
for (const r of S.status.repos) for (const w of r.worktrees) {
const key = w.path || r.path + w.branch, n = stateName(w.state), prev = S.lastStates.get(key);
if (prev && prev !== n && (n === 'diverged' || n === 'error')) notify(n === 'diverged' ? 'Diverged' : 'Sync error', short(r.path) + ' · ' + (w.branch || ''));
S.lastStates.set(key, n);
}
}
async function refresh() {
if (S.busy) return;
S.busy = true;
try {
const st = await ipc({ v: 1, cmd: 'status' });
S.offline = !st.ok; S.status = st.ok ? st.data : null;
if (st.ok) { const lg = await ipc({ v: 1, cmd: 'log', limit: 200 }); if (lg.ok) S.log = lg.data; }
} catch (_) { S.offline = true; S.status = null; }
if (S.config === undefined) { try { S.config = await getConfig(); } catch (_) { S.config = { exists: false }; } }
try { watchTransitions(); } finally { S.busy = false; }
render(false);
}
window.addEventListener('hashchange', () => render(true));
refresh().then(() => { if (!(S.config && S.config.exists) && !location.hash) location.hash = '#/settings'; });
setInterval(refresh, 2000); // refresh() skips while a previous one is still in flight
+36
View File
@@ -0,0 +1,36 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grove</title>
<link rel="icon" href="logo.svg" type="image/svg+xml">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="app">
<aside class="side">
<div class="brand"><img src="logo.svg" alt="" width="26" height="26"><span>Grove</span></div>
<nav id="nav">
<a href="#/repos" data-route="repos">Repositories</a>
<a href="#/activity" data-route="activity">Activity</a>
<a href="#/new" data-route="new">New repository</a>
<a href="#/import" data-route="import">Import</a>
<a href="#/settings" data-route="settings">Settings</a>
</nav>
<div class="machine" id="machine"></div>
</aside>
<div class="main">
<header class="top">
<div id="pill" class="pill pill-muted"><span class="dot"></span><span id="pill-text">Connecting…</span></div>
<div class="spacer"></div>
<button id="btn-sync" class="btn">Sync now</button>
<button id="btn-pause" class="btn btn-primary">Pause sync</button>
</header>
<main id="view" class="view" aria-live="polite"></main>
</div>
</div>
<div id="toasts" class="toasts"></div>
<script src="app.js"></script>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#1f7a4d"/><path d="M16 26V15M16 15c0-4 3-7 7-7 0 4-3 7-7 7zM16 19c0-3-2-5-5-5 0 3 2 5 5 5z" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>

After

Width:  |  Height:  |  Size: 294 B

+98
View File
@@ -0,0 +1,98 @@
:root {
--bg: #f5f6f4; --panel: #ffffff; --text: #1b2420; --muted: #66726b; --line: #e1e5e1;
--accent: #1f7a4d; --accent-ink: #ffffff; --accent-soft: #e3f2ea;
--ok: #1f7a4d; --ok-bg: #e3f2ea;
--warn: #9a6200; --warn-bg: #fdf0d5;
--info: #1d5fa8; --info-bg: #e3eefa;
--bad: #b3261e; --bad-bg: #fbe4e1;
--mono: ui-monospace, "SF Mono", "Cascadia Mono", Menlo, Consolas, monospace;
--radius: 10px;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121714; --panel: #1a211d; --text: #e6ede8; --muted: #93a39a; --line: #2a342e;
--accent: #3fb27a; --accent-ink: #08140d; --accent-soft: #1d3a2b;
--ok: #5bd197; --ok-bg: #1d3a2b; --warn: #f0b64a; --warn-bg: #3a2e12;
--info: #7ab4f0; --info-bg: #17304d; --bad: #ff8a80; --bad-bg: #4a1f1b;
}
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
.app { display: grid; grid-template-columns: 220px 1fr; min-height: 100%; }
.side { background: var(--panel); border-right: 1px solid var(--line); padding: 18px 14px; display: flex; flex-direction: column; gap: 18px; }
.brand { display: flex; align-items: center; gap: 10px; font-weight: 650; font-size: 17px; letter-spacing: .2px; padding: 0 6px; }
nav { display: flex; flex-direction: column; gap: 2px; }
nav a { padding: 8px 10px; border-radius: 8px; color: var(--muted); text-decoration: none; font-weight: 500; }
nav a:hover { background: var(--bg); color: var(--text); }
nav a.active { background: var(--accent-soft); color: var(--accent); }
.machine { margin-top: auto; font-size: 12px; color: var(--muted); padding: 0 6px; word-break: break-all; }
.machine b { color: var(--text); font-weight: 600; }
.main { display: flex; flex-direction: column; min-width: 0; }
.top { display: flex; align-items: center; gap: 10px; padding: 12px 24px; border-bottom: 1px solid var(--line); background: var(--panel); position: sticky; top: 0; z-index: 2; }
.spacer { flex: 1; }
.view { padding: 24px; max-width: 1100px; width: 100%; }
h1 { font-size: 20px; margin: 0 0 4px; }
h2 { font-size: 15px; margin: 22px 0 8px; }
.sub { color: var(--muted); margin: 0 0 18px; }
.btn { font: inherit; padding: 7px 14px; border-radius: 8px; border: 1px solid var(--line); background: var(--panel); color: var(--text); cursor: pointer; font-weight: 500; }
.btn:hover { border-color: var(--muted); }
.btn:focus-visible, input:focus-visible, select:focus-visible, a:focus-visible, .row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.btn-primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
.btn-danger { background: var(--bad-bg); color: var(--bad); border-color: transparent; }
.btn:disabled { opacity: .5; cursor: default; }
.pill { display: inline-flex; align-items: center; gap: 8px; padding: 5px 12px; border-radius: 999px; font-weight: 600; font-size: 13px; }
.pill .dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; }
.pill-ok { background: var(--ok-bg); color: var(--ok); }
.pill-warn { background: var(--warn-bg); color: var(--warn); }
.pill-bad { background: var(--bad-bg); color: var(--bad); }
.pill-muted { background: var(--bg); color: var(--muted); }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); }
.table { width: 100%; border-collapse: collapse; }
.table th { text-align: left; font-weight: 600; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .5px; padding: 10px 16px; border-bottom: 1px solid var(--line); }
.table td { padding: 12px 16px; border-bottom: 1px solid var(--line); vertical-align: top; }
.table tr:last-child td { border-bottom: 0; }
.row { cursor: pointer; }
.row:hover td { background: color-mix(in srgb, var(--accent-soft) 45%, transparent); }
.repo-name { font-weight: 600; }
.path { font-family: var(--mono); font-size: 12px; color: var(--muted); word-break: break-all; }
.badge { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: 12px; font-weight: 600; margin: 1px 4px 1px 0; }
.b-synced { background: var(--ok-bg); color: var(--ok); }
.b-dirty, .b-behinddirty { background: var(--warn-bg); color: var(--warn); }
.b-ahead, .b-behind { background: var(--info-bg); color: var(--info); }
.b-diverged, .b-error { background: var(--bad-bg); color: var(--bad); }
.muted { color: var(--muted); }
.err { color: var(--bad); font-size: 13px; margin-top: 4px; }
.empty { padding: 40px 20px; text-align: center; color: var(--muted); }
.form { display: grid; gap: 14px; max-width: 520px; padding: 20px; }
label { display: grid; gap: 5px; font-weight: 600; font-size: 13px; }
label .hint { font-weight: 400; color: var(--muted); }
input[type=text], input[type=password], select { font: inherit; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--text); }
.check { display: flex; align-items: center; gap: 8px; font-weight: 500; }
.term { font-family: var(--mono); font-size: 12.5px; background: #0f1512; color: #cfe8d9; border-radius: var(--radius); padding: 14px 16px; white-space: pre-wrap; word-break: break-word; margin-top: 14px; max-height: 320px; overflow: auto; }
.term.fail { color: #ffb4ab; }
.kv { display: grid; grid-template-columns: 160px 1fr; gap: 8px 16px; padding: 16px 20px; }
.kv dt { color: var(--muted); }
.kv dd { margin: 0; word-break: break-all; }
.kind { font-family: var(--mono); font-size: 12px; padding: 1px 7px; border-radius: 6px; background: var(--bg); border: 1px solid var(--line); }
.k-error, .k-watch_error { color: var(--bad); border-color: var(--bad); }
.k-snapshot, .k-applied, .k-fast_forward, .k-materialized { color: var(--ok); }
.k-declined, .k-pause { color: var(--warn); }
.back { display: inline-block; margin-bottom: 12px; color: var(--muted); text-decoration: none; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.callout { border: 1px solid var(--bad); background: var(--bad-bg); border-radius: var(--radius); padding: 14px 16px; margin-top: 12px; }
.callout h3 { margin: 0 0 4px; font-size: 14px; color: var(--bad); }
.callout p { margin: 4px 0 10px; }
.toasts { position: fixed; right: 18px; bottom: 18px; display: grid; gap: 8px; z-index: 10; }
.toast { background: var(--text); color: var(--bg); padding: 10px 14px; border-radius: 10px; max-width: 360px; box-shadow: 0 6px 24px rgba(0,0,0,.25); }
.toast.bad { background: var(--bad); color: #fff; }
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; margin-bottom: 18px; }
.stat { padding: 14px 16px; }
.stat b { display: block; font-size: 24px; line-height: 1.1; }
.stat span { color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .5px; }
@media (max-width: 760px) {
.app { grid-template-columns: 1fr; }
.side { flex-direction: row; align-items: center; overflow-x: auto; padding: 10px; }
nav { flex-direction: row; } .machine { display: none; }
.view { padding: 16px; } .table th:nth-child(n+4), .table td:nth-child(n+4) { display: none; }
}
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# Phase 4 end-to-end check against a throwaway Forgejo on localhost:3300 (spikes/forgejo-up.sh):
# new repo -> config repo -> a fresh machine rebuilds the workspace with `grove bootstrap`.
set -euo pipefail
G=${GROVE_BIN:-target/debug/grove}
G=$(realpath "$G")
W=$(mktemp -d)
api() { curl -fs -u spike:spike-pass-123 "$@"; }
cleanup() {
for r in alpha beta gamma grove-config; do api -X DELETE "localhost:3300/api/v1/repos/spike/$r" >/dev/null || true; done
rm -rf "$W"
}
trap cleanup EXIT
TOK=$(api -H 'Content-Type: application/json' -X POST localhost:3300/api/v1/users/spike/tokens \
-d "{\"name\":\"e2e$RANDOM\",\"scopes\":[\"all\"]}" | sed -E 's/.*"sha1":"([^"]+)".*/\1/')
export GROVE_TOKEN_MAIN=$TOK
machine() { # name
export XDG_CONFIG_HOME=$W/$1/cfg XDG_STATE_HOME=$W/$1/state
"$G" init --machine "$1" --root "$W/$1/ws" --provider main --kind gitea \
--url http://localhost:3300 --group work --config-repo grove-config --force >/dev/null
}
machine pca
"$G" new work alpha
"$G" new work beta --public
"$G" config-repo-init
machine pcb
"$G" bootstrap
test -d "$W/pcb/ws/work/alpha/main" && test -d "$W/pcb/ws/work/beta/main"
echo "OK: fresh machine pcb has both repos"
# Encrypted .env channel: pca pushes, pcb (own key, after rekey on pca) pulls.
machine pca
"$G" new work gamma >/dev/null
"$G" secrets init
echo "API_KEY=s3cr3t" > "$W/pca/ws/work/gamma/main/.env"
machine pcb
"$G" bootstrap >/dev/null
"$G" secrets init
machine pca
"$G" secrets push "$W/pca/ws/work/gamma/main/.env"
"$G" secrets rekey
machine pcb
"$G" secrets pull
test "$(cat "$W/pcb/ws/work/gamma/main/.env")" = "API_KEY=s3cr3t"
test "$(stat -c %a "$W/pcb/ws/work/gamma/main/.env")" = "600"
echo "OK: .env travelled encrypted and landed with mode 600"