Merge pull request #6 from Dasemu/development

Development
This commit is contained in:
dasemu authored and GitHub committed 2026-11-16 22:25:28 +01:00
commit d281c91c30
12 files changed
+782 -18

No files matched your search

+2 -2
View File
@@ -4,7 +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-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.
`grove-gui` (native Slint desktop app with a ksni tray, `docs/phase7.md`). Phases 0-7 are implemented; the real two-PC run passed (`docs/two-pc-run.md`).
Do not start new work before the previous results are written to `docs/`.
## Commands
@@ -17,7 +17,7 @@ Do not start new work before the previous results are written to `docs/`.
- Throwaway e2e on a local Forgejo: `spikes/phase4-e2e.sh`
## Architecture
See `docs/` (`phase0-spike.md` ... `phase7.md`, `DECISIONS.md`). Git is the storage layer; shell out to
See `docs/` (`phase0-spike.md` ... `phase7.md`, `two-pc-run.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.
+39
View File
@@ -155,6 +155,10 @@ pub struct Sync {
/// Default snapshot push policy; a group can override it.
#[serde(default)]
pub snapshots: SnapshotPolicy,
/// Directory under the root that repos deleted on their forge are moved to (and so stop
/// syncing). Empty disables the move.
#[serde(default = "default_purged_dir")]
pub purged_dir: String,
}
impl Default for Sync {
@@ -165,6 +169,7 @@ impl Default for Sync {
ignore_extra: Vec::new(),
max_file_mb: default_max_file_mb(),
snapshots: SnapshotPolicy::default(),
purged_dir: default_purged_dir(),
}
}
}
@@ -184,6 +189,9 @@ fn default_debounce() -> u64 {
fn default_max_file_mb() -> u64 {
50
}
fn default_purged_dir() -> String {
"Purged".into()
}
fn default_fetch() -> u64 {
60
}
@@ -275,6 +283,19 @@ impl Config {
"machine.name {n:?} must be non-empty and use only letters, digits, '-' or '_'"
));
}
let pd = &self.sync.purged_dir;
if !pd.is_empty() {
if pd.starts_with('.') || pd.contains(['/', '\\']) {
return bad(format!(
"sync.purged_dir {pd:?} must be a plain directory name"
));
}
if self.groups.iter().any(|g| &g.name == pd) {
return bad(format!(
"sync.purged_dir {pd:?} is also a group: purged repos would keep syncing"
));
}
}
for g in &self.groups {
// Group names are directory names under the root.
if g.name.is_empty() || g.name.starts_with('.') || g.name.contains(['/', '\\']) {
@@ -383,6 +404,24 @@ name = "grove-config"
assert_eq!(c.root_path(), PathBuf::from("/x"));
}
#[test]
fn purged_dir_defaults_and_must_not_be_a_group() {
let base = "[machine]\nname=\"a\"\n[root]\npath=\"/x\"\n[providers.p]\nkind=\"github\"\n";
assert_eq!(Config::parse(base).unwrap().sync.purged_dir, "Purged");
let off = format!("{base}[sync]\npurged_dir=\"\"\n");
assert_eq!(Config::parse(&off).unwrap().sync.purged_dir, "");
for bad in [
format!("{base}[sync]\npurged_dir=\"a/b\"\n"),
format!("{base}[sync]\npurged_dir=\".x\"\n"),
format!("{base}[[groups]]\nname=\"Purged\"\nprimary=\"p\"\n"),
] {
assert!(
matches!(Config::parse(&bad), Err(ConfigError::Invalid(_))),
"{bad}"
);
}
}
#[test]
fn rejects_unsafe_machine_name() {
for n in ["", "a/b", "a b", "a..b"] {
+129 -3
View File
@@ -4,7 +4,74 @@ use std::ffi::OsStr;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// Wall-clock limit for one git invocation in seconds; 0 (the default) means none.
static TIMEOUT_SECS: AtomicU64 = AtomicU64::new(0);
/// Sets a wall-clock limit for every git invocation of this process (0 disables it). Meant for
/// the daemon, whose single sync loop must never block forever on a stuck fetch, hook or helper.
pub fn set_timeout(secs: u64) {
TIMEOUT_SECS.store(secs, Ordering::Relaxed);
}
/// Runs `cmd`, killing it (and its process group: ssh, helpers) when it outlives the limit.
fn output(cmd: Command, args: &[String]) -> Result<Output, GitError> {
output_within(cmd, args, TIMEOUT_SECS.load(Ordering::Relaxed))
}
fn output_within(mut cmd: Command, args: &[String], secs: u64) -> Result<Output, GitError> {
if secs == 0 {
return Ok(cmd.output()?);
}
use std::io::Read;
use std::os::unix::process::CommandExt;
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0);
let mut child = cmd.spawn()?;
let reader = |mut r: Box<dyn Read + Send>| {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = r.read_to_end(&mut buf);
let _ = tx.send(buf);
});
rx
};
let out_rx = reader(Box::new(child.stdout.take().expect("piped")));
let err_rx = reader(Box::new(child.stderr.take().expect("piped")));
let deadline = Instant::now() + Duration::from_secs(secs);
let mut nap = Duration::from_millis(1);
let status = loop {
if let Some(st) = child.try_wait()? {
break st;
}
if Instant::now() >= deadline {
let _ = Command::new("kill")
.args(["-KILL", "--", &format!("-{}", child.id())])
.status();
let _ = child.kill();
let _ = child.wait();
return Err(GitError::Other(format!(
"git {} timed out after {secs} s and was killed",
args.join(" ")
)));
}
std::thread::sleep(nap);
nap = (nap * 2).min(Duration::from_millis(100));
};
// A lingering ssh master (ControlPersist) may keep the pipes open after git exits.
let grace = Duration::from_secs(2);
Ok(Output {
status,
stdout: out_rx.recv_timeout(grace).unwrap_or_default(),
stderr: err_rx.recv_timeout(grace).unwrap_or_default(),
})
}
#[derive(Debug)]
pub enum GitError {
@@ -37,6 +104,10 @@ impl From<io::Error> for GitError {
}
}
fn owned(args: &[&str]) -> Vec<String> {
args.iter().map(|s| s.to_string()).collect()
}
/// A git invocation context: a working directory plus extra environment.
#[derive(Debug, Clone)]
pub struct Git {
@@ -73,7 +144,7 @@ impl Git {
/// Run git, returning trimmed stdout. Any non-zero exit is an error.
pub fn run(&self, args: &[&str]) -> Result<String, GitError> {
let out = self.command(args).output()?;
let out = output(self.command(args), &owned(args))?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
@@ -87,7 +158,7 @@ impl Git {
/// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`).
pub fn probe(&self, args: &[&str]) -> Result<Option<String>, GitError> {
let out = self.command(args).output()?;
let out = output(self.command(args), &owned(args))?;
if out.status.success() {
Ok(Some(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
@@ -97,3 +168,58 @@ impl Git {
}
}
}
/// Environment that keeps unattended git from ever waiting on a person: no terminal or askpass
/// prompts (a desktop `SSH_ASKPASS` such as ksshaskpass would otherwise open a dialog and block
/// forever), and stalled HTTP transfers abort. The ssh command is left alone so a user's (or a
/// repo's) `core.sshCommand` keeps working; wall-clock limits come from [`set_timeout`].
pub fn noninteractive_env() -> Vec<(String, String)> {
[
("GIT_TERMINAL_PROMPT", "0"),
("GIT_ASKPASS", "true"),
("SSH_ASKPASS_REQUIRE", "never"),
("GIT_HTTP_LOW_SPEED_LIMIT", "1000"),
("GIT_HTTP_LOW_SPEED_TIME", "60"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
}
/// Whether the user configured their own ssh command for git (env or `core.sshCommand`).
pub fn has_custom_ssh() -> bool {
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())
}
#[cfg(test)]
mod env_tests {
use super::*;
#[test]
fn unattended_git_never_prompts_and_leaves_the_ssh_command_alone() {
let env = noninteractive_env();
let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
assert_eq!(get("GIT_TERMINAL_PROMPT"), Some("0"));
assert_eq!(get("SSH_ASKPASS_REQUIRE"), Some("never"));
assert_eq!(get("GIT_SSH_COMMAND"), None);
}
#[test]
fn a_git_call_over_the_limit_is_killed() {
// A hook-like stall: `git -c alias.x='!sleep 30' x`. The global limit is not touched, so
// tests running in parallel are unaffected.
let args = owned(&["-c", "alias.zzsleep=!sleep 30", "zzsleep"]);
let t = Instant::now();
let r = output_within(Git::new(".").command(&args), &args, 1);
assert!(r.unwrap_err().to_string().contains("timed out"));
assert!(t.elapsed() < Duration::from_secs(10));
let v = owned(&["--version"]);
let out = output_within(Git::new(".").command(&v), &v, 5).unwrap();
assert!(String::from_utf8_lossy(&out.stdout).starts_with("git version"));
}
}
+124 -1
View File
@@ -5,6 +5,7 @@
use crate::activity::{Activity, now_secs};
use crate::discover::{discover, group_of, is_ready, subdirs};
use crate::ipc;
use crate::purge;
use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config;
use grove_core::receive::Received;
@@ -426,6 +427,8 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
let mut next_full = Instant::now();
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
let mut rescan_at: Option<Instant> = None;
// Repos whose forge first confirmed their deletion at this time (see `purge`).
let mut gone_since: HashMap<PathBuf, (u64, u64)> = HashMap::new();
loop {
let now = Instant::now();
@@ -515,7 +518,15 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
// While backing off after a failure, still snapshot local work (no network needed);
// the network is retried at the first pass after the backoff expires.
let offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx);
let failures = pass(
&r,
&cfg,
&st,
&mut visibility,
offline,
&mut gone_since,
&ctx,
);
if !is_ready(&r) {
// It vanished mid-pass: whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
@@ -559,6 +570,7 @@ fn pass(
st: &Settings,
visibility: &mut Visibility,
offline: bool,
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
ctx: &Ctx,
) -> u32 {
let name = repo.display().to_string();
@@ -600,6 +612,9 @@ fn pass(
push_snapshots,
};
let result = sync_repo(repo, &opts);
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
return 0;
}
let mut shared = ctx.shared.lock().unwrap();
// The repo may have been dropped by a rediscovery while the pass ran.
let Some(status) = shared.repos.get_mut(repo) else {
@@ -693,6 +708,114 @@ fn pass(
status.failures
}
/// Moves `repo` out of the synced tree once its forge has kept confirming its deletion for
/// `purge::CONFIRM_AFTER_SECS`; returns true when it is gone from its place. A fetch that works,
/// or the forge seeing the repo, clears it; so does a gap of more than twice that interval
/// between confirmations.
fn purge_if_gone(
repo: &Path,
cfg: &Config,
st: &Settings,
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
ctx: &Ctx,
) -> bool {
let name = repo.display().to_string();
let hint = match result {
Ok(rep) => rep.fetch_error.as_deref().is_some_and(purge::looks_gone),
Err(_) => false,
};
if !hint || cfg.sync.purged_dir.is_empty() {
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
gone_since.remove(repo);
}
return false;
}
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
Ok(true) => {}
Ok(false) => {
gone_since.remove(repo);
return false;
}
// Cannot tell (network, token): keep whatever was confirmed before.
Err(_) => return false,
}
let now = now_secs();
let window = purge::CONFIRM_AFTER_SECS;
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
if now.saturating_sub(entry.1) > 2 * window {
// Stale: start over.
*entry = (now, now);
}
entry.1 = now;
let first = entry.0;
if first == now {
ctx.activity.log(
"purge_pending",
Some(&name),
format!(
"the forge reports the remote repo deleted; moving it to {}/ if that still holds in {} min",
cfg.sync.purged_dir,
window / 60
),
);
}
if now.saturating_sub(first) < window {
return false;
}
let Some(dest) = purge::destination(&cfg.root_path(), &cfg.sync.purged_dir, repo, &stamp())
else {
return false;
};
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
gone_since.remove(repo);
ctx.shared.lock().unwrap().repos.remove(repo);
};
match purge::move_repo(repo, &dest) {
Ok(moved) => {
gone(ctx, gone_since);
let mut msg = format!(
"remote repo deleted: moved to {} (no longer synced; files untouched)",
dest.display()
);
if !moved.unrepaired.is_empty() {
let list: Vec<String> = moved
.unrepaired
.iter()
.map(|p| p.display().to_string())
.collect();
msg.push_str(&format!(
"; worktrees not found, run `git worktree repair <path>` from {}/.bare once they are back: {}",
dest.display(),
list.join(", ")
));
}
ctx.activity.log("purged", Some(&name), msg);
true
}
Err(purge::MoveError::Repair(e)) => {
gone(ctx, gone_since);
ctx.activity.log(
"purged",
Some(&name),
format!(
"remote repo deleted: moved to {}, but repairing its worktree links failed ({e}); run `git worktree repair` there",
dest.display()
),
);
true
}
Err(purge::MoveError::NotMoved(e)) => {
ctx.activity.log(
"purge_failed",
Some(&name),
format!("not moved to {}: {e}", dest.display()),
);
false
}
}
}
/// Records why snapshots are withheld (or that they are pushed again), logging only changes.
fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option<String>) {
let mut shared = ctx.shared.lock().unwrap();
+1
View File
@@ -6,6 +6,7 @@ pub mod activity;
pub mod daemon;
pub mod discover;
pub mod ipc;
pub mod purge;
#[cfg(test)]
#[path = "../../../test-support/tmp.rs"]
mod test_tmp;
+10
View File
@@ -5,6 +5,9 @@ use grove_core::config::Config;
use grove_daemon::{Daemon, Settings};
use std::path::PathBuf;
/// Upper bound for one git call of the daemon (a large first fetch included).
const GIT_TIMEOUT_SECS: u64 = 900;
fn main() -> Result<()> {
let mut args = std::env::args().skip(1);
let mut config: Option<PathBuf> = None;
@@ -23,6 +26,13 @@ fn main() -> Result<()> {
.context("cannot determine config path")?;
let cfg = Config::load(&path)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
// Unattended: git/ssh must never prompt (the session's SSH_ASKPASS would open a dialog and
// block every sync), and no git call may block the sync loop forever.
for (k, v) in grove_core::git::noninteractive_env() {
// SAFETY: still single-threaded; no other thread reads the environment yet.
unsafe { std::env::set_var(k, v) };
}
grove_core::git::set_timeout(GIT_TIMEOUT_SECS);
let st = Settings::standard();
eprintln!(
"groved: machine {:?}, root {}, socket {}",
+378
View File
@@ -0,0 +1,378 @@
//! Repos deleted on their forge are moved out of the synced tree, never deleted locally.
//!
//! A fetch error alone never moves anything: the forge must answer 404 for a repo the token's
//! account owns (its login, or an organisation named in a group's `owners`) while that token
//! works, and must still do so [`CONFIRM_AFTER_SECS`] after the first confirmation. The repo then
//! moves to `root/<sync.purged_dir>/<group>/<repo>`, which is not a configured group, so it is no
//! longer synced; its worktree links are repaired.
use crate::visibility::{Forge, Seen, parse_remote, provider_for};
use grove_core::busy::BusyGuard;
use grove_core::config::Config;
use grove_core::git::Git;
use std::path::{Path, PathBuf};
/// How long a remote deletion must keep being confirmed before the repo is moved.
pub const CONFIRM_AFTER_SECS: u64 = 600;
/// Fetch failures that may mean the remote repo is gone (only a hint; see [`confirmed_gone`]).
pub fn looks_gone(fetch_error: &str) -> bool {
let e = fetch_error.to_ascii_lowercase();
[
"not found",
"does not appear to be a git repository",
"does not exist",
"error: 404",
]
.iter()
.any(|p| e.contains(p))
}
/// True only when the forge serving `remote` answers 404 for a repo owned by the token's own
/// account or by an organisation the config names in some group's `owners`, while that token
/// works. A repo of someone else (made private, or access revoked) is never reported gone.
pub fn confirmed_gone(
cfg: &Config,
repo: &Path,
remote: &str,
forge: &dyn Forge,
) -> Result<bool, String> {
let url = Git::new(repo.join(".bare"))
.run(&["remote", "get-url", remote])
.map_err(|e| e.to_string())?;
let id = parse_remote(&url).ok_or_else(|| format!("cannot parse remote URL {url:?}"))?;
let (pid, pc) = provider_for(cfg, &id)?;
// A 404 from a broken or foreign token proves nothing.
let login = forge.login(pid, pc)?;
let owned = id.owner.eq_ignore_ascii_case(&login)
|| cfg.groups.iter().any(|g| {
g.owners
.get(pid)
.is_some_and(|o| o.eq_ignore_ascii_case(&id.owner))
});
if !owned {
return Ok(false);
}
Ok(forge.seen(pid, pc, &id.owner, &id.name)? == Seen::Absent)
}
/// Where `repo` (`root/<group>/<name>`) goes: `root/<purged_dir>/<group>/<name>`, with a
/// `-<stamp>` suffix when that is taken.
pub fn destination(root: &Path, purged_dir: &str, repo: &Path, stamp: &str) -> Option<PathBuf> {
let name = repo.file_name()?;
let group = repo.parent()?.file_name()?;
let dir = root.join(purged_dir).join(group);
let first = dir.join(name);
if !first.exists() {
return Some(first);
}
Some(dir.join(format!("{}-{stamp}", name.to_string_lossy())))
}
#[derive(Debug)]
pub enum MoveError {
/// Nothing was moved (busy, an operation in progress, cross-device...).
NotMoved(String),
/// The repo is at its destination, but some worktree links could not be repaired.
Repair(String),
}
/// A finished move: worktrees whose directory was missing (unmounted disk, prunable) could not
/// be repaired; `git worktree repair <path>` from the new `.bare` fixes them later.
#[derive(Debug, Default)]
pub struct Moved {
pub unrepaired: Vec<PathBuf>,
}
/// An operation in progress in some worktree (or the repo) that a move would break.
fn in_progress(repo: &Path, wts: &[PathBuf]) -> Option<String> {
if repo.join(".grove-stage").exists() {
return Some("an interrupted grove operation left .grove-stage".into());
}
for w in wts.iter().filter(|w| w.exists()) {
let Ok(gd) = Git::new(w).run(&["rev-parse", "--absolute-git-dir"]) else {
continue;
};
let gd = PathBuf::from(gd);
for f in [
"index.lock",
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
] {
if gd.join(f).exists() {
return Some(format!("{}: {f} (git operation in progress)", w.display()));
}
}
}
None
}
/// Moves the bare-layout repo to `dest` (same file system) and repairs every worktree link:
/// worktrees inside the repo move with it, linked ones elsewhere are pointed at the new `.bare`.
/// Holds `.grove-busy` while moving and refuses while a git operation is in progress.
pub fn move_repo(repo: &Path, dest: &Path) -> Result<Moved, MoveError> {
let not = |m: String| MoveError::NotMoved(m);
// git reports worktree paths resolved (symlinks followed): compare against resolved paths.
let real_repo = repo
.canonicalize()
.map_err(|e| not(format!("{}: {e}", repo.display())))?;
let bare = real_repo.join(".bare");
let list = Git::new(&bare)
.run(&["worktree", "list", "--porcelain"])
.map_err(|e| not(e.to_string()))?;
let wts: Vec<PathBuf> = list
.lines()
.filter_map(|l| l.strip_prefix("worktree "))
.map(PathBuf::from)
.filter(|p| *p != bare)
.collect();
let guard =
BusyGuard::acquire(&real_repo).map_err(|e| not(format!("repo busy (.grove-busy): {e}")))?;
if let Some(why) = in_progress(&real_repo, &wts) {
return Err(not(why));
}
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| not(format!("{}: {e}", parent.display())))?;
}
// A rename never copies: across file systems it fails and the repo stays where it was.
std::fs::rename(&real_repo, dest)
.map_err(|e| not(format!("cannot move to {}: {e}", dest.display())))?;
// The marker moved with the repo: the guard's old path is gone, remove the moved one.
drop(guard);
let _ = std::fs::remove_file(dest.join(".grove-busy"));
let real_dest = dest.canonicalize().unwrap_or_else(|_| dest.to_path_buf());
let mut moved = Moved::default();
let mut repair: Vec<String> = Vec::new();
for w in &wts {
let now = match w.strip_prefix(&real_repo) {
Ok(rel) => real_dest.join(rel),
Err(_) => w.clone(),
};
if now.exists() {
repair.push(now.display().to_string());
} else {
moved.unrepaired.push(now);
}
}
if !repair.is_empty() {
let mut args = vec!["worktree", "repair"];
args.extend(repair.iter().map(String::as_str));
Git::new(real_dest.join(".bare"))
.run(&args)
.map_err(|e| MoveError::Repair(e.to_string()))?;
}
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_tmp as tmp;
use grove_core::config::Provider as ProviderCfg;
use std::cell::Cell;
#[test]
fn only_not_found_style_fetch_errors_are_hints() {
assert!(looks_gone(
"git fetch failed (Some(128)): ERROR: Repository not found."
));
assert!(looks_gone(
"fatal: 'x.git' does not appear to be a git repository"
));
assert!(!looks_gone(
"ssh: connect to host h port 22: Connection timed out"
));
assert!(!looks_gone("fatal: Authentication failed"));
}
struct Fake {
login_ok: bool,
seen: Seen,
lookups: Cell<u32>,
}
impl Forge for Fake {
fn seen(&self, _: &str, _: &ProviderCfg, _: &str, _: &str) -> Result<Seen, String> {
self.lookups.set(self.lookups.get() + 1);
Ok(self.seen)
}
fn login(&self, _: &str, _: &ProviderCfg) -> Result<String, String> {
if self.login_ok {
Ok("me".into())
} else {
Err("401".into())
}
}
}
fn git(dir: &Path, args: &[&str]) {
Git::new(dir).run(args).unwrap();
}
/// `base/root/G/r` in bare layout with a `main` worktree and a linked one outside the repo.
fn bare_repo(base: &Path) -> (PathBuf, PathBuf) {
let repo = base.join("root/G/r");
std::fs::create_dir_all(&repo).unwrap();
let bare = repo.join(".bare");
git(
base,
&["init", "-q", "--bare", "-b", "main", bare.to_str().unwrap()],
);
git(
&bare,
&["remote", "add", "origin", "https://git.example.es/me/r.git"],
);
let main = repo.join("main");
git(
&bare,
&[
"worktree",
"add",
"-q",
"--orphan",
"-b",
"main",
main.to_str().unwrap(),
],
);
std::fs::write(main.join("f"), "x").unwrap();
git(&main, &["add", "f"]);
git(
&main,
&[
"-c",
"user.name=t",
"-c",
"user.email=t@t",
"commit",
"-qm",
"c",
],
);
let ext = base.join("elsewhere");
git(
&bare,
&["worktree", "add", "-q", "-b", "side", ext.to_str().unwrap()],
);
(repo, ext)
}
fn cfg() -> Config {
Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
)
.unwrap()
}
#[test]
fn a_404_counts_only_with_a_working_token() {
let d = tmp::TempDir::new("purge-confirm");
let (repo, _) = bare_repo(d.path());
let cfg = cfg();
let gone = |login_ok, seen| {
let f = Fake {
login_ok,
seen,
lookups: Cell::new(0),
};
confirmed_gone(&cfg, &repo, "origin", &f)
};
assert_eq!(gone(true, Seen::Absent), Ok(true));
assert_eq!(gone(true, Seen::Private), Ok(false));
assert!(gone(false, Seen::Absent).is_err());
// Someone else's repo (made private, access revoked) is never "gone".
git(
&repo.join(".bare"),
&[
"remote",
"set-url",
"origin",
"https://git.example.es/other/r.git",
],
);
let f = Fake {
login_ok: true,
seen: Seen::Absent,
lookups: Cell::new(0),
};
assert_eq!(confirmed_gone(&cfg, &repo, "origin", &f), Ok(false));
assert_eq!(f.lookups.get(), 0);
// ...unless the config names that organisation as an owner.
let org = Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n\
[[groups]]\nname=\"G\"\nprimary=\"gitea\"\nowners={gitea=\"Other\"}\n",
)
.unwrap();
assert_eq!(confirmed_gone(&org, &repo, "origin", &f), Ok(true));
}
#[test]
fn moving_keeps_every_worktree_working() {
let d = tmp::TempDir::new("purge-move");
let (repo, ext) = bare_repo(d.path());
let root = d.path().join("root");
let dest = destination(&root, "Purged", &repo, "1").unwrap();
assert_eq!(dest, root.join("Purged/G/r"));
move_repo(&repo, &dest).unwrap();
assert!(!repo.exists());
for wt in [dest.join("main"), ext.clone()] {
let st = Git::new(&wt).run(&["status", "--porcelain"]);
assert!(st.is_ok(), "{}: {st:?}", wt.display());
}
let list = Git::new(dest.join(".bare"))
.run(&["worktree", "list", "--porcelain"])
.unwrap();
assert!(list.contains(&dest.join("main").display().to_string()));
assert!(!list.contains("prunable"), "{list}");
// A second repo of the same name does not overwrite the first.
std::fs::create_dir_all(&repo).unwrap();
assert_eq!(
destination(&root, "Purged", &repo, "7").unwrap(),
root.join("Purged/G/r-7")
);
}
#[test]
fn moving_through_a_symlinked_root_repairs_the_worktrees() {
let d = tmp::TempDir::new("purge-symlink");
std::fs::create_dir_all(d.path().join("real")).unwrap();
std::os::unix::fs::symlink(d.path().join("real"), d.path().join("link")).unwrap();
let base = d.path().join("link");
let (repo, ext) = bare_repo(&base);
let dest = destination(&base.join("root"), "Purged", &repo, "1").unwrap();
let moved = move_repo(&repo, &dest).unwrap();
assert!(moved.unrepaired.is_empty());
for wt in [dest.join("main"), ext] {
assert!(Git::new(&wt).run(&["status"]).is_ok(), "{}", wt.display());
}
assert!(!dest.join(".grove-busy").exists());
}
#[test]
fn a_busy_repo_or_a_git_operation_in_progress_is_left_alone() {
let d = tmp::TempDir::new("purge-busy");
let (repo, _) = bare_repo(d.path());
let dest = d.path().join("root/Purged/G/r");
std::fs::write(repo.join(".grove-busy"), "1 1\n").unwrap();
assert!(matches!(
move_repo(&repo, &dest),
Err(MoveError::NotMoved(_))
));
std::fs::remove_file(repo.join(".grove-busy")).unwrap();
let gd = Git::new(repo.join("main"))
.run(&["rev-parse", "--absolute-git-dir"])
.unwrap();
std::fs::write(Path::new(&gd).join("MERGE_HEAD"), "x").unwrap();
assert!(matches!(
move_repo(&repo, &dest),
Err(MoveError::NotMoved(_))
));
assert!(repo.join(".bare").is_dir() && !dest.exists());
assert!(!repo.join(".grove-busy").exists());
}
}
+13 -4
View File
@@ -31,10 +31,19 @@ pub fn get(provider_id: &str) -> Result<String> {
return Ok(t.trim().to_string());
}
let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?;
match e.get_password() {
Ok(t) => Ok(t),
Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())),
Err(e) => Err(Error::Other(format!("secret service: {e}"))),
// A locked keyring may wait on an unlock dialog: never block the caller for longer than the
// forge CLIs get (the thread is left behind if the Secret Service never answers).
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(e.get_password());
});
match rx.recv_timeout(CLI_TIMEOUT) {
Ok(Ok(t)) => Ok(t),
Ok(Err(keyring::Error::NoEntry)) => Err(Error::NoToken(provider_id.into())),
Ok(Err(e)) => Err(Error::Other(format!("secret service: {e}"))),
Err(_) => Err(Error::Other(
"secret service did not answer in time (locked keyring?)".into(),
)),
}
}
+2 -8
View File
@@ -95,14 +95,8 @@ pub fn connect(cfg: &Config, id: &str) -> Result<Forge> {
/// 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 {
let mut env = grove_core::git::noninteractive_env();
if !grove_core::git::has_custom_ssh() {
env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into()));
}
env
+2
View File
@@ -5,3 +5,5 @@
3. Config: TOML for user intent (implemented); runtime state storage still open.
4. License: MIT (decided).
5. Final name: Grove (decided; binary `grove`, crates `grove-core` and `grove`).
6. Open: `groved` under systemd gets `PATH=/usr/local/bin:/usr/bin:/bin`, so a `tea`/`gh` in `~/.local/bin` is not found and the token lookup fails. Options: ship `Environment=PATH=%h/.local/bin:...` in `contrib/groved.service`, or resolve the helpers by absolute path (`~/.local/bin`, then `PATH`). Workaround in use: a user drop-in (see `two-pc-run.md`).
7. Open: `grove add` refuses `extensions.worktreeConfig = true` even when no `config.worktree` exists. Claude Code worktrees leave that flag behind. Options: accept it when no per-worktree config file exists (and sparse checkout is off), or keep refusing and print the exact `git config --unset` hint.
+32
View File
@@ -118,6 +118,38 @@ groups are only picked up then).
**Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading
`.`); a config with other names no longer loads.
### Repos deleted on the forge
A managed repo whose remote was deleted is moved out of the synced tree, never deleted locally:
```toml
[sync]
purged_dir = "Purged" # default; "" disables the move
```
- Trigger: a fetch fails with a "not found"-style error. That is only a hint: the forge serving
`origin` must then answer 404 while the same token works (`test_connection`), and still do so
`purge::CONFIRM_AFTER_SECS` (10 min) after the first confirmation (a gap of more than twice
that starts over). A working fetch, or the forge seeing the repo again, clears it. Network or
token errors change nothing.
- Only repos owned by the token's account, or by an organisation named in some group's `owners`
for that provider, are ever moved: someone else's repo turning private or revoking access looks
the same as a deletion. Being removed from one of your own `owners` organisations is still
indistinguishable and moves its repos.
- Never while busy: the move holds `.grove-busy` and is skipped (`purge_failed`, retried next
pass) when `.grove-stage` exists or a worktree has a git operation in progress (`index.lock`,
rebase, merge, cherry-pick, revert, bisect).
- Action: `root/<group>/<repo>` moves to `root/<purged_dir>/<group>/<repo>` (a `-<stamp>` suffix
if taken) by `rename` (same file system only; otherwise it stays and `purge_failed` is logged),
then `git worktree repair` fixes the in-repo and linked worktrees (paths compared after
resolving symlinks). Worktrees whose directory is missing at that moment are listed in the
`purged` entry for a later `git worktree repair`. The directory is not a configured group, so
the daemon stops syncing it.
- Activity log: `purge_pending` (first confirmation), `purged` (moved, with the destination),
`purge_failed` (not moved, with the reason).
- `purged_dir` must be a plain directory name and must not also be a group.
- The confirmation state is in memory: a daemon restart restarts the 10-minute wait.
### Snapshot policy
WIP snapshots (`refs/sync/<machine>/<branch>`) contain uncommitted work, so on a public repo anyone
+50
View File
@@ -0,0 +1,50 @@
# Real two-PC run
First real run on two machines, 16/11/2026: `Dasemu-LT` (laptop, already running Grove) and
`Dasemu-PC` (desktop, Fedora 44, KDE Plasma / Wayland, installed fresh from `development` at
`e6030f7`). Real forges: Gitea `git.zenvairo.es` (SSH on port 2222) and github.com, both with
`protocol = "ssh"`.
## Result
Passed. An uncommitted file in a private test repo on `Dasemu-PC` was snapshotted by the daemon
and pushed as `refs/sync/Dasemu-PC/main` (snapshot commit on top of `main`, containing only the
untracked file). On `Dasemu-LT`, after `grove import Darío <test repo>` and one daemon pass, the
snapshot showed up as `refs/sync-remote/Dasemu-PC/main`. The other direction was already visible
on real repos: `Academia-LMS` carries both `refs/sync/Dasemu-LT/feat/student-portal` and
`refs/sync/Dasemu-PC/feat/student-portal`. The throwaway repo was deleted from Gitea afterwards.
Notes:
- Right after `grove import`, the clone has no `refs/sync-remote/*` yet; they arrive with the
daemon's first pass over the new repo (up to `fetch_interval_s`, or `grove daemon sync PATH`).
- A repo created while the daemon runs is picked up (`repo_added`), but its worktree states only
appear after its first pass.
## Install on the second machine
`cargo test` passed; `grove`, `groved` and `grove-gui` installed with `cargo install --root ~/.local`.
`grove doctor` found both tokens (tea, gh). Migration of the existing `~/Hacking`:
- 14 plain clones migrated with `grove add`; 9 of them had a read-only Gitea pull mirror as
`origin` and were switched to their GitHub source (the `e6030f7` fix), Grove itself included.
- 19 missing repos cloned with `grove import`; 4 unversioned folders turned into repos with
`grove new` (2 public on GitHub with a Gitea mirror, 2 private on Gitea).
- First daemon pass: no `diverged`, 8 `dirty`, 2 `ahead`; 36 public repos report
`snapshots withheld` as intended.
## Problems found
1. **systemd PATH.** The user unit runs with `PATH=/usr/local/bin:/usr/bin:/bin`. `tea` lived in
`~/.local/bin`, so under systemd `groved` found no Gitea token (`grove doctor` run with that
PATH: `no token for provider "gitea"`). Worked around with a drop-in
`~/.config/systemd/user/groved.service.d/path.conf` setting
`Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin`. See `DECISIONS.md` (6).
2. **Leftover `extensions.worktreeConfig`.** Claude Code worktrees set
`extensions.worktreeConfig = true`; it stays after the worktrees are removed. `grove add`
refused 12 such clones ("sparse checkout / per-worktree config is not supported yet") although
none had a `config.worktree` file. Unsetting the extension (only when no `config.worktree`
exists and sparse checkout is off) let them migrate. See `DECISIONS.md` (7).
3. **Clones with a dirty linked worktree** still cannot be migrated (2 repos left as plain clones).
4. **Repos deleted on the forge after import** (2 on Gitea) make the daemon log a fetch error on
every pass. `development` now moves such repos to `Purged/` (PR #4); not part of this install.