Merge pull request 'feat(gui): native Slint desktop app with tray; faster import, SSH protocol' (#7) from feat/native-gui into development

This commit is contained in:
dasemu committed 2026-11-16 18:18:54 +00:00
commit 09fbf79e87
49 files changed
+9112 -942

No files matched your search

+1
View File
@@ -0,0 +1 @@
ticks30s 14 rss 24344 -
+5 -5
View File
@@ -4,8 +4,7 @@
Linux tool that keeps chosen git repos continuously in sync across machines, including
uncommitted work, via snapshot refs (`refs/sync/<machine>/<branch>`) on a primary remote.
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.
`grove-gui` (native Slint desktop app with a ksni tray, `docs/phase7.md`). Phases 0-7 are implemented; the real two-PC run is still pending.
Do not start new work before the previous results are written to `docs/`.
## Commands
@@ -13,17 +12,17 @@ Do not start new work before the previous results are written to `docs/`.
- 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`
- GUI: `cargo run -p grove-gui` (`--hidden` starts in the tray; needs a Wayland/X11 session and a StatusNotifier host)
- 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` ... `phase6.md`, `DECISIONS.md`). Git is the storage layer; shell out to
See `docs/` (`phase0-spike.md` ... `phase7.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, clap+anyhow, notify+serde_json, ureq, keyring, age, tauri v2 (GUI shell), approved. Ask before adding more.
- Dependencies: serde+toml, clap+anyhow, notify+serde_json, ureq, keyring, age, slint (GUI, `winit` + software renderer) and ksni (tray), 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.
- The daemon manages only bare-layout repos at `root/<group>/<repo>` and pushes WIP snapshots only to private repos by default (`sync.snapshots`, per-group override); see `docs/phase6.md`.
@@ -40,3 +39,4 @@ Native Linux app (systemd user service). Never Docker for deployment.
## Gotchas
- Forgejo push mirrors to localhost need `migrations.ALLOW_LOCALNETWORKS` (test instances only).
- Push-mirror exclusion of `refs/sync/*` is verified on Forgejo 11 only, not yet on the real Gitea.
- Slint on Wayland: a window shown from an idle (hidden) event loop is not mapped until another event arrives; `show_window` schedules a one-shot redraw. Keep it.
Generated
+3896 -44
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", "crates/grove-providers", "crates/grove-bridge"]
members = ["crates/grove-core", "crates/grove", "crates/grove-daemon", "crates/grove-providers", "crates/grove-gui"]
[workspace.package]
edition = "2024"
+2
View File
@@ -8,3 +8,5 @@
- 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.
- Slint (winit/Wayland): `show()` from an idle event loop leaves the window unmapped until another event arrives; follow it with a one-shot `request_redraw` timer.
- Slint has no top-level `function`; use a `global`. A wrapped `Text` under-reports its preferred height inside layouts, so elide long log/error text instead of wrapping it.
File renamed without changes.

Before

Width:  |  Height:  |  Size: 209 B

After

Width:  |  Height:  |  Size: 209 B

+8
View File
@@ -0,0 +1,8 @@
[Desktop Entry]
Type=Application
Name=Grove
Comment=Grove tray icon (starts hidden)
Exec=grove-gui --hidden
Icon=grove
Terminal=false
X-GNOME-Autostart-enabled=true
+10
View File
@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=Grove
GenericName=Git sync
Comment=Keep your git repositories in sync across machines
Exec=grove-gui
Icon=grove
Terminal=false
Categories=Development;Utility;
StartupWMClass=grove
-12
View File
@@ -1,12 +0,0 @@
[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"
-155
View File
@@ -1,155 +0,0 @@
//! 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"),
}
}
+43
View File
@@ -37,9 +37,35 @@ pub enum ProviderKind {
Github,
}
/// How local git talks to a forge: HTTPS with the API token, or SSH with the user's keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
#[default]
Https,
Ssh,
}
fn is_https(p: &Protocol) -> bool {
*p == Protocol::Https
}
impl Protocol {
pub fn as_str(self) -> &'static str {
match self {
Protocol::Https => "https",
Protocol::Ssh => "ssh",
}
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Provider {
pub kind: ProviderKind,
/// Transport for clone/fetch/push (`https` by default). Mirrors are server-side and always
/// use HTTPS.
#[serde(default, skip_serializing_if = "is_https")]
pub protocol: Protocol,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
@@ -485,4 +511,21 @@ mirror_to = ["gitea"]
let t = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitlab\"\n";
assert!(matches!(Config::parse(t), Err(ConfigError::Parse(_))));
}
#[test]
fn provider_protocol_defaults_to_https_and_is_validated() {
let t = |p: &str| {
format!(
"[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"gitea\"\n{p}"
)
};
assert_eq!(
Config::parse(&t("")).unwrap().providers["p"].protocol,
Protocol::Https
);
let c = Config::parse(&t("protocol=\"ssh\"\n")).unwrap();
assert_eq!(c.providers["p"].protocol, Protocol::Ssh);
assert!(toml::to_string(&c).unwrap().contains("protocol = \"ssh\""));
assert!(Config::parse(&t("protocol=\"git\"\n")).is_err());
}
}
+121 -2
View File
@@ -5,6 +5,7 @@ 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)]
@@ -47,19 +48,104 @@ impl Registry {
/// Creates `<dir>/.bare` as a clone of `url` and a worktree per remote branch.
/// `envs` are extra git environment variables (credentials).
///
/// `dir` must not exist or be empty. If anything fails, what this call created is removed again
/// (the `.bare`, the worktree directories, `dir` itself when it created it); if that is not
/// possible a `.grove-stage` marker is left so the daemon reports the repo as stalled instead of
/// adopting a half-built one.
pub fn clone_bare_layout(
url: &str,
dir: &Path,
envs: &[(String, String)],
) -> Result<Vec<PathBuf>, GitError> {
clone_bare_layout_impl(url, dir, envs, false)
}
#[doc(hidden)]
pub fn clone_bare_layout_failing_after_clone(
url: &str,
dir: &Path,
envs: &[(String, String)],
) -> Result<Vec<PathBuf>, GitError> {
clone_bare_layout_impl(url, dir, envs, true)
}
fn clone_bare_layout_impl(
url: &str,
dir: &Path,
envs: &[(String, String)],
fail_after_clone: bool,
) -> Result<Vec<PathBuf>, GitError> {
let created_dir = !dir.exists();
let non_empty = !created_dir
&& fs::read_dir(dir)
.map_err(|e| GitError::Other(format!("{}: {e}", dir.display())))?
.next()
.is_some();
if non_empty {
return Err(GitError::Other(format!(
"{} already exists and is not empty",
dir.display()
)));
}
// Released last: until then the daemon ignores the half-built repo.
let _busy = crate::busy::BusyGuard::acquire(dir)?;
let busy = crate::busy::BusyGuard::acquire(dir)
.map_err(|e| GitError::Other(format!("{}: {e}", dir.display())))?;
let res = clone_steps(url, dir, envs, fail_after_clone);
if res.is_err() {
rollback_clone(dir);
}
drop(busy);
if res.is_err() && created_dir {
// Only while empty: `remove_dir` refuses anything else.
let _ = fs::remove_dir(dir);
}
res
}
/// Removes everything in `dir` except the busy marker (the caller guarantees `dir` was empty
/// before the clone started). On failure, leaves `.grove-stage` behind.
fn rollback_clone(dir: &Path) {
let mut failed = false;
if let Ok(rd) = fs::read_dir(dir) {
for e in rd.filter_map(Result::ok) {
if e.file_name() == crate::busy::BUSY {
continue;
}
let p = e.path();
let r = if e.file_type().is_ok_and(|t| t.is_dir()) {
fs::remove_dir_all(&p)
} else {
fs::remove_file(&p)
};
failed |= r.is_err();
}
} else {
failed = true;
}
if failed {
let _ = fs::write(
dir.join(".grove-stage"),
"a failed clone could not be cleaned up; remove this directory's contents by hand\n",
);
}
}
fn clone_steps(
url: &str,
dir: &Path,
envs: &[(String, String)],
fail_after_clone: bool,
) -> Result<Vec<PathBuf>, GitError> {
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()])?;
g.run(&["clone", "-q", "--bare", "--", url, &bare.to_string_lossy()])?;
if fail_after_clone {
return Err(GitError::Other("injected failure".into()));
}
Git::new(&bare).run(&["config", "core.bare", "true"])?;
ensure_fetch_refspec(&bare, "origin")?;
let mut f = Git::new(&bare);
@@ -124,3 +210,36 @@ pub fn push_initial(dir: &Path, envs: &[(String, String)]) -> Result<(), GitErro
g.run(&["push", "-q", "-u", "origin", "main"])?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn rollback_that_cannot_remove_everything_leaves_a_stage_marker() {
let d = std::env::temp_dir().join(format!("grove-rb-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
let locked = d.join(".bare/locked");
fs::create_dir_all(&locked).unwrap();
fs::write(locked.join("f"), "x").unwrap();
fs::write(d.join(crate::busy::BUSY), "1 1\n").unwrap();
fs::set_permissions(&locked, fs::Permissions::from_mode(0o500)).unwrap();
rollback_clone(&d);
assert!(d.join(".grove-stage").exists());
assert!(
d.join(crate::busy::BUSY).exists(),
"the marker is the guard's to remove"
);
fs::set_permissions(&locked, fs::Permissions::from_mode(0o700)).unwrap();
let _ = fs::remove_dir_all(&d);
// Everything removable: nothing left but the busy marker, no stage marker.
fs::create_dir_all(d.join(".bare")).unwrap();
fs::create_dir_all(d.join("main")).unwrap();
fs::write(d.join(crate::busy::BUSY), "1 1\n").unwrap();
rollback_clone(&d);
assert!(!d.join(".grove-stage").exists() && !d.join(".bare").exists());
let _ = fs::remove_dir_all(&d);
}
}
+55
View File
@@ -74,3 +74,58 @@ fn registry_roundtrip_and_upsert() {
assert_eq!(r.repos[0].group, "a");
assert_eq!(Registry::parse(&r.to_text()).unwrap(), r);
}
fn remote_with_main(base: &std::path::Path) -> String {
let remote = base.join("r.git");
Git::new(base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let a = base.join("A/g/proj");
init_bare_layout(&a, remote.to_str().unwrap()).unwrap();
push_initial(&a, &[]).unwrap();
remote.to_str().unwrap().to_string()
}
#[test]
fn clone_failing_after_the_clone_step_removes_what_it_created() {
let base = tmpdir("regfail");
let url = remote_with_main(&base);
// A directory the clone creates itself: gone afterwards, no marker left.
let fresh = base.join("B/g/fresh");
assert!(clone_bare_layout_failing_after_clone(&url, &fresh, &[]).is_err());
assert!(!fresh.exists());
// A pre-existing empty directory stays, empty and without markers.
let empty = base.join("B/g/empty");
fs::create_dir_all(&empty).unwrap();
assert!(clone_bare_layout_failing_after_clone(&url, &empty, &[]).is_err());
assert_eq!(fs::read_dir(&empty).unwrap().count(), 0);
// The retry works: nothing half-built is in the way.
clone_bare_layout(&url, &fresh, &[]).unwrap();
assert!(fresh.join(".bare").is_dir() && !fresh.join(".grove-busy").exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn clone_refuses_a_non_empty_directory_and_touches_nothing() {
let base = tmpdir("regkeep");
let url = remote_with_main(&base);
let plain = base.join("B/g/plain");
fs::create_dir_all(plain.join(".git")).unwrap();
fs::write(plain.join("keep.txt"), "mine").unwrap();
let e = clone_bare_layout(&url, &plain, &[]).unwrap_err();
assert!(e.to_string().contains("not empty"), "{e}");
assert_eq!(fs::read_to_string(plain.join("keep.txt")).unwrap(), "mine");
assert!(plain.join(".git").is_dir() && !plain.join(".bare").exists());
assert!(!plain.join(".grove-busy").exists());
fs::remove_dir_all(&base).unwrap();
}
+11
View File
@@ -86,6 +86,8 @@ pub struct Shared {
pub repos: BTreeMap<PathBuf, RepoStatus>,
/// Plain clones in configured groups: ignored until migrated with `grove add`.
pub not_migrated: Vec<PathBuf>,
/// Repos left alone because an interrupted `grove add`/clone left a marker behind.
pub stalled: Vec<PathBuf>,
}
pub enum Msg {
@@ -365,6 +367,7 @@ fn rescan(
{
let mut shared = ctx.shared.lock().unwrap();
shared.not_migrated = d.not_migrated;
shared.stalled = d.stalled.clone();
shared.repos.retain(|p, _| {
let keep = found.contains(p);
if !keep {
@@ -663,6 +666,13 @@ fn pass(
}
}
}
if !errors.is_empty() && !is_ready(repo) {
// The directory vanished (or stopped being a bare layout) mid-pass: the failure is a
// consequence of the removal, not a sync error. Rediscovery drops the repo and logs
// `repo_removed`.
status.phase = "idle";
return 0;
}
if offline {
// A snapshot-only pass during backoff changes neither the failure count nor the phase.
status.phase = if status.failures > 0 { "error" } else { "idle" };
@@ -723,6 +733,7 @@ fn purge_snapshots(ctx: &Ctx, repo: &Path, name: &str, cfg: &Config, st: &Settin
done.join(", ")
),
),
Err(_) if !is_ready(repo) => {} // removed mid-pass: rediscovery reports it
Err(e) => ctx.activity.log(
"error",
Some(name),
+2 -1
View File
@@ -169,7 +169,8 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
.collect();
ok(
json!({"machine": ctx.machine, "paused": s.paused, "now": now_secs(), "repos": repos,
"not_migrated": s.not_migrated.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()}),
"not_migrated": s.not_migrated.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(),
"stalled": s.stalled.iter().map(|p| p.display().to_string()).collect::<Vec<_>>()}),
)
}
"pause" | "resume" => {
+9 -1
View File
@@ -610,7 +610,11 @@ fn managed_repo_removed_after_start_disappears_without_crash() {
// Keep the first repo busy so a pass may be running when the other one vanishes.
fs::write(root.join("g/repo/main/busy.txt"), "x\n").unwrap();
fs::remove_dir_all(root.join("g/second")).unwrap();
// The daemon may create files in the repo while it is being deleted (ENOTEMPTY): retry.
wait_until("repo directory removed", 5, || {
let _ = fs::remove_dir_all(root.join("g/second"));
!root.join("g/second").exists()
});
wait_until("removed repo dropped", 10, || {
repo_paths(&sock) == vec![root.join("g/repo").display().to_string()]
});
@@ -712,6 +716,10 @@ fn stale_busy_marker_keeps_the_repo_out_and_warns_once() {
assert_eq!(events(&sock, "repo_stalled").len(), 1);
assert_eq!(repo_paths(&sock).len(), 1);
assert!(stale.join(".grove-busy").exists());
assert_eq!(
status(&sock)["stalled"],
json!([stale.display().to_string()])
);
d.shutdown();
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "grove-gui"
description = "Native desktop GUI for grove: tray icon, window, daemon IPC"
edition.workspace = true
version.workspace = true
license.workspace = true
[[bin]]
name = "grove-gui"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
grove-core = { version = "0.1.0", path = "../grove-core" }
grove-daemon = { version = "0.1.0", path = "../grove-daemon" }
# async-io instead of the default tokio: no second async runtime in a small tray app.
ksni = { version = "0.3.7", default-features = false, features = ["async-io", "blocking"] }
serde_json = "1.0.154"
slint = { version = "=1.18.1", default-features = false, features = ["std", "backend-winit", "renderer-software", "compat-1-2"] }
toml = "1.2.1"
[build-dependencies]
slint-build = "=1.18.1"
+5
View File
@@ -0,0 +1,5 @@
fn main() {
// `fluent` is a pure-Slint style: no Qt needed on the machine.
let config = slint_build::CompilerConfiguration::new().with_style("fluent".into());
slint_build::compile_with_config("ui/app.slint", config).expect("slint compile");
}
+55
View File
@@ -0,0 +1,55 @@
//! "Start at login": a copy of the autostart desktop file in `~/.config/autostart`.
use std::path::{Path, PathBuf};
const DESKTOP: &str = include_str!("../../../contrib/grove-autostart.desktop");
/// `$XDG_CONFIG_HOME` or `~/.config`.
pub fn config_home() -> Option<PathBuf> {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
}
pub fn file(config_home: &Path) -> PathBuf {
config_home.join("autostart").join("grove.desktop")
}
pub fn is_enabled(config_home: &Path) -> bool {
file(config_home).exists()
}
pub fn set(config_home: &Path, on: bool) -> std::io::Result<()> {
let f = file(config_home);
if on {
if let Some(d) = f.parent() {
std::fs::create_dir_all(d)?;
}
std::fs::write(&f, DESKTOP)
} else {
match std::fs::remove_file(&f) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggle_writes_and_removes_the_desktop_file() {
let d = std::env::temp_dir().join(format!("gg-auto-{}", std::process::id()));
assert!(!is_enabled(&d));
set(&d, true).unwrap();
assert!(is_enabled(&d));
let text = std::fs::read_to_string(file(&d)).unwrap();
assert!(text.contains("Exec=grove-gui --hidden"));
set(&d, false).unwrap();
assert!(!is_enabled(&d));
set(&d, false).unwrap(); // already off: fine
let _ = std::fs::remove_dir_all(&d);
}
}
@@ -1,9 +1,8 @@
//! Everything the GUI needs from the machine, behind three calls. The Tauri shell and the
//! localhost dev server both expose exactly these.
//! Everything the GUI needs from the machine: daemon IPC, allow-listed `grove` calls, config.
use serde_json::{Value, json};
use std::io::Write;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
/// `grove` subcommands the GUI may run. Everything else is refused.
@@ -12,6 +11,7 @@ const ALLOWED: &[&str] = &[
"login",
"new",
"import",
"add",
"config-repo-init",
"bootstrap",
"resolve",
@@ -45,6 +45,15 @@ impl Bridge {
if let Err(e) = validate(args) {
return json!({"ok": false, "output": format!("rejected: {e}")});
}
// `add` gets the canonical path the check validated, not the string it was given.
let mut checked: Vec<String> = args.to_vec();
if sub == "add" {
match self.check_migrate_args(args) {
Ok(canon) => checked[1] = canon.to_string_lossy().into_owned(),
Err(e) => return json!({"ok": false, "output": format!("rejected: {e}")}),
}
}
let args = &checked[..];
let mut cmd = Command::new(&self.grove_bin);
if let Some(c) = &self.config {
cmd.arg("--config").arg(c);
@@ -80,6 +89,28 @@ impl Bridge {
}
}
fn loaded_config(&self) -> Option<grove_core::config::Config> {
let p = self
.config
.clone()
.or_else(grove_core::config::Config::default_path)?;
grove_core::config::Config::load(&p).ok()
}
/// `add <path>` only for an existing directory directly under `<root>/<group>/`.
fn check_migrate_args(&self, args: &[String]) -> Result<PathBuf, String> {
let [_, path] = args else {
return Err("add takes exactly one path".into());
};
let cfg = self.loaded_config().ok_or("no readable configuration")?;
check_migrate_path(&cfg, Path::new(path))
}
/// Where `grove add` writes its safety backup.
pub fn backup_dir() -> Option<PathBuf> {
grove_core::config::Config::state_dir().map(|d| d.join("backups"))
}
/// `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)?;
@@ -91,7 +122,19 @@ impl Bridge {
/// 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"]),
"init" => (
&[],
&[
"--machine",
"--root",
"--provider",
"--kind",
"--protocol",
"--group",
"--config-repo",
"--url",
],
),
"new" => (&["--public"], &[]),
"resolve" => (&["--take-remote", "--keep-local"], &["--save-as"]),
_ => (&[], &[]),
@@ -124,6 +167,31 @@ pub fn validate(args: &[String]) -> Result<(), String> {
Ok(())
}
/// A clone the GUI may migrate: an existing directory (not a symlink) whose parent is one of the
/// configured group directories. Returns its canonical path.
pub fn check_migrate_path(
cfg: &grove_core::config::Config,
path: &Path,
) -> Result<PathBuf, String> {
let meta = std::fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
if !meta.is_dir() {
return Err(format!("{} is not a directory", path.display()));
}
let canon = path.canonicalize().map_err(|e| e.to_string())?;
let parent = canon.parent().ok_or("path has no parent directory")?;
let root = cfg.root_path();
let root = root.canonicalize().unwrap_or(root);
if cfg.groups.iter().any(|g| root.join(&g.name) == parent) {
Ok(canon)
} else {
Err(format!(
"{} is not directly inside a group directory under {}",
path.display(),
root.display()
))
}
}
fn grove_core_default_config() -> Option<PathBuf> {
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
@@ -149,6 +217,77 @@ mod tests {
assert!(v(&["secrets", "pull"]).is_ok());
}
#[test]
fn migrate_path_must_be_a_clone_directly_under_a_group() {
let base = std::env::temp_dir().join(format!("grove-mig-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("work/proj/sub")).unwrap();
std::fs::create_dir_all(base.join("other/proj")).unwrap();
std::fs::write(base.join("work/file"), "x").unwrap();
std::os::unix::fs::symlink(base.join("other/proj"), base.join("work/link")).unwrap();
let cfg = grove_core::config::Config::parse(&format!(
"[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n",
base.display()
))
.unwrap();
assert!(check_migrate_path(&cfg, &base.join("work/proj")).is_ok());
for bad in [
"work/proj/sub",
"other/proj",
"work/file",
"work/link",
"work/none",
"work",
"work/../other/proj",
] {
assert!(check_migrate_path(&cfg, &base.join(bad)).is_err(), "{bad}");
}
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn add_runs_only_for_valid_clone_paths() {
use std::os::unix::fs::PermissionsExt;
let base = std::env::temp_dir().join(format!("grove-add-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("work/proj")).unwrap();
std::fs::create_dir_all(base.join("elsewhere")).unwrap();
let cfg = base.join("config.toml");
std::fs::write(&cfg, format!(
"[machine]\nname=\"m\"\n[root]\npath=\"{}\"\n[providers.p]\nkind=\"gitea\"\n[[groups]]\nname=\"work\"\nprimary=\"p\"\n",
base.display()
)).unwrap();
// A stand-in `grove` that reports what it was asked to do.
let fake = base.join("grove");
std::fs::write(&fake, "#!/bin/sh\necho \"migrated: $4/wt\"\n").unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let b = Bridge {
grove_bin: fake,
config: Some(cfg),
socket: "/nonexistent".into(),
};
let ok = b.cli(
&["add".into(), base.join("work/proj").display().to_string()],
"",
);
assert_eq!(ok["ok"], true, "{ok}");
assert!(ok["output"].as_str().unwrap().starts_with("migrated:"));
// A path with `..`/symlink parts reaches `grove add` in canonical form.
let sneaky = format!("{}/work/../work/proj", base.display());
let canon = base.join("work/proj").canonicalize().unwrap();
let r = b.cli(&["add".into(), sneaky], "");
assert_eq!(r["output"], format!("migrated: {}/wt", canon.display()));
let bad = b.cli(
&["add".into(), base.join("elsewhere").display().to_string()],
"",
);
assert_eq!(bad["ok"], false);
assert!(bad["output"].as_str().unwrap().contains("rejected"));
let flag = b.cli(&["add".into(), "--backup-dir".into(), "/x".into()], "");
assert_eq!(flag["ok"], false);
let _ = std::fs::remove_dir_all(&base);
}
fn bridge() -> Bridge {
Bridge {
grove_bin: "/nonexistent/grove".into(),
+187
View File
@@ -0,0 +1,187 @@
//! Single instance: the first process listens on a Unix socket; a second launch asks it to show
//! its window and exits.
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::{DirBuilderExt, MetadataExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `$XDG_RUNTIME_DIR/grove/gui.sock` (same private directory as the daemon socket); without a
/// runtime dir, a private per-user directory under the temp dir.
pub fn default_socket_path() -> PathBuf {
match std::env::var_os("XDG_RUNTIME_DIR") {
Some(base) => PathBuf::from(base).join("grove").join("gui.sock"),
None => std::env::temp_dir()
.join(format!("grove-gui-{}", own_uid()))
.join("gui.sock"),
}
}
fn own_uid() -> u32 {
std::fs::metadata("/proc/self")
.map(|m| m.uid())
.unwrap_or(0)
}
/// Creates `dir` with mode 0700, or checks that an existing one is ours and not accessible to
/// others (a pre-created directory in a shared /tmp must not be trusted).
pub fn ensure_private_dir(dir: &Path) -> std::io::Result<()> {
if let Some(parent) = dir.parent() {
std::fs::create_dir_all(parent)?;
}
match std::fs::DirBuilder::new().mode(0o700).create(dir) {
Ok(()) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
let m = std::fs::symlink_metadata(dir)?;
if !m.is_dir() || m.uid() != own_uid() || m.mode() & 0o077 != 0 {
return Err(std::io::Error::other(format!(
"{} is not a private directory owned by you",
dir.display()
)));
}
Ok(())
}
pub enum Role {
/// Another instance is running and has been told to show (or ignore, when `show` is false).
Secondary,
/// This process owns the socket.
Primary(UnixListener),
}
/// Tries to hand over to a running instance; otherwise becomes the primary one.
pub fn acquire(path: &Path, show: bool) -> std::io::Result<Role> {
acquire_with(path, show, Duration::from_secs(2))
}
pub fn acquire_with(path: &Path, show: bool, timeout: Duration) -> std::io::Result<Role> {
if let Some(dir) = path.parent() {
ensure_private_dir(dir)?;
}
for _ in 0..3 {
match notify(path, if show { "show" } else { "ping" }, timeout) {
Ok(()) => return Ok(Role::Secondary),
// Nobody listens: a stale socket file from a crash is replaced. A reset
// (seen under load on a socket whose listener is gone) means the same.
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::ConnectionRefused
| std::io::ErrorKind::ConnectionReset
| std::io::ErrorKind::NotFound
) =>
{
if e.kind() != std::io::ErrorKind::NotFound {
let _ = std::fs::remove_file(path);
}
}
// A live instance that does not answer in time is never evicted.
Err(e) => return Err(e),
}
match UnixListener::bind(path) {
Ok(l) => return Ok(Role::Primary(l)),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => continue,
Err(e) => return Err(e),
}
}
Err(std::io::Error::other("cannot acquire the instance socket"))
}
fn notify(path: &Path, msg: &str, timeout: Duration) -> std::io::Result<()> {
let mut c = UnixStream::connect(path)?;
c.set_read_timeout(Some(timeout))?;
writeln!(c, "{msg}")?;
let mut line = String::new();
BufReader::new(c).read_line(&mut line)?;
if line.trim() == "ok" {
Ok(())
} else {
Err(std::io::Error::other("unexpected answer"))
}
}
/// Serves the primary socket forever; calls `on_show` for every `show` request.
pub fn serve(listener: UnixListener, on_show: impl Fn() + Send + 'static) {
for conn in listener.incoming().flatten() {
let _ = conn.set_read_timeout(Some(Duration::from_secs(2)));
let mut line = String::new();
let mut conn = BufReader::new(conn);
if conn.read_line(&mut line).is_err() {
continue;
}
if line.trim() == "show" {
on_show();
}
let _ = writeln!(conn.get_mut(), "ok");
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
use std::sync::mpsc;
fn tmp_sock(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("gg-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d); // leftovers of an earlier run with the same pid
std::fs::create_dir_all(&d).unwrap();
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)).unwrap();
d.join("gui.sock")
}
#[test]
fn second_launch_asks_first_to_show() {
let p = tmp_sock("show");
let Role::Primary(l) = acquire(&p, true).unwrap() else {
panic!("first must be primary");
};
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || serve(l, move || tx.send(()).unwrap()));
assert!(matches!(acquire(&p, true).unwrap(), Role::Secondary));
rx.recv_timeout(Duration::from_secs(2))
.expect("show callback");
// A hidden (autostart) relaunch does not pop the window.
assert!(matches!(acquire(&p, false).unwrap(), Role::Secondary));
assert!(rx.recv_timeout(Duration::from_millis(200)).is_err());
}
#[test]
fn unresponsive_instance_is_not_evicted() {
let p = tmp_sock("busy");
let l = UnixListener::bind(&p).unwrap();
// Accepts but never answers (a primary stuck in startup).
let t = std::thread::spawn(move || {
let c = l.accept().unwrap();
std::thread::sleep(Duration::from_millis(600));
drop(c);
});
let r = acquire_with(&p, true, Duration::from_millis(200));
assert!(r.is_err(), "must not become primary");
assert!(p.exists(), "socket file must stay");
t.join().unwrap();
}
#[test]
fn private_dir_is_enforced() {
let base = std::env::temp_dir().join(format!("gg-priv-{}", std::process::id()));
let d = base.join("x");
ensure_private_dir(&d).unwrap();
assert_eq!(std::fs::metadata(&d).unwrap().mode() & 0o777, 0o700);
ensure_private_dir(&d).unwrap(); // idempotent
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(ensure_private_dir(&d).is_err());
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn stale_socket_is_replaced() {
let p = tmp_sock("stale");
drop(UnixListener::bind(&p).unwrap()); // leaves the socket file behind
assert!(p.exists());
assert!(matches!(acquire(&p, true).unwrap(), Role::Primary(_)));
}
}
+75
View File
@@ -0,0 +1,75 @@
//! A small log file (`<state dir>/grove-gui.log`) for things that would otherwise vanish when the
//! GUI runs from autostart with stdout/stderr closed: panics, fatal errors and why it exited.
use std::io::Write;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
static PATH: OnceLock<std::path::PathBuf> = OnceLock::new();
/// Set when the process leaves on purpose (tray "Quit", window closed without a tray).
pub static EXPECTED_EXIT: AtomicBool = AtomicBool::new(false);
const MAX_BYTES: u64 = 256 * 1024;
/// Opens the log (truncating a file past 256 KiB) and installs the panic hook.
pub fn init() {
let Some(dir) = grove_core::config::Config::state_dir() else {
return;
};
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("grove-gui.log");
if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_BYTES) {
let _ = std::fs::rename(&path, dir.join("grove-gui.log.old"));
}
let _ = PATH.set(path);
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let t = std::thread::current();
let bt = std::backtrace::Backtrace::force_capture();
line(&format!(
"PANIC in thread {:?}: {info}\n{bt}",
t.name().unwrap_or("<unnamed>")
));
default(info);
}));
}
/// Appends one timestamped line; never fails and never panics.
pub fn line(msg: &str) {
let Some(p) = PATH.get() else { return };
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(p)
{
let _ = writeln!(f, "{} [{}] {msg}", stamp(), std::process::id());
}
}
pub fn expected_exit() {
EXPECTED_EXIT.store(true, Ordering::SeqCst);
}
/// `YYYY-MM-DD HH:MM:SSZ` (UTC) from the system clock.
fn stamp() -> String {
let s = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let (days, rem) = (s / 86400, s % 86400);
// Civil-from-days (Howard Hinnant).
let z = days as i64 + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
File diff suppressed because it is too large. Load diff
+504
View File
@@ -0,0 +1,504 @@
//! UI-independent logic: daemon status -> aggregate state, formatting, CLI output parsing.
use serde_json::Value;
use std::collections::HashMap;
/// What the tray icon and the status pill show.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum TrayState {
Ok,
Syncing,
Attention,
Paused,
#[default]
Offline,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Aggregate {
pub state: TrayState,
pub text: String,
pub repos: usize,
pub worktrees: usize,
pub attention: usize,
}
/// `error: <detail>` states collapse to `error`.
pub fn state_name(s: &str) -> &str {
if s.starts_with("error") { "error" } else { s }
}
pub fn state_label(s: &str) -> &'static str {
match state_name(s) {
"synced" => "Synced",
"dirty" => "Editing",
"ahead" => "Ahead",
"behind" => "Behind",
"behinddirty" => "Behind + editing",
"diverged" => "Diverged",
"error" => "Error",
_ => "Unknown",
}
}
/// What the next sync pass will do for a worktree in this state.
pub fn state_plan(s: &str) -> &'static str {
match state_name(s) {
"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.",
_ => "",
}
}
fn str_of<'a>(v: &'a Value, key: &str) -> &'a str {
v.get(key).and_then(Value::as_str).unwrap_or("")
}
/// Summarises the `status` answer of the daemon. `None` means the daemon is unreachable.
pub fn aggregate(status: Option<&Value>) -> Aggregate {
let Some(s) = status else {
return Aggregate {
state: TrayState::Offline,
text: "Daemon offline".into(),
..Default::default()
};
};
let empty = Vec::new();
let repos = s.get("repos").and_then(Value::as_array).unwrap_or(&empty);
let (mut attention, mut dirty, mut total) = (0, 0, 0);
for r in repos {
let wts = r
.get("worktrees")
.and_then(Value::as_array)
.unwrap_or(&empty);
let has_err = wts
.iter()
.any(|w| state_name(str_of(w, "state")) == "error");
if r.get("last_error").is_some_and(|e| !e.is_null()) && !has_err {
attention += 1;
}
for w in wts {
total += 1;
match state_name(str_of(w, "state")) {
// These need the user: nothing automatic will fix them.
"diverged" | "error" | "ahead" | "behinddirty" => attention += 1,
"synced" => {}
_ => dirty += 1,
}
}
}
let (state, text) = if s.get("paused").and_then(Value::as_bool) == Some(true) {
(TrayState::Paused, "Paused".to_string())
} else if attention > 0 {
let verb = if attention == 1 { "needs" } else { "need" };
(
TrayState::Attention,
format!("{attention} {verb} attention"),
)
} else if dirty > 0 {
(TrayState::Syncing, format!("{dirty} syncing"))
} else {
(TrayState::Ok, "All synced".to_string())
};
Aggregate {
state,
text,
repos: repos.len(),
worktrees: total,
attention,
}
}
/// Output of a CLI run shown under a worktree. It is dropped when the worktree's state changes
/// after the first render that followed the run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OutRec {
pub ok: bool,
pub text: String,
pub baseline: Option<String>,
}
/// `states`: worktree path -> current state key.
pub fn reconcile_outputs(outputs: &mut HashMap<String, OutRec>, states: &HashMap<String, String>) {
outputs.retain(|path, rec| match states.get(path) {
None => true,
Some(now) => match &rec.baseline {
None => {
rec.baseline = Some(now.clone());
true
}
Some(b) => b == now,
},
});
}
/// Colour key of an activity event kind.
pub fn log_tone(kind: &str) -> &'static str {
match kind {
"error" | "watch_error" => "error",
"state" | "snapshots_withheld" | "snapshots_purged" | "declined" | "repo_stalled" => "warn",
_ => "ok",
}
}
/// Last two path components, e.g. `work/api`.
pub fn short(path: &str) -> String {
let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
parts[parts.len().saturating_sub(2)..].join("/")
}
pub fn ago(ts: u64, now: u64) -> String {
if ts == 0 {
return "never".into();
}
let d = now.saturating_sub(ts);
match d {
0..=4 => "just now".into(),
5..=59 => format!("{d}s ago"),
60..=3599 => format!("{} min ago", (d + 30) / 60),
3600..=86399 => format!("{} h ago", (d + 1800) / 3600),
_ => format!("{} d ago", (d + 43200) / 86400),
}
}
/// `HH:MM:SS` (UTC offset applied by the caller) for the activity log.
pub fn clock(ts: u64, utc_offset_s: i64) -> String {
let t = (ts as i64 + utc_offset_s).rem_euclid(86400);
format!("{:02}:{:02}:{:02}", t / 3600, (t / 60) % 60, t % 60)
}
/// Repository names from `grove import <group>` listing lines: ` owner/name on <provider>[ (private)]`.
pub fn parse_import_listing(output: &str) -> Vec<String> {
let mut names = Vec::new();
for line in output.lines() {
if !line.starts_with(char::is_whitespace) {
continue;
}
let mut words = line.split_whitespace();
let Some(first) = words.next() else { continue };
let Some((_, name)) = first.split_once('/') else {
continue;
};
let rest: Vec<&str> = words.collect();
let ok = matches!(
rest.as_slice(),
[] | ["(private)"] | ["on", _] | ["on", _, "(private)"]
);
if ok && !name.is_empty() && !name.contains('/') {
names.push(name.to_string());
}
}
names
}
/// Repository names of the `FAILED <name>: <reason>` lines `grove import` prints per failed clone.
pub fn parse_import_failures(output: &str) -> Vec<String> {
output
.lines()
.filter_map(|l| l.strip_prefix("FAILED "))
.filter_map(|l| l.split_once(':').map(|(n, _)| n.trim().to_string()))
.collect()
}
fn names(v: Option<&Value>) -> Vec<String> {
v.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect()
})
.unwrap_or_default()
}
/// One line per group: routes (private + public), snapshot policy, owners and layout.
pub fn group_summary(g: &Value) -> String {
let mut s = format!("primary {}", str_of(g, "primary"));
let mirrors = names(g.get("mirror_to"));
if !mirrors.is_empty() {
s += &format!(" · mirrors: {}", mirrors.join(", "));
}
if let Some(p) = g.get("public").filter(|p| p.is_object()) {
s += &format!(" · public: {}", str_of(p, "primary"));
let pm = names(p.get("mirror_to"));
if !pm.is_empty() {
s += &format!(" → {}", pm.join(", "));
}
}
if let Some(p) = g.get("snapshots").and_then(Value::as_str) {
s += &format!(" · snapshots: {p}");
}
if let Some(o) = g
.get("owners")
.and_then(Value::as_object)
.filter(|o| !o.is_empty())
{
let list: Vec<String> = o
.iter()
.map(|(k, v)| format!("{k}={}", v.as_str().unwrap_or("")))
.collect();
s += &format!(" · owners: {}", list.join(", "));
}
let layout = g
.get("layout")
.and_then(Value::as_str)
.unwrap_or("bare-worktrees");
format!("{s} · {layout}")
}
pub type Section = (String, Vec<(String, String)>);
/// The settings view: sections of key/value rows, from `config.toml` as JSON.
pub fn settings_sections(cfg: &Value) -> Vec<Section> {
let sync = cfg.get("sync");
let num = |k: &str, d: u64| {
sync.and_then(|s| s.get(k))
.and_then(Value::as_u64)
.unwrap_or(d)
};
let machine = vec![
(
"Name".to_string(),
str_of(&cfg["machine"], "name").to_string(),
),
(
"Workspace root".into(),
str_of(&cfg["root"], "path").to_string(),
),
(
"Fetch interval".into(),
format!("{} s", num("fetch_interval_s", 60)),
),
(
"Largest synced file".into(),
format!("{} MiB", num("max_file_mb", 50)),
),
(
"Snapshots (default)".into(),
sync.and_then(|s| s.get("snapshots"))
.and_then(Value::as_str)
.unwrap_or("private-only")
.to_string(),
),
];
let providers = cfg
.get("providers")
.and_then(Value::as_object)
.map(|m| {
m.iter()
.map(|(id, p)| {
let url = str_of(p, "url");
let url = if url.is_empty() {
String::new()
} else {
format!(" · {url}")
};
// `protocol` is how git talks to the forge; https when the key is absent.
let proto = match str_of(p, "protocol") {
"" => "https",
p => p,
};
(id.clone(), format!("{} · {proto}{url}", str_of(p, "kind")))
})
.collect()
})
.unwrap_or_default();
let groups = cfg
.get("groups")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|g| (str_of(g, "name").to_string(), group_summary(g)))
.collect()
})
.unwrap_or_default();
let crepo = match cfg.get("config_repo").filter(|c| c.is_object()) {
Some(c) => format!("{} on {}", str_of(c, "name"), str_of(c, "provider")),
None => "not configured".into(),
};
vec![
("This machine".into(), machine),
("Providers".into(), providers),
("Groups".into(), groups),
(
"Config repository".into(),
vec![("Repository".into(), crepo)],
),
]
}
/// Group name from a combo entry (`name → primary`).
pub fn group_name(entry: &str) -> &str {
entry.split(" → ").next().unwrap_or(entry)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn status(paused: bool, states: &[&str], last_error: Option<&str>) -> Value {
let wts: Vec<Value> = states
.iter()
.map(|s| json!({"branch": "main", "state": s, "path": "/w/a/main"}))
.collect();
json!({"machine": "m", "paused": paused, "now": 100,
"repos": [{"path": "/w/a", "phase": "idle", "last_sync": 90,
"last_error": last_error, "worktrees": wts}]})
}
#[test]
fn offline_when_no_status() {
let a = aggregate(None);
assert_eq!(a.state, TrayState::Offline);
assert_eq!(a.text, "Daemon offline");
}
#[test]
fn state_to_tray_mapping() {
let agg = |s: Value| aggregate(Some(&s));
assert_eq!(agg(status(false, &["synced"], None)).state, TrayState::Ok);
assert_eq!(
agg(json!({"paused": false, "repos": []})).state,
TrayState::Ok
);
assert_eq!(
agg(status(false, &["synced", "dirty"], None)).state,
TrayState::Syncing
);
assert_eq!(
agg(status(false, &["behind"], None)).state,
TrayState::Syncing
);
assert_eq!(
agg(status(false, &["diverged"], None)).state,
TrayState::Attention
);
assert_eq!(
agg(status(false, &["error: boom"], None)).state,
TrayState::Attention
);
assert_eq!(
agg(status(false, &["synced"], Some("fetch failed"))).state,
TrayState::Attention
);
// Paused wins over everything else.
assert_eq!(
agg(status(true, &["diverged"], None)).state,
TrayState::Paused
);
}
#[test]
fn attention_counts_and_text() {
let a = aggregate(Some(&status(
false,
&["diverged", "error: x", "dirty"],
None,
)));
assert_eq!((a.attention, a.worktrees, a.repos), (2, 3, 1));
assert_eq!(a.text, "2 need attention");
let a = aggregate(Some(&status(false, &["diverged"], None)));
assert_eq!(a.text, "1 needs attention");
// An error on the repo that no worktree shows counts once.
let a = aggregate(Some(&status(false, &["error: x"], Some("x"))));
assert_eq!(a.attention, 1);
}
#[test]
fn import_listing_parses_every_line_shape() {
let out = "remote repositories in group work not on this machine:\n me/alpha on main\n me/beta on main (private)\n me/gamma\n me/delta (private)\nnot indented/line on x\n nonsense line here\n";
assert_eq!(
parse_import_listing(out),
["alpha", "beta", "gamma", "delta"]
);
assert!(parse_import_listing("nothing to import").is_empty());
}
#[test]
fn failed_imports_are_listed() {
let out = "imported a -> /x/a\nFAILED b: git clone failed: boom\nFAILED c: nope";
assert_eq!(parse_import_failures(out), ["b", "c"]);
assert!(parse_import_failures("imported a").is_empty());
}
#[test]
fn outputs_are_dropped_when_the_state_changes() {
let rec = |t: &str| OutRec {
ok: true,
text: t.into(),
baseline: None,
};
let mut o = HashMap::from([
("/a".to_string(), rec("x")),
("/gone".to_string(), rec("y")),
]);
let st = |s: &str| HashMap::from([("/a".to_string(), s.to_string())]);
reconcile_outputs(&mut o, &st("diverged")); // first render sets the baseline
assert_eq!(o["/a"].baseline.as_deref(), Some("diverged"));
reconcile_outputs(&mut o, &st("diverged"));
assert!(o.contains_key("/a"));
reconcile_outputs(&mut o, &st("synced")); // state changed
assert!(!o.contains_key("/a"));
assert!(o.contains_key("/gone"), "unknown paths are kept");
}
#[test]
fn log_tones() {
assert_eq!(log_tone("snapshots_withheld"), "warn");
assert_eq!(log_tone("snapshots_purged"), "warn");
assert_eq!(log_tone("snapshots_enabled"), "ok");
assert_eq!(log_tone("watch_error"), "error");
assert_eq!(log_tone("repo_stalled"), "warn");
assert_eq!(log_tone("repo_added"), "ok");
assert_eq!(log_tone("repo_removed"), "ok");
}
#[test]
fn formatting() {
assert_eq!(short("/home/u/Workspace/work/api"), "work/api");
assert_eq!(short("api"), "api");
assert_eq!(ago(0, 100), "never");
assert_eq!(ago(98, 100), "just now");
assert_eq!(ago(70, 100), "30s ago");
assert_eq!(ago(100, 400), "5 min ago");
assert_eq!(ago(1, 7201), "2 h ago");
assert_eq!(clock(3661, 0), "01:01:01");
assert_eq!(clock(3600 * 23, 7200), "01:00:00");
assert_eq!(state_label("error: x"), "Error");
assert!(state_plan("diverged").contains("resolve"));
}
#[test]
fn settings_show_public_route_and_owners() {
let cfg = json!({
"machine": {"name": "pca"}, "root": {"path": "/w"},
"providers": {"gitea": {"kind": "gitea", "protocol": "ssh", "url": "https://g.example"}, "gh": {"kind": "github"}},
"groups": [{"name": "work", "primary": "gitea", "mirror_to": ["gh"],
"owners": {"gitea": "Org", "gh": "org-gh"},
"snapshots": "none",
"public": {"primary": "gh", "mirror_to": ["gitea"]}}],
"config_repo": {"name": "grove-config", "provider": "gitea"}
});
let s = settings_sections(&cfg);
assert_eq!(s[0].1[0], ("Name".into(), "pca".into()));
assert_eq!(s[0].1[2].1, "60 s");
assert_eq!(
s[0].1[4],
("Snapshots (default)".into(), "private-only".into())
);
// Providers come out sorted by id.
assert_eq!(s[1].1[0].1, "github · https");
assert_eq!(s[1].1[1].1, "gitea · ssh · https://g.example");
assert_eq!(
s[2].1[0].1,
"primary gitea · mirrors: gh · public: gh → gitea · snapshots: none · owners: gh=org-gh, gitea=Org · bare-worktrees"
);
assert_eq!(s[3].1[0].1, "grove-config on gitea");
assert_eq!(group_name("work → gitea"), "work");
}
}
+243
View File
@@ -0,0 +1,243 @@
//! StatusNotifierItem tray (ksni). Icons are drawn in code, one per state, so no image decoder
//! is needed.
use crate::model::{Aggregate, TrayState};
use ksni::blocking::{Handle, TrayMethods};
use ksni::menu::StandardItem;
use ksni::{Icon, MenuItem, Status, ToolTip};
use std::sync::{Arc, OnceLock};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
Show,
SyncNow,
TogglePause,
Quit,
}
pub struct GroveTray {
agg: Aggregate,
on_action: Arc<dyn Fn(Action) + Send + Sync>,
}
pub type TrayHandle = Handle<GroveTray>;
/// Starts the tray service. Fails when there is no D-Bus session.
pub fn spawn(on_action: Arc<dyn Fn(Action) + Send + Sync>) -> Result<TrayHandle, ksni::Error> {
GroveTray {
agg: Aggregate::default(),
on_action,
}
.spawn()
}
/// Returns false when the tray service has ended (D-Bus connection lost).
pub fn set_state(handle: &TrayHandle, agg: &Aggregate) -> bool {
let agg = agg.clone();
handle
.update(move |t| {
if t.agg != agg {
t.agg = agg;
}
})
.is_some()
}
impl ksni::Tray for GroveTray {
fn id(&self) -> String {
"grove".into()
}
fn title(&self) -> String {
"Grove".into()
}
fn status(&self) -> Status {
match self.agg.state {
TrayState::Attention => Status::NeedsAttention,
_ => Status::Active,
}
}
fn icon_pixmap(&self) -> Vec<Icon> {
icons(self.agg.state)
}
fn attention_icon_pixmap(&self) -> Vec<Icon> {
icons(TrayState::Attention)
}
fn tool_tip(&self) -> ToolTip {
ToolTip {
title: format!("Grove: {}", self.agg.text),
..Default::default()
}
}
fn activate(&mut self, _x: i32, _y: i32) {
(self.on_action)(Action::Show);
}
fn menu(&self) -> Vec<MenuItem<Self>> {
let online = self.agg.state != TrayState::Offline;
let paused = self.agg.state == TrayState::Paused;
let item = |label: &str, enabled: bool, a: Action| {
StandardItem {
label: label.into(),
enabled,
activate: Box::new(move |t: &mut Self| (t.on_action)(a)),
..Default::default()
}
.into()
};
vec![
StandardItem {
label: self.agg.text.clone(),
enabled: false,
..Default::default()
}
.into(),
MenuItem::Separator,
item("Open Grove", true, Action::Show),
item("Sync now", online && !paused, Action::SyncNow),
item(
if paused { "Resume sync" } else { "Pause sync" },
online,
Action::TogglePause,
),
MenuItem::Separator,
item("Quit", true, Action::Quit),
]
}
}
// ---- icon drawing ----------------------------------------------------------------------------
fn colour(s: TrayState) -> [u8; 3] {
match s {
TrayState::Ok => [0x2e, 0x9e, 0x5b],
TrayState::Syncing => [0x2f, 0x7d, 0xd1],
TrayState::Attention => [0xd9, 0x48, 0x3b],
TrayState::Paused => [0x8a, 0x8f, 0x98],
TrayState::Offline => [0x4a, 0x4f, 0x58],
}
}
fn seg(px: f32, py: f32, a: (f32, f32), b: (f32, f32), half: f32) -> bool {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let t = (((px - a.0) * dx + (py - a.1) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0);
let (cx, cy) = (a.0 + t * dx, a.1 + t * dy);
(px - cx).hypot(py - cy) <= half
}
/// Glyph in a 32x32 box, white on the coloured disc.
fn glyph(s: TrayState, x: f32, y: f32) -> bool {
match s {
TrayState::Ok => {
seg(x, y, (9.0, 16.5), (14.0, 21.5), 1.6) || seg(x, y, (14.0, 21.5), (23.0, 11.0), 1.6)
}
TrayState::Syncing => {
// Ring with a gap at the upper right, like a refresh symbol.
let (dx, dy) = (x - 16.0, y - 16.0);
let r = dx.hypot(dy);
let gap = dx > 0.0 && dy < 0.0 && dx.abs() * 0.6 < dy.abs() * 1.6;
(5.0..=8.0).contains(&r) && !gap
}
TrayState::Attention => {
(14.4..=17.6).contains(&x) && (8.0..=18.0).contains(&y)
|| (x - 16.0).hypot(y - 22.5) <= 2.0
}
TrayState::Paused => {
(10.0..=14.0).contains(&x) && (9.0..=23.0).contains(&y)
|| (18.0..=22.0).contains(&x) && (9.0..=23.0).contains(&y)
}
TrayState::Offline => {
seg(x, y, (10.0, 10.0), (22.0, 22.0), 1.5) || seg(x, y, (22.0, 10.0), (10.0, 22.0), 1.5)
}
}
}
/// ARGB32 (network byte order) pixmap of `size` x `size`, 3x3 supersampled.
pub fn render(s: TrayState, size: u32) -> Icon {
let [r, g, b] = colour(s);
let scale = 32.0 / size as f32;
let mut data = Vec::with_capacity((size * size * 4) as usize);
for py in 0..size {
for px in 0..size {
let (mut disc, mut mark) = (0u32, 0u32);
for sy in 0..3 {
for sx in 0..3 {
let x = (px as f32 + (sx as f32 + 0.5) / 3.0) * scale;
let y = (py as f32 + (sy as f32 + 0.5) / 3.0) * scale;
if (x - 16.0).hypot(y - 16.0) <= 15.0 {
disc += 1;
if glyph(s, x, y) {
mark += 1;
}
}
}
}
let a = (disc * 255 / 9) as u8;
// Blend the white glyph over the disc colour by its share of the covered samples.
let w = (mark * 255).checked_div(disc).unwrap_or(0);
let mix = |c: u8| ((c as u32 * (255 - w) + 255 * w) / 255) as u8;
data.extend_from_slice(&[a, mix(r), mix(g), mix(b)]);
}
}
Icon {
width: size as i32,
height: size as i32,
data,
}
}
/// Rendered once per state: the tray asks for the pixmaps on every property read.
fn icons(s: TrayState) -> Vec<Icon> {
static CACHE: [OnceLock<Vec<Icon>>; 5] = [const { OnceLock::new() }; 5];
CACHE[s as usize]
.get_or_init(|| vec![render(s, 22), render(s, 32), render(s, 64)])
.clone()
}
#[cfg(test)]
mod tests {
use super::*;
const ALL: [TrayState; 5] = [
TrayState::Ok,
TrayState::Syncing,
TrayState::Attention,
TrayState::Paused,
TrayState::Offline,
];
#[test]
fn every_state_has_a_distinct_non_empty_icon() {
let imgs: Vec<_> = ALL.iter().map(|s| render(*s, 32)).collect();
for (i, a) in imgs.iter().enumerate() {
assert_eq!(a.data.len(), 32 * 32 * 4);
assert!(a.data.chunks(4).any(|p| p[0] == 255), "opaque pixels");
assert_eq!(a.data[0], 0, "corner is transparent");
for b in &imgs[i + 1..] {
assert_ne!(a.data, b.data);
}
}
}
#[test]
fn glyph_is_drawn_in_white() {
let ok = render(TrayState::Ok, 32);
let white = ok
.data
.chunks(4)
.filter(|p| p[0] == 255 && p[1] == 255 && p[2] == 255)
.count();
assert!(white > 20, "{white}");
}
#[test]
fn pixmap_sizes() {
let sizes: Vec<_> = icons(TrayState::Ok).iter().map(|i| i.width).collect();
assert_eq!(sizes, [22, 32, 64]);
}
}
File diff suppressed because it is too large. Load diff
+31 -12
View File
@@ -30,6 +30,7 @@ fn repo(v: &Value) -> RemoteRepo {
name: s("name"),
private: v["private"].as_bool().unwrap_or(false),
clone_url: s("clone_url"),
ssh_url: s("ssh_url"),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
@@ -67,19 +68,37 @@ impl Provider for Gitea {
}
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(self
.http
.pages("/user/repos", 50, "limit", false)?
.iter()
.map(repo)
.collect())
}
fn list_owner_repos(&self, owner: &str, login: &str) -> Result<Vec<RemoteRepo>> {
let path = if owner.eq_ignore_ascii_case(login) {
"/user/repos".to_string()
} else {
format!("/orgs/{owner}/repos")
};
let items = match self.http.pages(&path, 50, "limit", false) {
Ok(v) => v,
// Not an organisation (a user, or an org the token cannot see): say so, and take
// what the token can see under that name, private repos it collaborates on included.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => {
eprintln!(
"grove: /orgs/{owner} not found; listing the repositories you can see owned by {owner}"
);
self.http.pages("/user/repos", 50, "limit", false)?
}
}
Ok(out)
Err(e) => return Err(e),
};
Ok(items
.iter()
.map(repo)
.filter(|r| r.owner.eq_ignore_ascii_case(owner))
.collect())
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
+36 -14
View File
@@ -29,6 +29,7 @@ fn repo(v: &Value) -> RemoteRepo {
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(),
ssh_url: v["ssh_url"].as_str().unwrap_or_default().to_string(),
default_branch: v["default_branch"].as_str().unwrap_or("main").to_string(),
}
}
@@ -74,21 +75,42 @@ impl Provider for GitHub {
}
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(self
.http
.pages("/user/repos", 100, "per_page", true)?
.iter()
.map(repo)
.collect())
}
fn list_owner_repos(&self, owner: &str, login: &str) -> Result<Vec<RemoteRepo>> {
let path = if owner.eq_ignore_ascii_case(login) {
"/user/repos?affiliation=owner".to_string()
} else {
format!("/orgs/{owner}/repos?type=all")
};
let items = match self.http.pages(&path, 100, "per_page", true) {
Ok(v) => v,
// Not an organisation (a user, or an org the token cannot see): say so, and take
// what the token can see under that name, private repos it collaborates on included.
Err(Error::Api { status: 404, .. }) if !owner.eq_ignore_ascii_case(login) => {
eprintln!(
"grove: /orgs/{owner} not found; listing the repositories you can see owned by {owner}"
);
self.http.pages(
"/user/repos?affiliation=owner,collaborator,organization_member",
100,
"per_page",
true,
)?
}
}
Ok(out)
Err(e) => return Err(e),
};
Ok(items
.iter()
.map(repo)
.filter(|r| r.owner.eq_ignore_ascii_case(owner))
.collect())
}
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo> {
+68 -1
View File
@@ -24,6 +24,17 @@ impl Http {
/// 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)> {
self.send_h(method, path, body)
.map(|(status, json, _)| (status, json))
}
/// Like [`send`], also returning the pagination hints of the response headers.
fn send_h(
&self,
method: &str,
path: &str,
body: Option<&Value>,
) -> Result<(u16, Value, PageHints)> {
let url = format!("{}{}", self.base, path);
let net = |e: ureq::Error| Error::Network(e.to_string());
let mut resp = match (method, body) {
@@ -43,9 +54,19 @@ impl Http {
}
.map_err(net)?;
let status = resp.status().as_u16();
let header = |n: &str| {
resp.headers()
.get(n)
.and_then(|v| v.to_str().ok())
.map(str::to_string)
};
let hints = PageHints {
total: header("x-total-count").and_then(|v| v.trim().parse().ok()),
link: header("link"),
};
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))
Ok((status, json, hints))
}
/// Like [`send`], but maps non-2xx statuses to [`Error::Api`].
@@ -60,4 +81,50 @@ impl Http {
.to_string();
Err(Error::Api { status, message })
}
/// Every item of a paginated list endpoint (`path` may already carry a query string).
///
/// A short page is not the end (a server may cap the page size below what was asked). It
/// ends on `X-Total-Count` being reached, on a `Link` header without `rel="next"` (also when
/// absent, for `link_style` servers such as GitHub), or on an empty or repeated page.
pub fn pages(
&self,
path: &str,
per_page: usize,
size_param: &str,
link_style: bool,
) -> Result<Vec<Value>> {
let sep = if path.contains('?') { '&' } else { '?' };
let mut out: Vec<Value> = Vec::new();
let mut prev: Option<Vec<Value>> = None;
for page in 1..=500 {
let url = format!("{path}{sep}{size_param}={per_page}&page={page}");
let (status, v, hints) = self.send_h("GET", &url, None)?;
if !(200..300).contains(&status) {
let message = v["message"].as_str().unwrap_or("(no message)").to_string();
return Err(Error::Api { status, message });
}
let items = v.as_array().cloned().unwrap_or_default();
if items.is_empty() || prev.as_ref() == Some(&items) {
break;
}
out.extend(items.iter().cloned());
// GitHub style: no `Link: rel="next"` means this was the last page.
let no_next = hints
.link
.as_deref()
.map_or(link_style, |l| !l.contains("rel=\"next\""));
if hints.total.is_some_and(|t| out.len() >= t) || no_next {
break;
}
prev = Some(items);
}
Ok(out)
}
}
/// What the response headers say about the rest of a paginated list.
struct PageHints {
total: Option<usize>,
link: Option<String>,
}
+22 -1
View File
@@ -6,6 +6,7 @@ mod gitea;
mod github;
mod http;
pub mod token;
pub mod url;
pub use gitea::Gitea;
pub use github::GitHub;
@@ -53,9 +54,26 @@ pub struct RemoteRepo {
pub name: String,
pub private: bool,
pub clone_url: String,
/// SSH clone URL (empty when the forge did not report one).
pub ssh_url: String,
pub default_branch: String,
}
impl RemoteRepo {
/// The URL local git should use for `protocol`.
pub fn git_url(&self, protocol: grove_core::config::Protocol) -> Result<&str> {
use grove_core::config::Protocol;
match protocol {
Protocol::Https => Ok(&self.clone_url),
Protocol::Ssh if self.ssh_url.is_empty() => Err(Error::Other(format!(
"the forge reported no SSH URL for {}/{}",
self.owner, self.name
))),
Protocol::Ssh => Ok(&self.ssh_url),
}
}
}
#[derive(Debug, Clone)]
pub struct NewRepo {
pub name: String,
@@ -99,7 +117,7 @@ pub struct PullMirrorSpec {
pub interval: String,
}
pub trait Provider {
pub trait Provider: Send + Sync {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
/// Verifies the token and returns the authenticated login.
@@ -107,6 +125,9 @@ pub trait Provider {
/// One repo's metadata (notably its visibility): `GET /repos/{owner}/{repo}`.
fn get_repo(&self, owner: &str, name: &str) -> Result<RemoteRepo>;
fn list_repos(&self) -> Result<Vec<RemoteRepo>>;
/// The repos owned by `owner` (an organisation, or the authenticated user `login`), without
/// paging through everything else the token can see.
fn list_owner_repos(&self, owner: &str, login: &str) -> Result<Vec<RemoteRepo>>;
fn create_repo(&self, new: &NewRepo) -> Result<RemoteRepo>;
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
+1
View File
@@ -161,6 +161,7 @@ mod tests {
let h = |kind, url: &str| {
host(&ProviderCfg {
kind,
protocol: Default::default(),
url: Some(url.into()),
})
};
+191
View File
@@ -0,0 +1,191 @@
//! Validation and normalisation of what a forge (or a registry entry) tells us to clone: repo
//! names become directory names, URLs go to `git clone` together with credentials.
use crate::{Error, Result};
use grove_core::config::{Provider as ProviderCfg, ProviderKind};
/// A repo name is used as a directory name under the group: a plain, harmless one.
pub fn valid_repo_name(name: &str) -> bool {
!name.is_empty()
&& name != ".."
&& !name.starts_with(['.', '-'])
&& !name.contains(['/', '\\'])
&& !name.chars().any(char::is_control)
}
pub fn check_repo_name(name: &str) -> Result<()> {
if valid_repo_name(name) {
Ok(())
} else {
Err(Error::Other(format!(
"refusing repository name {name:?}: not a plain directory name"
)))
}
}
/// Host (lowercase, no user info, no port) of an `https://`, `ssh://` or scp-like
/// (`user@host:path`) URL. `None` for anything else (`file://`, local paths, `ext::`...).
pub fn url_host(url: &str) -> Option<String> {
if url.starts_with('-') || url.chars().any(char::is_control) {
return None;
}
let authority = if let Some((scheme, rest)) = url.split_once("://") {
if !["https", "ssh"].contains(&scheme) {
return None;
}
rest.split(['/', '?', '#']).next()?
} else {
// scp-like: user@host:path
let (head, _) = url.split_once(':')?;
if !head.contains('@') || head.contains('/') {
return None;
}
head
};
let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
let host = if host.starts_with('[') {
host
} else {
host.split(':').next()?
};
(!host.is_empty()).then(|| host.to_lowercase())
}
/// Ok when `url` is a clonable https/ssh URL on the provider's own host.
pub fn check_git_url(url: &str, expected_host: &str) -> Result<()> {
match url_host(url) {
Some(h) if h.eq_ignore_ascii_case(expected_host) => Ok(()),
Some(h) => Err(Error::Other(format!(
"refusing URL {url:?}: host {h} is not the provider's host {expected_host}"
))),
None => Err(Error::Other(format!(
"refusing URL {url:?}: only https://, ssh:// and user@host:path URLs are accepted"
))),
}
}
/// Host (no port) the provider's forge answers on; `github.com` for GitHub without a URL.
pub fn provider_host(cfg: &ProviderCfg) -> String {
let base = provider_base(cfg);
url_host(&base).unwrap_or_default()
}
/// `https://host[:port]` of the provider's web/git endpoint (no trailing slash).
pub fn provider_base(cfg: &ProviderCfg) -> String {
let url = cfg.url.as_deref().map(str::trim).unwrap_or_default();
let (scheme, rest) = url.split_once("://").unwrap_or(("https", url));
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
match cfg.kind {
ProviderKind::Github => {
let h = authority.strip_prefix("api.").unwrap_or(authority);
format!("https://{}", if h.is_empty() { "github.com" } else { h })
}
_ if authority.is_empty() => String::new(),
_ => format!("{scheme}://{authority}"),
}
}
/// `(owner, name)` of the path of a git URL (any accepted form), without a trailing `.git`.
pub fn owner_and_name(url: &str) -> Option<(String, String)> {
url_host(url)?;
let path = match url.split_once("://") {
Some((_, rest)) => rest.split_once('/')?.1,
None => url.split_once(':')?.1,
};
let path = path.trim_matches('/');
let path = path.strip_suffix(".git").unwrap_or(path);
let (owner, name) = path.rsplit_once('/')?;
// Only the last two segments matter (a forge may live under a sub-path).
let owner = owner.rsplit('/').next()?;
(!owner.is_empty() && !name.is_empty()).then(|| (owner.to_string(), name.to_string()))
}
/// The canonical https clone URL of the repo a git URL points to, on the provider `cfg`.
/// `None` when the URL's host is not the provider's.
pub fn canonical_https(cfg: &ProviderCfg, url: &str) -> Option<String> {
if !url_host(url)?.eq_ignore_ascii_case(&provider_host(cfg)) {
return None;
}
let (owner, name) = owner_and_name(url)?;
if !valid_repo_name(&name) || !valid_repo_name(&owner) {
return None;
}
Some(format!("{}/{owner}/{name}.git", provider_base(cfg)))
}
#[cfg(test)]
mod tests {
use super::*;
use grove_core::config::Protocol;
fn cfg(kind: ProviderKind, url: Option<&str>) -> ProviderCfg {
ProviderCfg {
kind,
protocol: Protocol::Https,
url: url.map(Into::into),
}
}
#[test]
fn repo_names_must_be_plain() {
for ok in ["a", "my-repo", "x.y", "Synapse_2"] {
assert!(valid_repo_name(ok), "{ok}");
}
for bad in [
"", "..", ".", ".hidden", "-rf", "a/b", "a\\b", "a\nb", "a\u{7}",
] {
assert!(!valid_repo_name(bad), "{bad:?}");
}
}
#[test]
fn only_https_ssh_and_scp_urls_on_the_right_host() {
let g = "git.example.es";
for ok in [
"https://git.example.es/o/r.git",
"https://tok@git.example.es:3000/o/r.git",
"ssh://gitea@git.example.es:2222/o/r.git",
"git@git.example.es:o/r.git",
] {
assert!(check_git_url(ok, g).is_ok(), "{ok}");
}
for bad in [
"https://evil.example/o/r.git",
"git@evil.example:o/r.git",
"file:///etc/passwd",
"/local/path",
"ext::sh -c id",
"--upload-pack=x",
"http://git.example.es/o/r.git",
"git://git.example.es/o/r.git",
] {
assert!(check_git_url(bad, g).is_err(), "{bad}");
}
}
#[test]
fn canonical_urls_follow_the_provider() {
let gitea = cfg(ProviderKind::Gitea, Some("https://git.example.es/"));
let want = Some("https://git.example.es/dasemu/x.git".to_string());
assert_eq!(
canonical_https(&gitea, "ssh://gitea@git.example.es:2222/dasemu/x.git"),
want
);
assert_eq!(
canonical_https(&gitea, "https://git.example.es/dasemu/x"),
want
);
assert_eq!(
canonical_https(&gitea, "https://evil.example/dasemu/x.git"),
None
);
let gh = cfg(ProviderKind::Github, None);
assert_eq!(
canonical_https(&gh, "git@github.com:Dasemu/Synapse.git").as_deref(),
Some("https://github.com/Dasemu/Synapse.git")
);
let ghe = cfg(ProviderKind::Github, Some("https://api.ghe.example.com"));
assert_eq!(provider_host(&ghe), "ghe.example.com");
}
}
+98
View File
@@ -87,6 +87,7 @@ fn gitea_connection_list_create_and_mirror() {
200,
r#"[{"name":"a","private":true,"clone_url":"u/a.git","default_branch":"main","owner":{"login":"dasemu"}}]"#,
),
(200, "[]"),
(
201,
r#"{"name":"n","private":true,"clone_url":"u/n.git","default_branch":"main","owner":{"login":"dasemu"}}"#,
@@ -115,6 +116,7 @@ fn gitea_connection_list_create_and_mirror() {
.unwrap();
assert_eq!(r.clone_url, "u/n.git");
rx.recv().unwrap();
rx.recv().unwrap(); // the empty second page
let create = rx.recv().unwrap();
assert!(create.starts_with("POST /api/v1/user/repos "), "{create}");
assert_eq!(body(&create)["private"], true);
@@ -301,10 +303,12 @@ fn falls_back_to_tea_and_gh_logins() {
let off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "0");
let gitea = |url: &str| ProviderCfg {
kind: ProviderKind::Gitea,
protocol: Default::default(),
url: Some(url.into()),
};
let github = ProviderCfg {
kind: ProviderKind::Github,
protocol: Default::default(),
url: None,
};
let id = format!("clitok-{}", std::process::id());
@@ -368,3 +372,97 @@ fn get_repo_reports_visibility_on_both_forges() {
.private
);
}
const REPO_A: &str = r#"{"name":"a","private":false,"clone_url":"https://h/o/a.git","ssh_url":"git@h:o/a.git","default_branch":"main","owner":{"login":"Org"}}"#;
const REPO_B: &str = r#"{"name":"b","private":true,"clone_url":"https://h/me/b.git","ssh_url":"ssh://gitea@h:2222/me/b.git","default_branch":"main","owner":{"login":"me"}}"#;
const REPO_C: &str = r#"{"name":"c","private":true,"clone_url":"https://h/x/c.git","ssh_url":"","default_branch":"main","owner":{"login":"x"}}"#;
fn lines(req: &str) -> &str {
req.lines().next().unwrap()
}
#[test]
fn gitea_owner_listing_uses_the_org_endpoint_or_the_users_own() {
let org = format!("[{REPO_A}]");
let user = format!("[{REPO_B},{REPO_C}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, "[]"),
(200, Box::leak(user.into_boxed_str())),
(200, "[]"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_owner_repos("Org", "me").unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].ssh_url, "git@h:o/a.git");
assert!(lines(&rx.recv().unwrap()).starts_with("GET /api/v1/orgs/Org/repos?limit=50&page=1 "));
assert!(lines(&rx.recv().unwrap()).contains("page=2 "));
// The login itself: `/user/repos`, then only its own repos (org repos it can see are dropped).
let r = g.list_owner_repos("ME", "me").unwrap();
assert_eq!(r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["b"]);
assert!(lines(&rx.recv().unwrap()).starts_with("GET /api/v1/user/repos?limit=50&page=1 "));
}
#[test]
fn github_owner_listing_scopes_the_query_and_sees_collaborator_repos_of_users() {
let org = format!("[{REPO_A}]");
let mine = format!("[{REPO_B}]");
let collab = format!("[{REPO_C},{REPO_B}]");
let (url, rx) = mock(vec![
(200, Box::leak(org.into_boxed_str())),
(200, Box::leak(mine.into_boxed_str())),
(404, r#"{"message":"Not Found"}"#),
(200, Box::leak(collab.into_boxed_str())),
]);
let g = GitHub::new(&url, "t".into());
assert_eq!(g.list_owner_repos("Org", "me").unwrap().len(), 1);
assert!(
lines(&rx.recv().unwrap()).starts_with("GET /orgs/Org/repos?type=all&per_page=100&page=1 ")
);
assert_eq!(g.list_owner_repos("me", "me").unwrap().len(), 1);
assert!(
lines(&rx.recv().unwrap())
.starts_with("GET /user/repos?affiliation=owner&per_page=100&page=1 ")
);
// Not an organisation (404): what the token sees under that name, private ones included.
let r = g.list_owner_repos("x", "me").unwrap();
assert_eq!(r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(), ["c"]);
rx.recv().unwrap(); // the 404 on /orgs/x
assert!(lines(&rx.recv().unwrap()).starts_with(
"GET /user/repos?affiliation=owner,collaborator,organization_member&per_page=100&page=1 "
));
}
#[test]
fn a_short_page_is_not_the_end_of_a_listing() {
// A server that caps the page size below the request: page 1 has 2 items, page 2 has 1.
let p1 = format!("[{REPO_A},{REPO_B}]");
let p2 = format!("[{REPO_C}]");
let (url, _rx) = mock(vec![
(200, Box::leak(p1.into_boxed_str())),
(200, Box::leak(p2.into_boxed_str())),
(200, "[]"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
assert_eq!(g.list_repos().unwrap().len(), 3);
}
#[test]
fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
use grove_core::config::Protocol;
let (url, _rx) = mock(vec![
(
200,
Box::leak(format!("[{REPO_B},{REPO_C}]").into_boxed_str()),
),
(200, "[]"),
]);
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
let r = g.list_repos().unwrap();
assert_eq!(r[0].git_url(Protocol::Https).unwrap(), "https://h/me/b.git");
assert_eq!(
r[0].git_url(Protocol::Ssh).unwrap(),
"ssh://gitea@h:2222/me/b.git"
);
assert!(r[1].git_url(Protocol::Ssh).is_err());
}
+6 -1
View File
@@ -14,14 +14,19 @@ 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.
# `cargo build --release --workspace && cargo deb -p grove --no-build` packages CLI + daemon + GUI + desktop files + user unit.
[package.metadata.deb]
name = "grove"
section = "devel"
depends = "$auto, git"
recommends = "libnotify-bin"
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"],
["../../target/release/grove-gui", "usr/bin/", "755"],
["../../contrib/grove.desktop", "usr/share/applications/", "644"],
["../../contrib/grove-autostart.desktop", "usr/share/grove/grove-autostart.desktop", "644"],
["../../assets/grove.png", "usr/share/icons/hicolor/64x64/apps/grove.png", "644"],
["../../contrib/groved.deb.service", "usr/lib/systemd/user/groved.service", "644"],
]
+10
View File
@@ -88,6 +88,9 @@ enum Cmd {
kind: String,
#[arg(long)]
url: Option<String>,
/// How git talks to the forge: https (API token) or ssh (your keys)
#[arg(long, default_value = "https")]
protocol: String,
#[arg(long, default_value = "default")]
group: String,
/// Name of the private config repo to keep the repo registry in
@@ -359,10 +362,16 @@ fn main() -> Result<()> {
provider,
kind,
url,
protocol,
group,
config_repo,
force,
} => {
let protocol = match protocol.as_str() {
"https" => grove_core::config::Protocol::Https,
"ssh" => grove_core::config::Protocol::Ssh,
p => bail!("unknown protocol {p:?} (https, ssh)"),
};
let path = cli
.config
.clone()
@@ -390,6 +399,7 @@ fn main() -> Result<()> {
provider: provider.clone(),
kind,
url: url.clone(),
protocol,
group: group.clone(),
config_repo: config_repo.clone(),
},
+409 -54
View File
@@ -2,11 +2,13 @@
use anyhow::{Context, Result, bail};
use grove_core::config::{
Config, Group, Layout, Machine, Provider as ProviderCfg, ProviderKind, Root,
Config, Group, Layout, Machine, Protocol, 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, PullMirrorSpec, RemoteRepo, build, token};
use grove_providers::{
MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, build, token, url,
};
use std::fs;
use std::path::{Path, PathBuf};
@@ -17,6 +19,30 @@ pub struct Forge {
pub token: String,
/// Git environment that authenticates HTTPS operations with the stored token.
pub git_env: Vec<(String, String)>,
pub protocol: Protocol,
pub cfg: ProviderCfg,
}
impl Forge {
/// The URL local git uses for `r` with this provider's protocol. The repo name must be a
/// plain directory name and both URLs the forge reports must be https/ssh URLs on the
/// provider's own host: credentials never go anywhere else.
pub fn clone_url(&self, r: &RemoteRepo) -> Result<String> {
let host = url::provider_host(&self.cfg);
url::check_repo_name(&r.name)?;
for u in [&r.clone_url, &r.ssh_url] {
if !u.is_empty() {
url::check_git_url(u, &host)?;
}
}
Ok(r.git_url(self.protocol)?.to_string())
}
/// The canonical https URL stored in the registry for `r`.
pub fn registry_url(&self, r: &RemoteRepo) -> Result<String> {
url::canonical_https(&self.cfg, &r.clone_url)
.with_context(|| format!("no canonical URL for {}/{}", r.owner, r.name))
}
}
pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
@@ -27,38 +53,61 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
let (tok, _) = token::resolve(id, pc)?;
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 takes the token as Basic auth (any user name works).
ProviderKind::Github => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!(
"Authorization: Basic {}",
base64(&format!("x-access-token:{tok}"))
let git_env = if pc.protocol == Protocol::Ssh {
// The user's SSH keys/agent authenticate; never prompt.
ssh_env()
} else {
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()),
],
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
// GitHub git-over-HTTPS takes the token as Basic auth (any user name works).
ProviderKind::Github => vec![
("GIT_CONFIG_COUNT".into(), "1".into()),
("GIT_CONFIG_KEY_0".into(), "http.extraHeader".into()),
(
"GIT_CONFIG_VALUE_0".into(),
format!(
"Authorization: Basic {}",
base64(&format!("x-access-token:{tok}"))
),
),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
],
}
};
Ok(Forge {
api,
login,
token: tok,
git_env,
protocol: pc.protocol,
cfg: pc.clone(),
})
}
/// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts.
/// `BatchMode` is only forced when the user has no ssh command of their own.
fn ssh_env() -> Vec<(String, String)> {
let mut env = vec![("GIT_TERMINAL_PROMPT".to_string(), "0".to_string())];
let custom = std::env::var_os("GIT_SSH_COMMAND").is_some()
|| std::env::var_os("GIT_SSH").is_some()
|| std::process::Command::new("git")
.args(["config", "--get", "core.sshCommand"])
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty());
if !custom {
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
}
env
}
/// The group's owner on `provider`, or `None` when that is the authenticated user itself
/// (personal repos use `/user/repos`, not the org endpoint).
fn org_owner(grp: &Group, provider: &str, login: &str) -> Option<String> {
@@ -103,6 +152,7 @@ pub struct InitArgs {
pub provider: String,
pub kind: ProviderKind,
pub url: Option<String>,
pub protocol: Protocol,
pub group: String,
pub config_repo: Option<String>,
}
@@ -119,6 +169,7 @@ pub fn init(path: &Path, a: InitArgs, force: bool) -> Result<Config> {
a.provider.clone(),
ProviderCfg {
kind: a.kind,
protocol: a.protocol,
url: a.url,
},
);
@@ -179,7 +230,9 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re
"created {}/{} on {}",
remote.owner, remote.name, route.primary
);
let wt = init_bare_layout(&dir, &remote.clone_url)?;
let local_url = primary.clone_url(&remote)?;
let registry_url = primary.registry_url(&remote)?;
let wt = init_bare_layout(&dir, &local_url)?;
push_initial(&dir, &primary.git_env)?;
println!("pushed initial commit; worktree {}", wt.display());
@@ -194,7 +247,7 @@ pub fn new_repo(cfg: &Config, group_name: &str, name: &str, private: bool) -> Re
&Entry {
group: grp.name.clone(),
name: name.into(),
url: remote.clone_url,
url: registry_url,
},
)?;
Ok(wt)
@@ -256,6 +309,82 @@ fn select(repos: Vec<RemoteRepo>, owner: &str, private: Option<bool>) -> Vec<Rem
.collect()
}
/// `host/owner/name` (lowercase) of a git remote URL in https, `ssh://` or scp-like form.
fn remote_key(url: &str) -> Option<String> {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r);
let (host, path) = match rest.split_once(['/', ':']) {
Some((h, p)) => (h, p),
None => return None,
};
// `host:2222/owner/repo` (ssh with a port): drop the port.
let path = match path.split_once('/') {
Some((port, p)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => p,
_ => path,
};
let path = path.trim_matches('/').trim_end_matches(".git");
let (owner, name) = path.rsplit_once('/')?;
Some(format!("{host}/{owner}/{name}").to_lowercase())
}
/// What is already in a group directory: anything non-empty by lowercase directory name, plain
/// (not yet migrated) clones among them, and the owner/name the `origin` of bare-layout repos
/// points to.
struct Local {
names: std::collections::HashSet<String>,
plain: std::collections::HashSet<String>,
origins: std::collections::HashSet<String>,
}
impl Local {
fn scan(gdir: &Path) -> Local {
let mut l = Local {
names: Default::default(),
plain: Default::default(),
origins: Default::default(),
};
let Ok(rd) = fs::read_dir(gdir) else { return l };
for e in rd.filter_map(Result::ok) {
let p = e.path();
// An empty directory is free to import into; anything else is somebody's files.
let non_empty = fs::read_dir(&p).is_ok_and(|mut d| d.next().is_some());
if !non_empty {
continue;
}
let name = e.file_name().to_string_lossy().to_lowercase();
l.names.insert(name.clone());
let bare = p.join(".bare");
if !bare.exists() {
if p.join(".git").exists() {
l.plain.insert(name);
}
continue;
}
if let Ok(Some(url)) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])
&& let Some(k) = remote_key(&url)
{
l.origins.insert(k);
}
}
l
}
/// Present when a non-empty directory of that name exists (case-insensitively: forge names
/// are, and so are many file systems) or an existing repo's origin is this very remote.
fn has(&self, r: &RemoteRepo) -> bool {
self.names.contains(&r.name.to_lowercase())
|| [&r.clone_url, &r.ssh_url]
.iter()
.filter_map(|u| remote_key(u))
.any(|k| self.origins.contains(&k))
}
/// A plain, not yet migrated clone of that name.
fn is_plain(&self, r: &RemoteRepo) -> bool {
self.plain.contains(&r.name.to_lowercase())
}
}
/// Lists the group's remote repos 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)?;
@@ -268,14 +397,47 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
None => vec![(grp.primary.clone(), None)],
};
let gdir = cfg.root_path().join(&grp.name);
// Both routes of a split group are queried at the same time.
let scanned: Vec<Result<(String, Forge, Vec<RemoteRepo>)>> = std::thread::scope(|sc| {
let hs: Vec<_> = sides
.iter()
.map(|(pid, vis)| {
let grp = &grp;
sc.spawn(move || {
let f = connect(cfg, pid)?;
let owner = grp.owner(pid).unwrap_or(&f.login).to_string();
let mut repos = select(f.api.list_owner_repos(&owner, &f.login)?, &owner, *vis);
repos.retain(|r| {
let ok = url::valid_repo_name(&r.name);
if !ok {
eprintln!(
"grove: skipping {}/{}: not a plain directory name",
r.owner, r.name
);
}
ok
});
Ok((pid.clone(), f, repos))
})
})
.collect();
hs.into_iter()
.map(|h| {
h.join()
.unwrap_or_else(|_| Err(anyhow::anyhow!("provider scan panicked")))
})
.collect()
});
let mut forges = Vec::new();
let mut missing: Vec<(RemoteRepo, usize)> = Vec::new();
for (pid, vis) in sides {
let f = connect(cfg, &pid)?;
let owner = grp.owner(&pid).unwrap_or(&f.login).to_string();
for r in select(f.api.list_repos()?, &owner, vis) {
let here = gdir.join(&r.name).join(".bare").exists();
if !here && !missing.iter().any(|(m, _)| m.name == r.name) {
let mut plain: Vec<RemoteRepo> = Vec::new();
let local = Local::scan(&gdir);
for res in scanned {
let (pid, f, repos) = res?;
for r in repos {
if local.is_plain(&r) {
plain.push(r);
} else if !local.has(&r) && !missing.iter().any(|(m, _)| m.name == r.name) {
missing.push((r, forges.len()));
}
}
@@ -292,25 +454,55 @@ pub fn import(cfg: &Config, group_name: &str, wanted: &[String]) -> Result<()> {
if r.private { " (private)" } else { "" }
);
}
if !plain.is_empty() {
println!("already here as plain clones (not migrated: use `grove add <path>`):");
for r in &plain {
println!("- {}/{}", r.owner, r.name);
}
}
println!("run `grove import {group_name} <name>...` to clone them");
return Ok(());
}
// One broken repo must not stop the others: collect failures and report them at the end.
let mut failed: Vec<String> = Vec::new();
for w in wanted {
let (r, i) = 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, &forges[*i].1.git_env)?;
println!("imported {} -> {}", r.name, dir.display());
register(
cfg,
&Entry {
group: grp.name.clone(),
name: r.name.clone(),
url: r.clone_url.clone(),
},
)?;
let Some((r, i)) = missing.iter().find(|(r, _)| &r.name == w) else {
if plain.iter().any(|r| &r.name == w) {
println!("FAILED {w}: local clone, not migrated; use `grove add`");
} else {
println!("FAILED {w}: not a remote repo missing locally");
}
failed.push(w.clone());
continue;
};
let forge = &forges[*i].1;
let res = (|| -> Result<()> {
let url = forge.clone_url(r)?;
let dir = gdir.join(&r.name);
// Refuses a non-empty directory and cleans up after itself on failure.
clone_bare_layout(&url, &dir, &forge.git_env)?;
println!("imported {} -> {}", r.name, dir.display());
register(
cfg,
&Entry {
group: grp.name.clone(),
name: r.name.clone(),
url: forge.registry_url(r)?,
},
)
})();
if let Err(e) = res {
println!("FAILED {w}: {e:#}");
failed.push(w.clone());
}
}
if !failed.is_empty() {
bail!(
"{} of {} imports failed: {}",
failed.len(),
wanted.len(),
failed.join(", ")
);
}
Ok(())
}
@@ -338,7 +530,7 @@ pub(crate) fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, F
.into_iter()
.find(|r| r.name == cr.name);
let url = match exists {
Some(r) => r.clone_url,
Some(r) => forge.clone_url(&r)?,
None if create => {
let r = forge.api.create_repo(&NewRepo {
name: cr.name.clone(),
@@ -346,7 +538,7 @@ pub(crate) fn config_repo_open(cfg: &Config, create: bool) -> Result<(PathBuf, F
private: true,
description: "grove configuration (managed repos, machines)".into(),
})?;
r.clone_url
forge.clone_url(&r)?
}
None => bail!(
"config repo {:?} does not exist on {}",
@@ -420,7 +612,17 @@ pub fn register(cfg: &Config, e: &Entry) -> Result<()> {
)
}
/// The configured provider whose host `url` is on (first by id when several share a host).
fn provider_for_url<'a>(cfg: &'a Config, url: &str) -> Option<(&'a String, &'a ProviderCfg)> {
let host = url::url_host(url)?;
cfg.providers
.iter()
.find(|(_, p)| url::provider_host(p).eq_ignore_ascii_case(&host))
}
/// First machine: creates the config repo (if needed) and registers every repo already on disk.
/// Entries hold the canonical https URL; a repo whose origin is on no configured provider is
/// skipped with a warning.
pub fn config_repo_init(cfg: &Config) -> Result<usize> {
let (dir, forge) = config_repo_open(cfg, true)?;
let mut reg = read_registry(&dir)?;
@@ -434,14 +636,24 @@ pub fn config_repo_init(cfg: &Config) -> Result<usize> {
if !bare.is_dir() {
continue;
}
let Some(url) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])?
let Some(origin) = Git::new(&bare).probe(&["config", "--get", "remote.origin.url"])?
else {
continue;
};
let name = e.file_name().to_string_lossy().into_owned();
let Some(canon) =
provider_for_url(cfg, &origin).and_then(|(_, p)| url::canonical_https(p, &origin))
else {
println!(
"warning: {}/{name}: origin {origin:?} is on no configured provider; not registered",
grp.name
);
continue;
};
reg.upsert(Entry {
group: grp.name.clone(),
name: e.file_name().to_string_lossy().into_owned(),
url,
name,
url: canon,
});
}
}
@@ -451,23 +663,69 @@ pub fn config_repo_init(cfg: &Config) -> Result<usize> {
Ok(reg.repos.len())
}
/// Where and how to clone a registry entry on this machine: the provider is chosen by the
/// entry's host, the transport by that provider's local `protocol`, the credentials are that
/// provider's. An entry on a host no provider serves is refused (a token never leaves its host).
/// Entries written with ssh or https URLs are both understood.
fn plan_clone(
cfg: &Config,
forges: &mut std::collections::HashMap<String, Forge>,
e: &Entry,
) -> Result<(String, String)> {
if !url::valid_repo_name(&e.name) || !url::valid_repo_name(&e.group) {
bail!(
"refusing entry {}/{}: not plain directory names",
e.group,
e.name
);
}
let (pid, pc) = provider_for_url(cfg, &e.url)
.with_context(|| format!("no configured provider serves the host of {:?}", e.url))?;
let canon = url::canonical_https(pc, &e.url)
.with_context(|| format!("cannot read owner/name from {:?}", e.url))?;
if !forges.contains_key(pid) {
forges.insert(pid.clone(), connect(cfg, pid)?);
}
let forge = &forges[pid];
let target = match forge.protocol {
Protocol::Https => {
url::check_git_url(&canon, &url::provider_host(pc))?;
canon
}
Protocol::Ssh => {
let (owner, name) = url::owner_and_name(&canon).context("bad registry URL")?;
forge.clone_url(&forge.api.get_repo(&owner, &name)?)?
}
};
Ok((pid.clone(), target))
}
/// 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);
let mut forges = std::collections::HashMap::new();
for e in &reg.repos {
// Names are checked before they are joined to a path.
if !url::valid_repo_name(&e.name) || !url::valid_repo_name(&e.group) {
println!("FAILED {}/{}: not plain directory names", e.group, e.name);
continue;
}
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) {
let res = plan_clone(cfg, &mut forges, e).and_then(|(pid, u)| {
clone_bare_layout(&u, &target, &forges[&pid].git_env).map_err(Into::into)
});
match res {
Ok(_) => {
println!("cloned {}/{}", e.group, e.name);
done += 1;
}
Err(err) => println!("FAILED {}/{}: {err}", e.group, e.name),
Err(err) => println!("FAILED {}/{}: {err:#}", e.group, e.name),
}
}
write_heartbeat(cfg, &dir)?;
@@ -485,10 +743,107 @@ mod tests {
name: name.into(),
private,
clone_url: format!("u/{name}.git"),
ssh_url: String::new(),
default_branch: "main".into(),
}
}
#[test]
fn remote_key_normalises_every_url_form() {
let want = Some("github.com/dasemu/synapse".to_string());
assert_eq!(remote_key("git@github.com:Dasemu/Synapse.git"), want);
assert_eq!(remote_key("https://github.com/Dasemu/Synapse.git"), want);
assert_eq!(remote_key("ssh://git@github.com/dasemu/synapse"), want);
assert_eq!(
remote_key("ssh://gitea@git.example.es:2222/dasemu/x.git").as_deref(),
Some("git.example.es/dasemu/x")
);
assert_eq!(remote_key("nonsense"), None);
}
#[test]
fn local_repos_match_by_name_or_origin_ignoring_case() {
let d = std::env::temp_dir().join(format!("grove-local-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
// `synapse` (lowercase dir) whose origin is Dasemu/Synapse; `other` with a renamed origin.
for (dir, origin) in [
("synapse", "git@github.com:Dasemu/Synapse.git"),
("renamed", "git@github.com:me/old-name.git"),
] {
let bare = d.join(dir).join(".bare");
fs::create_dir_all(&bare).unwrap();
let g = Git::new(&bare);
g.run(&["init", "-q", "--bare"]).unwrap();
g.run(&["remote", "add", "origin", origin]).unwrap();
}
// A plain clone and an unrelated non-empty dir count as present; an empty dir does not.
fs::create_dir_all(d.join("plainrepo/.git")).unwrap();
fs::create_dir_all(d.join("notes")).unwrap();
fs::write(d.join("notes/x.txt"), "x").unwrap();
fs::create_dir_all(d.join("emptydir")).unwrap();
let l = Local::scan(&d);
assert!(l.has(&r("me", "PlainRepo", false)) && l.is_plain(&r("me", "plainrepo", false)));
assert!(l.has(&r("me", "notes", false)) && !l.is_plain(&r("me", "notes", false)));
assert!(!l.has(&r("me", "emptydir", false)));
let mut syn = r("Dasemu", "Synapse", false);
syn.clone_url = "https://github.com/Dasemu/Synapse.git".into();
assert!(l.has(&syn));
// Different directory name, same origin.
let mut moved = r("me", "new-name", false);
moved.ssh_url = "git@github.com:me/old-name.git".into();
assert!(l.has(&moved));
assert!(!l.has(&r("me", "absent", false)));
let _ = fs::remove_dir_all(&d);
}
fn two_provider_cfg() -> Config {
Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\nprotocol=\"ssh\"\n\
[providers.gh]\nkind=\"github\"\n",
)
.unwrap()
}
#[test]
fn registry_entries_pick_their_provider_by_host_in_any_url_form() {
let cfg = two_provider_cfg();
let id = |u: &str| provider_for_url(&cfg, u).map(|(i, _)| i.as_str());
assert_eq!(id("https://git.example.es/dasemu/x.git"), Some("gitea"));
assert_eq!(
id("ssh://gitea@git.example.es:2222/dasemu/x.git"),
Some("gitea")
);
assert_eq!(id("git@github.com:Dasemu/Synapse.git"), Some("gh"));
assert_eq!(id("https://evil.example/dasemu/x.git"), None);
}
#[test]
fn bootstrap_refuses_entries_on_hosts_no_provider_serves() {
let cfg = two_provider_cfg();
let mut forges = std::collections::HashMap::new();
let entry = |u: &str, n: &str| Entry {
group: "g".into(),
name: n.into(),
url: u.into(),
};
let e = plan_clone(
&cfg,
&mut forges,
&entry("https://evil.example/o/r.git", "r"),
)
.unwrap_err();
assert!(e.to_string().contains("no configured provider"), "{e}");
assert!(forges.is_empty(), "no token lookup for a foreign host");
let e = plan_clone(
&cfg,
&mut forges,
&entry("https://git.example.es/o/r.git", "../x"),
)
.unwrap_err();
assert!(e.to_string().contains("plain directory names"), "{e}");
}
#[test]
fn base64_matches_rfc4648_vectors() {
for (i, o) in [
+5 -1
View File
@@ -1,4 +1,8 @@
# Phase 3: GUI
# Phase 3: GUI (superseded)
> **Superseded by [Phase 7](phase7.md).** The HTML/JS frontend, the localhost bridge and the Tauri
> shell described below were removed; the native `grove-gui` replaces them. Kept for history.
## Layout
+1 -1
View File
@@ -20,7 +20,7 @@
## Not done
- AppImage (no `appimagetool`) and Flatpak: not attempted. The Tauri bundle config requests `deb` and
`appimage`, untested.
`appimage`, untested (Tauri was removed in [Phase 7](phase7.md); the `.deb` now ships `grove-gui`).
- 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.
+155
View File
@@ -0,0 +1,155 @@
# Phase 7: native GUI
`grove-gui` (crate `crates/grove-gui`) replaces the web UI of Phase 3. It is a native desktop app
(Slint UI, StatusNotifierItem tray) that lives in the system tray. It contains no sync logic: state
comes from the daemon over its Unix socket and every action runs an allow-listed `grove` subcommand,
exactly as before.
## Architecture
| Part | Where |
|---|---|
| Daemon IPC + allow-listed CLI calls + config (formerly `grove-bridge`) | `src/bridge.rs` |
| Pure logic: status -> aggregate/tray state, formatting, `grove import` listing parser, settings summary | `src/model.rs` |
| Tray (ksni), icons drawn in code per state | `src/tray.rs` |
| Single instance (Unix socket) | `src/instance.rs` |
| Window, callbacks, worker threads | `src/main.rs`, `ui/app.slint` |
Threads: the Slint event loop; a worker that fetches `status` (and `log`/config only while the window
is visible); a subscriber that holds a `subscribe` connection to the daemon and wakes the worker on
every event (reconnects every 5 s while the daemon is down); the tray service; the single-instance
listener; short-lived threads for CLI calls so the UI never blocks. Fallback poll: 5 s with the
window open, 30 s hidden. Daemon events are coalesced (at most one status refresh per 1 s visible,
10 s hidden). Hidden, the worker only asks for `status`: it drives the tray (touched only when the
aggregate changes; pixmaps are rendered once per state) and notifications, and nothing is sent to
the UI thread. Log, config and models are fetched when the window opens. No Slint timers run while idle.
Tray states: ok, syncing, attention (diverged, error, `ahead`, `behinddirty`; also sets the item to `NeedsAttention`), paused, daemon offline.
Menu: Open, Sync now, Pause/Resume, Quit; left click opens the window. Closing the window hides it;
Quit exits. If no StatusNotifier host exists, closing the window quits. A transition into
`Diverged`/`Error` shows a toast when the window is open and calls `notify-send` (best effort) when hidden.
Single instance: `$XDG_RUNTIME_DIR/grove/gui.sock`. A second `grove-gui` asks the first to show
its window and exits; `grove-gui --hidden` (autostart) only checks and never raises the window.
Daemon scope and snapshot policy (Phase 6) in the GUI: each repo shows `snapshots withheld: <reason>`
(list and detail), the repositories view lists the `not_migrated` clones with the hint to run
`grove add`, settings show the default snapshot policy and per-group overrides, and Activity colours
`snapshots_withheld`/`snapshots_purged` as warnings and `snapshots_enabled` as ok.
Screens (parity with Phase 3): repositories with per-worktree state, repository detail with the
resolve panel (confirmation first), activity with filter, new repository, import (scan, pick,
import), settings (machine, providers, groups incl. public route and `owners`, config repo, token
login, secrets), onboarding when there is no config, offline state with a hint.
## Run
```bash
cargo run --release -p grove-gui # window + tray
grove-gui --hidden # tray only
grove-gui --config PATH --socket PATH --grove-bin PATH # test against another daemon/config
grove-gui --view settings # start on a view (activity, new, import, repo:<path>)
```
`grove` is looked up next to the `grove-gui` binary, then in `PATH`. Packaging: `.deb` installs
`grove-gui`, `contrib/grove.desktop`, `assets/grove.png` and a copy of the autostart file under
`/usr/share/grove/`. Autostart is opt-in: Settings has a "Start Grove at login" toggle that writes or
removes `~/.config/autostart/grove.desktop`. The deb recommends `libnotify-bin` (`notify-send`). Dev builds need no system Qt: Slint is built with the `winit` backend (Wayland and
X11 loaded at runtime) and the software renderer.
## Dependencies
- `slint` / `slint-build` 1.18.1 (`std`, `backend-winit`, `renderer-software`, `compat-1-2`; no Qt,
no femtovg, no system-tray feature). Style `fluent` (pure Slint). Slint is licensed GPL-3.0 or its
royalty-free license (attribution required) or a commercial one; pick one before distributing.
- `ksni` 0.3.7 (`async-io` + `blocking`, no tokio).
## Memory (release build, KDE Plasma 6 / Wayland, `ps -o rss`)
| State | Software renderer (used) | femtovg (GL) |
|---|---|---|
| Started with `--hidden` | 24 MB | 94 MB |
| Window open | 31 MB | 105 MB |
| After closing the window (hidden again) | 25 MB | not measured |
Hidden CPU against a busy daemon (8 repos, 5 s fetch interval, ~4 events/s): about 4 ticks in 60 s
(0.07%), RSS flat. 9 threads.
## Limits
- Slint does not expose xdg-activation, so launching again (or clicking the tray) on a visible window re-maps it (hide + show); the compositor focuses the fresh window (checked on KWin: keyboard focus arrives). The compositor picks the window position again.
- Activity timestamps use the local UTC offset read via `date +%z` (no timezone crate).
- Onboarding stays on screen until login and bootstrap succeed. If a config already exists it is kept and `grove init` is skipped (the form fields are then ignored, the output says so).
- Resolve output under a worktree disappears once that worktree's state changes after the run; a toast reports the result.
- The activity list shows the first line of each message, repository errors are cut at 160 characters
in the list (full text in the detail view).
- Slint's wrapped text under-reports its height in layouts, so long text is elided, not wrapped.
- Side-by-side compare for `Diverged` stays in the CLI (`grove resolve --compare`).
- Only the layout and read-only views were checked visually; forms and CLI-driven flows were not
clicked through (no input injection available), only their parsing and logic are unit-tested.
## Import speed, git protocol, import robustness
- `Provider::list_owner_repos(owner, login)` lists only the owner's repos: Gitea `/orgs/{org}/repos`
or `/user/repos` (filtered by owner) for the login; GitHub `/orgs/{org}/repos?type=all` or
`/user/repos?affiliation=owner`. A 404 on the org endpoint falls back to `/users/{owner}/repos`.
The two sides of a split group are scanned in parallel threads. `grove import Darío` on the
owner's real forges: 3.5 s -> 1.3 s.
- The GUI scan runs on its own thread (not the status worker), is cached per group for the session,
and has a Rescan button. Switching groups shows the cached list; an import drops the cache.
- "Already on this machine" is case-insensitive by directory name, or when an existing bare repo's
`origin` points to the same host/owner/name (https, `ssh://` and scp-like forms).
- A failing clone no longer aborts a multi-repo import: the others continue, failures are printed
as `FAILED <name>: <reason>`, the exit status is non-zero and the GUI lists the failed names.
- Per-provider `protocol = "https" | "ssh"` (default `https`; also `grove init --protocol` and the
onboarding form). With `ssh`, `new`/`import`/`bootstrap` clone from the forge's `ssh_url`, registry
entries store that URL, and git gets no token header (only `GIT_TERMINAL_PROMPT=0`, plus
`GIT_SSH_COMMAND="ssh -o BatchMode=yes"` unless the user has their own ssh command). Mirrors stay
HTTPS with tokens (forge to forge). The Settings summary shows the protocol of each provider.
```toml
[providers.gitea]
kind = "gitea"
url = "https://git.example.com"
protocol = "ssh" # optional, default "https"
```
## Migrating clones from the GUI
The "Not migrated clones" card has a Migrate button per row and a Migrate all button. Each asks
for confirmation first (the dialog names the backup directory, `<state dir>/backups`), then runs
`grove add <path>` one clone at a time off the UI thread, showing "Migrating…", then the migrated
path or the refusal message (linked worktrees, submodules, detached HEAD...). The bridge only runs
`add` for an existing, non-symlink directory directly under `<root>/<group>/` and passes no flags
(so no custom backup directory). Afterwards the status is refreshed; the daemon computes its
not-migrated list at runtime, so after a migration the row keeps its result on screen until the
next status refresh drops it. A second `grove add` is refused while a `.grove-busy` marker is held;
Migrate all runs strictly one clone at a time and shows that refusal text on the row. Repos the
daemon reports as `stalled` (interrupted operation, marker left behind) get their own card with
the hint to check the backups; `repo_added`, `repo_removed` and `repo_stalled` (warning) appear in
Activity.
## Diagnostics log
`<state dir>/grove-gui.log` (rotated at 256 KiB) records start-up, daemon subscribe/disconnect,
tray errors and restarts, panics with a backtrace (from any thread) and why the event loop ended.
## Hardening of import, clone and bootstrap
- Any non-empty directory in the group counts as "already here". A plain clone is listed
separately ("use `grove add`") and `import` refuses it; `clone_bare_layout` refuses a non-empty
target itself.
- A clone that fails after `git clone` removes what it created (`.bare`, worktree directories,
and the directory when it created it). If that fails, `.grove-stage` is left so the daemon
reports the repo as stalled.
- The registry stores canonical https URLs (`https://host/owner/name.git`). `bootstrap` picks the
provider by the entry's host, the transport from that provider's `protocol`, and uses only that
provider's credentials; an entry on a host no provider serves is refused. Old entries with ssh
or https URLs are normalised when read.
- Repo names must be plain directory names (no `/`, `\`, leading `.` or `-`, control chars);
clone URLs must be `https://`, `ssh://` or `user@host:path` on the provider's host; `git clone`
gets `--`.
- Pagination stops on `X-Total-Count`, on a `Link` without `rel="next"` (GitHub), or an empty or
repeated page, not on a short page. For a user that is not the login, GitHub/Gitea listing uses
`/user/repos` (collaborator repos included) and says when `/orgs/{owner}` is a 404.
- The GUI hands `grove add` the canonical path it validated.
-2
View File
@@ -1,2 +0,0 @@
/target
/gen
-19
View File
@@ -1,19 +0,0 @@
# 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
@@ -1,3 +0,0 @@
fn main() {
tauri_build::build()
}
-7
View File
@@ -1,7 +0,0 @@
{
"$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"]
}
-79
View File
@@ -1,79 +0,0 @@
//! 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
@@ -1,20 +0,0 @@
{
"$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
@@ -1,367 +0,0 @@
'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+?)(?: on \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.public ? ' · public: ' + g.public.primary + ((g.public.mirror_to || []).length ? ' → ' + g.public.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
@@ -1,36 +0,0 @@
<!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
@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 294 B

-98
View File
@@ -1,98 +0,0 @@
: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; }
}