Compare commits

...
12 Commits
Author SHA1 Message Date
dasemu 206130df98 Merge pull request #7 from Dasemu/claude/funny-planck-2b88wj
feat(daemon): prune worktrees merged through a pull request
2026-11-16 22:46:15 +01:00
Claude e9ac627863 feat(daemon): prune worktrees merged through a pull request
The daemon asks the forge (GitHub, Gitea/Forgejo) which pull requests were
merged and removes the local worktree and branch of each merged head that
holds no local work. Squash/rebase merges and head branches kept on the
forge are covered; regenerable ignored output (target/, node_modules...)
does not keep a worktree, any other ignored file does. The tip is kept in a
refs/sync-backup/<machine>/<stamp>/merged/<branch> ref, and materialize no
longer brings a pruned branch back unless it gets new commits.

New config: sync.prune_merged (default true) and sync.prune_disposable.
See docs/prune-merged.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011GZUAKXXztS4Hy4F4sSRkc
2026-11-16 21:41:56 +00:00
dasemu d281c91c30 Merge pull request #6 from Dasemu/development
Development
2026-11-16 22:25:28 +01:00
dasemu 8cb87d9a37 Merge pull request #5 from Dasemu/docs/two-pc-run
docs: record the real two-PC run
2026-11-16 22:24:46 +01:00
dasemuandClaude Opus 5.5 ca8a2986dc docs: record the real two-PC run
Snapshot from Dasemu-PC reached Dasemu-LT as refs/sync-remote/Dasemu-PC/main.
Also logs the install on the second machine and two open questions
(systemd PATH for tea/gh, leftover extensions.worktreeConfig).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:23:31 +01:00
dasemu a5c7cc307b Merge pull request #4 from Dasemu/feat/purge-deleted-remotes
feat(daemon): move repos deleted on their forge to Purged/
2026-11-16 22:22:46 +01:00
dasemuandClaude Opus 5.5 d1d1fa29f3 feat(daemon): move repos deleted on their forge to Purged/
When a fetch fails with a not-found error, the daemon asks the forge:
a 404 for a repo owned by the token's account (or an `owners` org),
with a working token, still confirmed 10 min later, moves the repo to
root/<sync.purged_dir>/<group>/<repo> (default "Purged"), where it is
no longer synced. Never deleted; worktree links repaired; skipped while
busy or with a git operation in progress.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 22:22:31 +01:00
dasemu 9340a436d5 Merge pull request #3 from Dasemu/fix/daemon-detect-inplace-migration
fix(daemon): never block the sync loop on a prompt or a stuck git call
2026-11-16 22:00:06 +01:00
dasemuandClaude Opus 5.5 4c355b28ef fix(daemon): never block the sync loop on a prompt or a stuck git call
The daemon inherited the desktop session's SSH_ASKPASS (ksshaskpass), so
an ssh passphrase/host-key prompt opened a dialog nobody answered, and
git had no time limit: the single sync loop stalled for 1.5 h and repos
migrated meanwhile were never picked up.

- groved sets a non-interactive git env (no terminal/askpass prompts,
  HTTP low-speed abort) and leaves the ssh command to the user/repo.
- Git calls get an optional wall-clock limit (daemon: 900 s); on expiry
  the whole process group (git, ssh, helpers) is killed.
- Secret Service lookups time out like the forge CLIs (locked keyring).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:59:44 +01:00
dasemu d414862dec Merge pull request #2 from Dasemu/development
Development
2026-11-16 21:42:55 +01:00
dasemu 5f33bb9327 Merge pull request #1 from Dasemu/docs/github-primary
docs: GitHub is the primary remote
2026-11-16 21:37:06 +01:00
dasemuandClaude Opus 5.5 41e7c785af docs: GitHub is the primary remote, Gitea a pull mirror
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 21:36:27 +01:00
26 changed files with 1841 additions and 26 deletions

No files matched your search

+5 -4
View File
@@ -4,7 +4,8 @@
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`).
Worktrees merged through a PR on the forge are pruned by the daemon (`docs/prune-merged.md`).
Do not start new work before the previous results are written to `docs/`.
## Commands
@@ -17,7 +18,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`, `prune-merged.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.
@@ -28,8 +29,8 @@ user's branch or index.
- 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`.
## Workflow quirks
- Remote: Gitea `git.zenvairo.es`, owner `dasemu` (section `Darío`), CLI `tea`. SSH (port 22)
is unreachable from the dev machine; use HTTPS with `git -c credential.helper='!tea login helper'`.
- Remote: public GitHub `Dasemu/Grove` over SSH, CLI `gh`; PRs target `development` there.
`git.zenvairo.es/dasemu/Grove` is a read-only pull mirror of it (never push to it).
- In zsh, aliases like `g`/`gg` shadow shell functions; use unusual function names in scripts.
- Throwaway repos created on the real Gitea for tests must be deleted afterwards.
+102
View File
@@ -155,6 +155,18 @@ 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,
/// Remove worktrees whose branch was merged through a pull request on the forge (when they
/// hold no local work).
#[serde(default = "yes")]
pub prune_merged: bool,
/// Ignored files/directories (matched by name) that may be deleted with a pruned worktree:
/// regenerable build output and dependency caches. Any other ignored file keeps it.
#[serde(default = "default_disposable")]
pub prune_disposable: Vec<String>,
}
impl Default for Sync {
@@ -165,6 +177,9 @@ impl Default for Sync {
ignore_extra: Vec::new(),
max_file_mb: default_max_file_mb(),
snapshots: SnapshotPolicy::default(),
purged_dir: default_purged_dir(),
prune_merged: true,
prune_disposable: default_disposable(),
}
}
}
@@ -184,6 +199,36 @@ fn default_debounce() -> u64 {
fn default_max_file_mb() -> u64 {
50
}
fn default_purged_dir() -> String {
"Purged".into()
}
fn default_disposable() -> Vec<String> {
[
"target",
"node_modules",
".venv",
"venv",
"__pycache__",
".pytest_cache",
".mypy_cache",
".ruff_cache",
".tox",
".gradle",
".next",
".nuxt",
".svelte-kit",
".turbo",
".parcel-cache",
"dist",
"build",
"out",
"coverage",
".cache",
]
.into_iter()
.map(String::from)
.collect()
}
fn default_fetch() -> u64 {
60
}
@@ -275,6 +320,29 @@ 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"
));
}
}
if let Some(d) = self
.sync
.prune_disposable
.iter()
.find(|d| d.is_empty() || *d == "." || *d == ".." || d.contains(['/', '\\']))
{
return bad(format!(
"sync.prune_disposable entry {d:?} must be a plain file or directory name"
));
}
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 +451,40 @@ name = "grove-config"
assert_eq!(c.root_path(), PathBuf::from("/x"));
}
#[test]
fn prune_merged_defaults_on_and_disposable_names_are_plain() {
let base = "[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n";
let c = Config::parse(base).unwrap();
assert!(c.sync.prune_merged);
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
let own = format!("{base}[sync]\nprune_merged=false\nprune_disposable=[\"out\"]\n");
let c = Config::parse(&own).unwrap();
assert!(!c.sync.prune_merged);
assert_eq!(c.sync.prune_disposable, vec!["out".to_string()]);
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
assert!(Config::parse(&t).is_err(), "{bad}");
}
}
#[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"));
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod git;
pub mod inspect;
pub mod layout;
pub mod migrate;
pub mod prune;
pub mod receive;
pub mod registry;
pub mod resolve;
+195
View File
@@ -0,0 +1,195 @@
//! Removing worktrees whose work was merged through a pull request on the forge.
//!
//! The forge (not git ancestry) says what was merged: squash and rebase merges leave no
//! ancestry, and a branch freshly created from the default branch is an ancestor of it too.
//! A worktree is removed only when its branch is the head of a merged pull request, its tip is
//! that head (or an ancestor of it), and it holds no local work: no uncommitted or untracked
//! files, no ignored files other than regenerable ones (`sync.prune_disposable`), no git
//! operation in progress. The tip is kept under a backup ref before anything is removed.
use crate::git::{Git, GitError};
use crate::inspect::worktrees;
use crate::receive::backup_ref;
use std::path::{Path, PathBuf};
/// The head of a pull request merged on the forge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergedHead {
pub number: u64,
/// Branch name of the pull request's head (in the same repo; fork PRs are left out).
pub branch: String,
/// Commit the pull request's head pointed at when it was merged.
pub sha: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pruned {
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
Removed {
branch: String,
pr: u64,
path: PathBuf,
backup_ref: String,
},
/// Merged, but the worktree holds something that is not on the forge: kept.
Kept {
branch: String,
pr: u64,
why: String,
},
}
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
const KIND: &str = "merged";
/// An operation in progress in `worktree` that removing it would break.
pub fn operation_in_progress(worktree: &Path) -> Option<&'static str> {
let gd = Git::new(worktree)
.run(&["rev-parse", "--absolute-git-dir"])
.ok()?;
let gd = PathBuf::from(gd);
[
"index.lock",
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
]
.into_iter()
.find(|f| gd.join(f).exists())
}
/// Why `worktree` holds local work, if it does. Ignored entries whose last path component is
/// in `disposable` (build output, dependency caches) do not count.
fn local_work(worktree: &Path, disposable: &[String]) -> Result<Option<String>, GitError> {
if let Some(op) = operation_in_progress(worktree) {
return Ok(Some(format!("git operation in progress ({op})")));
}
let st = Git::new(worktree).run(&["status", "--porcelain", "--ignored", "-z"])?;
let mut kept = Vec::new();
for entry in st.split('\0').filter(|e| e.len() > 3) {
let (code, path) = entry.split_at(3);
if code != "!! " {
return Ok(Some("uncommitted or untracked changes".into()));
}
let last = path
.trim_end_matches('/')
.rsplit('/')
.next()
.unwrap_or(path);
if !disposable.iter().any(|d| d == last) {
kept.push(path.to_string());
}
}
if kept.is_empty() {
return Ok(None);
}
kept.truncate(5);
Ok(Some(format!("ignored files: {}", kept.join(", "))))
}
fn is_ancestor(g: &Git, a: &str, b: &str) -> bool {
matches!(g.probe(&["merge-base", "--is-ancestor", a, b]), Ok(Some(_)))
}
/// Removes the worktrees of the bare-layout repo at `root` whose branch was merged on the forge
/// (see the module docs). Only worktrees inside `root` are touched, never the one of the
/// default branch (`.bare`'s HEAD).
pub fn prune_merged(
root: &Path,
merged: &[MergedHead],
disposable: &[String],
machine: &str,
stamp: &str,
) -> Result<Vec<Pruned>, GitError> {
if merged.is_empty() {
return Ok(vec![]);
}
let bare = root.join(".bare");
let g = Git::new(&bare);
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
let canonical_root = root.canonicalize()?;
let mut out = Vec::new();
for wt in worktrees(&bare)? {
let Some(branch) = wt.branch.as_deref() else {
continue;
};
if default.as_deref() == Some(branch) || !wt.path.starts_with(&canonical_root) {
continue;
}
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
continue;
};
// The newest merged PR of this branch whose head contains the local tip.
let Some(pr) = merged
.iter()
.filter(|m| m.branch == branch)
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
else {
continue;
};
if !wt.path.is_dir() {
continue;
}
if let Some(why) = local_work(&wt.path, disposable)? {
out.push(Pruned::Kept {
branch: branch.to_string(),
pr: pr.number,
why,
});
continue;
}
let bref = backup_ref(machine, stamp, &format!("{KIND}/{branch}"));
g.run(&["update-ref", &bref, &tip])?;
// `--force`: the only files left are disposable ignored ones (checked above).
g.run(&["worktree", "remove", "--force", &wt.path.to_string_lossy()])?;
g.run(&["branch", "-D", branch])?;
out.push(Pruned::Removed {
branch: branch.to_string(),
pr: pr.number,
path: wt.path.clone(),
backup_ref: bref,
});
}
Ok(out)
}
/// Branches `materialize` must not bring back: the remote tip is the head of a merged PR, or
/// the tip this machine pruned (its `merged/<branch>` backup ref). New commits pushed to the
/// branch after the merge make it materialize again.
pub fn settled_branches(
bare: &Path,
remote: &str,
merged: &[MergedHead],
machine: &str,
) -> Result<Vec<String>, GitError> {
let g = Git::new(bare);
let backups = g.run(&[
"for-each-ref",
"--format=%(objectname) %(refname)",
&format!("refs/sync-backup/{machine}/"),
])?;
let pruned: Vec<(&str, &str)> = backups
.lines()
.filter_map(|l| l.split_once(' '))
.filter_map(|(sha, r)| {
let rest = r.strip_prefix(&format!("refs/sync-backup/{machine}/"))?;
let (_, kind) = rest.split_once('/')?;
Some((sha, kind.strip_prefix(&format!("{KIND}/"))?))
})
.collect();
let prefix = format!("refs/remotes/{remote}/");
let tips = g.run(&["for-each-ref", "--format=%(objectname) %(refname)", &prefix])?;
Ok(tips
.lines()
.filter_map(|l| l.split_once(' '))
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
.filter(|(sha, b)| {
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
})
.map(|(_, b)| b.to_string())
.collect())
}
+13 -1
View File
@@ -345,6 +345,15 @@ pub fn apply_snapshot(
/// Create worktrees under `root` for remote branches that have none. Returns new paths.
pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError> {
materialize_except(root, remote, &[])
}
/// Like [`materialize`], leaving out the branches in `skip` (e.g. merged ones that were pruned).
pub fn materialize_except(
root: &Path,
remote: &str,
skip: &[String],
) -> Result<Vec<PathBuf>, GitError> {
let bare = root.join(".bare");
let g = Git::new(&bare);
let prefix = format!("refs/remotes/{remote}/");
@@ -362,7 +371,10 @@ pub fn materialize(root: &Path, remote: &str) -> Result<Vec<PathBuf>, GitError>
let Some(branch) = r.strip_prefix(&prefix) else {
continue;
};
if branch == "HEAD" || existing_branches.iter().any(|b| b == branch) {
if branch == "HEAD"
|| existing_branches.iter().any(|b| b == branch)
|| skip.iter().any(|b| b == branch)
{
continue;
}
let refs: Vec<&str> = taken.iter().map(String::as_str).collect();
+21 -3
View File
@@ -1,11 +1,13 @@
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive.
//! One full sync pass over a repo: snapshot, push, fetch, receive, apply, materialize, archive,
//! prune merged.
//! Failures of individual steps are reported per worktree and never abort the whole pass.
use crate::git::{Git, GitError};
use crate::inspect::{facts, state, worktrees};
use crate::prune::{MergedHead, Pruned, prune_merged, settled_branches};
use crate::receive::{
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
materialize, push_snapshot, receive,
materialize_except, push_snapshot, receive,
};
use crate::snapshot::{Outcome, ref_name, take};
use crate::state::State;
@@ -24,6 +26,12 @@ pub struct Options {
/// repo, or `snapshots = "none"`) no `refs/sync/<machine>/*` ref is created or pushed;
/// fetching, fast-forwarding and applying other machines' snapshots are unaffected.
pub push_snapshots: bool,
/// Heads of pull requests merged on the forge (empty: unknown or pruning disabled).
/// Worktrees of those branches without local work are removed (bare layout only), and
/// `materialize` does not bring them back.
pub merged: Vec<MergedHead>,
/// Names of ignored files/directories that do not count as local work when pruning.
pub disposable: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -44,6 +52,7 @@ pub struct SyncReport {
pub fetch_error: Option<String>,
pub materialized: Vec<PathBuf>,
pub archived: Vec<Archived>,
pub pruned: Vec<Pruned>,
pub worktrees: Vec<WorktreeReport>,
}
@@ -72,7 +81,16 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
Ok(a) => rep.archived = a,
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
}
match materialize(path, &o.remote) {
}
if bare_layout && rep.fetch_error.is_none() && !o.offline {
match prune_merged(path, &o.merged, &o.disposable, &o.machine, &o.stamp) {
Ok(p) => rep.pruned = p,
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
}
}
if bare_layout && o.materialize && rep.fetch_error.is_none() {
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.machine);
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
Ok(m) => rep.materialized = m,
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
}
+224
View File
@@ -0,0 +1,224 @@
mod common;
use common::*;
use grove_core::git::Git;
use grove_core::migrate::migrate;
use grove_core::prune::{MergedHead, Pruned, prune_merged};
use grove_core::sync::{Options, sync_repo};
use std::fs;
use std::path::{Path, PathBuf};
struct World {
_tmp: tmp::TempDir,
base: PathBuf,
/// Another machine's plain clone (plays the forge user who merges).
dev: Git,
/// This machine's bare-layout repo.
root: PathBuf,
}
fn world() -> World {
let tmp = tmpdir("prune");
let base = tmp.to_path_buf();
let remote = base.join("remote.git");
Git::new(&base)
.run(&[
"init",
"-q",
"--bare",
"-b",
"main",
remote.to_str().unwrap(),
])
.unwrap();
let dev = init(&base.join("dev"));
dev.run(&["remote", "add", "origin", remote.to_str().unwrap()])
.unwrap();
commit(&dev, ".gitignore", "*.env\ntarget/\n");
dev.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
let d = base.join("me");
Git::new(&base)
.run(&["clone", "-q", remote.to_str().unwrap(), d.to_str().unwrap()])
.unwrap();
migrate(&d, "me", &base.join("bk"), "1").unwrap();
World {
_tmp: tmp,
base,
dev,
root: d.canonicalize().unwrap(),
}
}
fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
Options {
machine: "me".into(),
stamp: stamp.into(),
remote: "origin".into(),
offline: false,
materialize: true,
push_snapshots: false,
merged,
disposable: vec!["target".into()],
}
}
/// Pushes branch `b` with one commit from `dev` and returns its tip.
fn push_branch(w: &World, b: &str) -> String {
w.dev.run(&["checkout", "-q", "-b", b, "main"]).unwrap();
commit(&w.dev, &format!("{}.txt", b.replace('/', "-")), "x\n");
w.dev.run(&["push", "-q", "-u", "origin", b]).unwrap();
let tip = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
w.dev.run(&["checkout", "-q", "main"]).unwrap();
tip
}
/// A squash merge: the branch's content lands on main as a new commit (no ancestry), and the
/// head branch stays on the remote.
fn squash_merge(w: &World, b: &str) {
w.dev.run(&["merge", "-q", "--squash", b]).unwrap();
w.dev.run(&["commit", "-qm", "squash"]).unwrap();
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
}
fn head(n: u64, branch: &str, sha: &str) -> MergedHead {
MergedHead {
number: n,
branch: branch.into(),
sha: sha.into(),
}
}
fn has_branch(root: &Path, b: &str) -> bool {
Git::new(root.join(".bare"))
.probe(&["rev-parse", "-q", "--verify", &format!("refs/heads/{b}")])
.unwrap()
.is_some()
}
#[test]
fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
let w = world();
let tip = push_branch(&w, "feat/x");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
let wt = w.root.join("feat-x");
assert!(wt.exists());
// Build output is regenerable: it does not keep the worktree.
fs::create_dir_all(wt.join("target/debug")).unwrap();
fs::write(wt.join("target/debug/bin"), "b").unwrap();
squash_merge(&w, "feat/x");
let rep = sync_repo(&w.root, &opts("s2", vec![head(7, "feat/x", &tip)])).unwrap();
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
let [
Pruned::Removed {
branch,
pr,
backup_ref,
..
},
] = rep.pruned.as_slice()
else {
panic!("{:?}", rep.pruned);
};
assert_eq!((branch.as_str(), *pr), ("feat/x", 7));
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
let bare = Git::new(w.root.join(".bare"));
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
assert!(rep.materialized.is_empty(), "{:?}", rep.materialized);
// The remote branch is still there; later passes (even without a forge answer) leave it.
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
assert!(rep.materialized.is_empty() && !wt.exists());
// New commits on the branch after the merge are new work: it comes back.
w.dev.run(&["checkout", "-q", "feat/x"]).unwrap();
commit(&w.dev, "more.txt", "m\n");
w.dev.run(&["push", "-q", "origin", "feat/x"]).unwrap();
let rep = sync_repo(&w.root, &opts("s4", vec![head(7, "feat/x", &tip)])).unwrap();
assert_eq!(rep.materialized, vec![wt.clone()]);
assert!(rep.pruned.is_empty());
}
#[test]
fn local_work_keeps_a_merged_worktree() {
let w = world();
let tip = push_branch(&w, "a");
let tip_b = push_branch(&w, "b");
let tip_c = push_branch(&w, "c");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
fs::write(w.root.join("a/new.txt"), "untracked\n").unwrap();
fs::write(w.root.join("b/secret.env"), "ignored, not regenerable\n").unwrap();
// A local commit the merged PR does not have.
let gc = Git::new(w.root.join("c"));
gc.run(&["config", "user.email", "t@t"]).unwrap();
gc.run(&["config", "user.name", "t"]).unwrap();
commit(&gc, "local.txt", "l\n");
let merged = vec![
head(1, "a", &tip),
head(2, "b", &tip_b),
head(3, "c", &tip_c),
];
let rep = sync_repo(&w.root, &opts("s2", merged)).unwrap();
let mut kept: Vec<(String, String)> = rep
.pruned
.iter()
.map(|p| match p {
Pruned::Kept { branch, why, .. } => (branch.clone(), why.clone()),
other => panic!("{other:?}"),
})
.collect();
kept.sort();
assert_eq!(
kept,
vec![
("a".into(), "uncommitted or untracked changes".into()),
("b".into(), "ignored files: secret.env".into()),
]
);
for b in ["a", "b", "c"] {
assert!(w.root.join(b).exists() && has_branch(&w.root, b), "{b}");
}
}
#[test]
fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are() {
let w = world();
let first = push_branch(&w, "f");
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
// The PR got more commits (from another machine) before it was merged.
w.dev.run(&["checkout", "-q", "f"]).unwrap();
commit(&w.dev, "f2.txt", "2\n");
w.dev.run(&["push", "-q", "origin", "f"]).unwrap();
let last = w.dev.run(&["rev-parse", "HEAD"]).unwrap();
w.dev.run(&["checkout", "-q", "main"]).unwrap();
assert_ne!(first, last);
// A linked worktree outside the repo directory is the user's.
let ext = w.base.join("elsewhere");
let bare = Git::new(w.root.join(".bare"));
let tip_o = push_branch(&w, "o");
bare.run(&["fetch", "-q", "origin"]).unwrap();
bare.run(&[
"worktree",
"add",
"-q",
"-b",
"o",
ext.to_str().unwrap(),
"origin/o",
])
.unwrap();
let main_tip = bare.run(&["rev-parse", "refs/heads/main"]).unwrap();
// `prune_merged` alone: `f` is still at `first` locally (no fetch/fast-forward).
let merged = vec![
head(4, "f", &last),
head(5, "main", &main_tip),
head(6, "o", &tip_o),
];
let pruned = prune_merged(&w.root, &merged, &[], "me", "t").unwrap();
assert!(
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: 4, .. }] if branch == "f"),
"{pruned:?}"
);
assert!(w.root.join("main").exists() && ext.exists());
}
+2
View File
@@ -386,6 +386,8 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
offline: false,
materialize: true,
push_snapshots: true,
merged: vec![],
disposable: vec![],
};
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
commit(&w.g1, "z.txt", "z\n");
+2
View File
@@ -16,6 +16,8 @@ fn opts(machine: &str, stamp: &str) -> Options {
offline: false,
materialize: true,
push_snapshots: true,
merged: vec![],
disposable: vec![],
}
}
+170 -1
View File
@@ -5,8 +5,11 @@
use crate::activity::{Activity, now_secs};
use crate::discover::{discover, group_of, is_ready, subdirs};
use crate::ipc;
use crate::merged::{MergedCache, has_candidates};
use crate::purge;
use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config;
use grove_core::prune::Pruned;
use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher};
@@ -426,6 +429,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;
// Deletions being confirmed and merged pull requests, per repo.
let mut forge = ForgeMemory::default();
loop {
let now = Instant::now();
@@ -515,7 +520,7 @@ 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 forge, &ctx);
if !is_ready(&r) {
// It vanished mid-pass: whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
@@ -552,6 +557,15 @@ fn forget_removed(
backoff_until.retain(|r, _| found.contains(r));
}
/// What the daemon remembers between passes about each repo's forge (in memory only).
#[derive(Default)]
struct ForgeMemory {
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
gone_since: HashMap<PathBuf, (u64, u64)>,
/// Merged pull requests per repo (see `merged`).
merged: MergedCache,
}
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
fn pass(
repo: &Path,
@@ -559,8 +573,10 @@ fn pass(
st: &Settings,
visibility: &mut Visibility,
offline: bool,
forge: &mut ForgeMemory,
ctx: &Ctx,
) -> u32 {
let ForgeMemory { gone_since, merged } = forge;
let name = repo.display().to_string();
if !is_ready(repo) {
// Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out.
@@ -591,6 +607,22 @@ fn pass(
}
allowed
};
// Offline passes prune nothing; the last answer still keeps pruned branches away.
let merged_heads = if !cfg.sync.prune_merged || !has_candidates(repo) {
Vec::new()
} else if offline {
merged.cached(repo)
} else {
let h = merged.heads(cfg, repo, &st.remote, &RealForge, Instant::now());
if let Some(e) = h.new_error {
ctx.activity.log(
"prune_lookup_failed",
Some(&name),
format!("cannot list merged pull requests: {e}"),
);
}
h.heads
};
let opts = Options {
machine: cfg.machine.name.clone(),
stamp: stamp(),
@@ -598,8 +630,13 @@ fn pass(
offline,
materialize,
push_snapshots,
merged: merged_heads,
disposable: cfg.sync.prune_disposable.clone(),
};
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 {
@@ -664,6 +701,30 @@ fn pass(
for a in &rep.archived {
ctx.activity.log("archived", Some(&name), format!("{a:?}"));
}
let mut kept = Vec::new();
for p in &rep.pruned {
match p {
Pruned::Removed {
branch,
pr,
path,
backup_ref,
} => ctx.activity.log(
"pruned_merged",
Some(&name),
format!(
"{branch}: merged in PR #{pr}; removed {} (tip kept in {backup_ref})",
path.display()
),
),
Pruned::Kept { branch, pr, why } => {
kept.push(format!("{branch}: merged in PR #{pr} but kept: {why}"))
}
}
}
for k in merged.new_notes(repo, kept) {
ctx.activity.log("prune_kept", Some(&name), k);
}
}
}
if !errors.is_empty() && !is_ready(repo) {
@@ -693,6 +754,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();
+2
View File
@@ -6,6 +6,8 @@ pub mod activity;
pub mod daemon;
pub mod discover;
pub mod ipc;
pub mod merged;
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 {}",
+245
View File
@@ -0,0 +1,245 @@
//! Which branches of a repo were merged through a pull request on its forge (`origin`), so
//! that their worktrees can be pruned (`grove_core::prune`).
//!
//! The daemon asks the forge at most every [`TTL`] per repo, and only for repos that have a
//! worktree on a branch other than the default one. A failed lookup keeps the last answer, so a
//! forge outage never makes `materialize` bring back worktrees that were pruned.
use crate::visibility::{RealForge, parse_remote, provider_for};
use grove_core::config::{Config, Provider as ProviderCfg};
use grove_core::git::Git;
use grove_core::inspect::worktrees;
use grove_core::prune::MergedHead;
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
/// How long a forge answer is reused.
pub const TTL: Duration = Duration::from_secs(300);
/// Lists the merged pull requests of a repo on a forge.
pub trait PullSource {
fn merged(
&self,
id: &str,
pc: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String>;
}
impl PullSource for RealForge {
fn merged(
&self,
id: &str,
pc: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String> {
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
let pulls = grove_providers::build(pc, token)
.merged_pulls(owner, name)
.map_err(|e| e.to_string())?;
Ok(pulls
.into_iter()
.map(|p| MergedHead {
number: p.number,
branch: p.head_ref,
sha: p.head_sha,
})
.collect())
}
}
/// The merged pull requests of the repo at `repo` (bare layout), looked up on the forge that
/// serves its `remote` fetch URL.
pub fn lookup(
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
) -> Result<Vec<MergedHead>, 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)?;
src.merged(pid, pc, &id.owner, &id.name)
}
/// True when the repo has a worktree on a branch other than `.bare`'s HEAD: only then can
/// anything be pruned, so only then is the forge asked.
pub fn has_candidates(repo: &Path) -> bool {
let bare = repo.join(".bare");
let default = Git::new(&bare)
.probe(&["symbolic-ref", "--short", "-q", "HEAD"])
.ok()
.flatten();
worktrees(&bare).is_ok_and(|wts| {
wts.iter()
.filter_map(|w| w.branch.as_deref())
.any(|b| Some(b) != default.as_deref())
})
}
#[derive(Default)]
struct Entry {
checked: Option<Instant>,
heads: Vec<MergedHead>,
error: Option<String>,
/// "Kept" notes already logged, so a merged worktree with local work is reported once.
noted: BTreeSet<String>,
}
/// Per-repo forge answers and notes, held by the daemon loop (in memory only).
#[derive(Default)]
pub struct MergedCache {
entries: HashMap<PathBuf, Entry>,
}
/// Result of [`MergedCache::heads`].
pub struct Heads {
pub heads: Vec<MergedHead>,
/// A lookup error that differs from the previous one (to be logged once).
pub new_error: Option<String>,
}
impl MergedCache {
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
pub fn heads(
&mut self,
cfg: &Config,
repo: &Path,
remote: &str,
src: &dyn PullSource,
now: Instant,
) -> Heads {
let e = self.entries.entry(repo.to_path_buf()).or_default();
if e.checked
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
{
return Heads {
heads: e.heads.clone(),
new_error: None,
};
}
e.checked = Some(now);
let mut new_error = None;
match lookup(cfg, repo, remote, src) {
Ok(h) => {
e.heads = h;
e.error = None;
}
Err(err) => {
if e.error.as_deref() != Some(&err) {
new_error = Some(err.clone());
}
e.error = Some(err);
}
}
Heads {
heads: e.heads.clone(),
new_error,
}
}
/// Of the "kept" notes of this pass, those not logged yet for `repo`. Notes that no longer
/// apply are forgotten, so they are logged again if they come back.
pub fn new_notes(&mut self, repo: &Path, notes: Vec<String>) -> Vec<String> {
let e = self.entries.entry(repo.to_path_buf()).or_default();
let now: BTreeSet<String> = notes.into_iter().collect();
let fresh = now.difference(&e.noted).cloned().collect();
e.noted = now;
fresh
}
/// The last answer for `repo`, without asking the forge (offline passes).
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
self.entries
.get(repo)
.map(|e| e.heads.clone())
.unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_tmp as tmp;
use std::cell::{Cell, RefCell};
struct Fake {
calls: Cell<u32>,
asked: RefCell<Vec<String>>,
answer: RefCell<Result<Vec<MergedHead>, String>>,
}
impl PullSource for Fake {
fn merged(
&self,
id: &str,
_: &ProviderCfg,
owner: &str,
name: &str,
) -> Result<Vec<MergedHead>, String> {
self.calls.set(self.calls.get() + 1);
self.asked.borrow_mut().push(format!("{id}:{owner}/{name}"));
self.answer.borrow().clone()
}
}
fn head(n: u64) -> MergedHead {
MergedHead {
number: n,
branch: format!("b{n}"),
sha: "0".repeat(40),
}
}
#[test]
fn answers_are_cached_and_kept_on_failure() {
let d = tmp::TempDir::new("merged-cache");
let repo = d.path().join("G/r");
std::fs::create_dir_all(&repo).unwrap();
let bare = repo.join(".bare");
Git::new(d.path())
.run(&["init", "-q", "--bare", bare.to_str().unwrap()])
.unwrap();
Git::new(&bare)
.run(&["remote", "add", "origin", "git@git.example.es:Org/r.git"])
.unwrap();
let cfg = Config::parse(
"[machine]\nname=\"m\"\n[root]\npath=\"/x\"\n\
[providers.gitea]\nkind=\"gitea\"\nurl=\"https://git.example.es\"\n",
)
.unwrap();
let f = Fake {
calls: Cell::new(0),
asked: RefCell::new(vec![]),
answer: RefCell::new(Ok(vec![head(1)])),
};
let mut c = MergedCache::default();
let t0 = Instant::now();
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
// Within the TTL the forge is not asked again.
c.heads(&cfg, &repo, "origin", &f, t0 + Duration::from_secs(10));
assert_eq!(f.calls.get(), 1);
// A failure keeps the last answer and is reported once.
*f.answer.borrow_mut() = Err("down".into());
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL);
assert_eq!((h.heads, h.new_error), (vec![head(1)], Some("down".into())));
let h = c.heads(&cfg, &repo, "origin", &f, t0 + TTL * 2);
assert_eq!((h.heads, h.new_error), (vec![head(1)], None));
assert_eq!(f.calls.get(), 3);
}
#[test]
fn notes_are_reported_once_while_they_hold() {
let mut c = MergedCache::default();
let r = Path::new("/r");
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
assert!(c.new_notes(r, vec![]).is_empty());
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
}
}
+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());
}
}
+22 -1
View File
@@ -1,6 +1,7 @@
use crate::http::Http;
use crate::{
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
Result, same_repo,
};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
@@ -156,4 +157,24 @@ impl Provider for Gitea {
Some(&body),
)?))
}
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
let v = self.http.ok(
"GET",
&format!("/repos/{owner}/{name}/pulls?state=closed&sort=recentupdate&limit=50"),
None,
)?;
Ok(v.as_array()
.into_iter()
.flatten()
.filter(|p| p["merged"].as_bool() == Some(true) && same_repo(p))
.filter_map(|p| {
Some(MergedPull {
number: p["number"].as_u64()?,
head_ref: p["head"]["ref"].as_str()?.to_string(),
head_sha: p["head"]["sha"].as_str()?.to_string(),
})
})
.collect())
}
}
+26 -1
View File
@@ -1,6 +1,7 @@
use crate::http::Http;
use crate::{
Capabilities, Error, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo, Result,
Capabilities, Error, MergedPull, MirrorSpec, NewRepo, Provider, PullMirrorSpec, RemoteRepo,
Result, same_repo,
};
use grove_core::config::ProviderKind;
use serde_json::{Value, json};
@@ -138,4 +139,28 @@ impl Provider for GitHub {
"GitHub cannot pull-mirror another forge",
))
}
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>> {
let v = self.http.ok(
"GET",
&format!(
"/repos/{owner}/{name}/pulls?state=closed&sort=updated&direction=desc&per_page=100"
),
None,
)?;
Ok(v.as_array()
.into_iter()
.flatten()
.filter(|p| p["merged_at"].is_string() && same_repo(p))
.filter_map(pull)
.collect())
}
}
fn pull(p: &Value) -> Option<MergedPull> {
Some(MergedPull {
number: p["number"].as_u64()?,
head_ref: p["head"]["ref"].as_str()?.to_string(),
head_sha: p["head"]["sha"].as_str()?.to_string(),
})
}
+22
View File
@@ -119,6 +119,25 @@ pub struct PullMirrorSpec {
pub interval: String,
}
/// A pull request merged on the forge whose head branch is in the same repo.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergedPull {
pub number: u64,
pub head_ref: String,
pub head_sha: String,
}
/// Head repo of a pull request equals its base repo (fork PRs reuse branch names freely).
/// A head repo that was deleted reports `null`: not the same repo.
pub(crate) fn same_repo(pr: &serde_json::Value) -> bool {
let name = |side: &str| {
pr[side]["repo"]["full_name"]
.as_str()
.map(str::to_ascii_lowercase)
};
matches!((name("head"), name("base")), (Some(h), Some(b)) if h == b)
}
pub trait Provider: Send + Sync {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
@@ -134,6 +153,9 @@ pub trait Provider: Send + Sync {
fn configure_mirror(&self, owner: &str, repo: &str, spec: &MirrorSpec) -> Result<()>;
/// Creates a pull mirror (see [`Capabilities::pull_mirror`]).
fn create_pull_mirror(&self, spec: &PullMirrorSpec) -> Result<RemoteRepo>;
/// The most recently updated closed pull requests (one page) that were merged, newest
/// first, leaving out those whose head is in a fork.
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
}
/// Builds the provider described by `cfg`, using `token`.
+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(),
)),
}
}
+45
View File
@@ -481,3 +481,48 @@ fn git_url_follows_the_protocol_and_needs_an_ssh_url_for_ssh() {
);
assert!(r[1].git_url(Protocol::Ssh).is_err());
}
#[test]
fn merged_pulls_keep_only_merged_same_repo_heads() {
// Merged, closed without merging, merged from a fork, merged from a deleted fork.
let gitea = r#"[
{"number":3,"merged":true,"head":{"ref":"feat/a","sha":"aaa","repo":{"full_name":"O/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":2,"merged":false,"head":{"ref":"b","sha":"bbb","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":1,"merged":true,"head":{"ref":"c","sha":"ccc","repo":{"full_name":"x/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":0,"merged":true,"head":{"ref":"d","sha":"ddd","repo":null},"base":{"repo":{"full_name":"o/r"}}}
]"#;
let (url, rx) = mock(vec![(200, gitea)]);
let pulls = Gitea::new(ProviderKind::Forgejo, &url, "t".into())
.merged_pulls("o", "r")
.unwrap();
assert!(
rx.recv()
.unwrap()
.starts_with("GET /api/v1/repos/o/r/pulls?state=closed&sort=recentupdate&limit=50 ")
);
assert_eq!(pulls.len(), 1);
assert_eq!(
(
pulls[0].number,
pulls[0].head_ref.as_str(),
pulls[0].head_sha.as_str()
),
(3, "feat/a", "aaa")
);
let github = r#"[
{"number":9,"merged_at":"2026-01-01T00:00:00Z","head":{"ref":"x","sha":"999","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}},
{"number":8,"merged_at":null,"head":{"ref":"y","sha":"888","repo":{"full_name":"o/r"}},"base":{"repo":{"full_name":"o/r"}}}
]"#;
let (url, rx) = mock(vec![(200, github), (404, r#"{"message":"Not Found"}"#)]);
let gh = GitHub::new(&url, "t".into());
let pulls = gh.merged_pulls("o", "r").unwrap();
assert!(rx.recv().unwrap().starts_with(
"GET /repos/o/r/pulls?state=closed&sort=updated&direction=desc&per_page=100 "
));
assert_eq!(pulls.iter().map(|p| p.number).collect::<Vec<_>>(), vec![9]);
assert!(matches!(
gh.merged_pulls("o", "gone").unwrap_err(),
Error::Api { status: 404, .. }
));
}
+34
View File
@@ -4,6 +4,7 @@ use grove_core::config::{Config, ProviderKind};
use grove_core::git::Git;
use grove_core::inspect::{state, worktrees};
use grove_core::migrate::migrate;
use grove_core::prune::Pruned;
use grove_core::receive::{Applied, Archived, Received};
use grove_core::resolve::{Choice, resolve};
use grove_core::snapshot::{Outcome, take};
@@ -345,6 +346,21 @@ fn main() -> Result<()> {
Cmd::Sync { path, offline } => {
let cfg = load_config(&cli.config)?;
grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024);
// Merged pull requests, for pruning (bare layout only; best effort).
let merged = if *offline || !cfg.sync.prune_merged || !path.join(".bare").is_dir() {
Vec::new()
} else {
grove_daemon::merged::lookup(
&cfg,
path,
"origin",
&grove_daemon::visibility::RealForge,
)
.unwrap_or_else(|e| {
eprintln!("grove: cannot list merged pull requests: {e}");
Vec::new()
})
};
let rep = sync_repo(
path,
&Options {
@@ -359,6 +375,8 @@ fn main() -> Result<()> {
.and_then(|g| cfg.groups.iter().find(|x| x.name == g))
.is_none_or(|g| g.auto_materialize),
push_snapshots: true,
merged,
disposable: cfg.sync.prune_disposable.clone(),
},
)?;
print_report(&rep)
@@ -505,6 +523,22 @@ fn print_report(rep: &SyncReport) -> Result<()> {
}
}
}
for p in &rep.pruned {
match p {
Pruned::Removed {
branch,
pr,
path,
backup_ref,
} => println!(
"pruned {branch}: merged in PR #{pr}, removed {} (backup {backup_ref})",
path.display()
),
Pruned::Kept { branch, pr, why } => {
println!("kept {branch}: merged in PR #{pr} but {why}")
}
}
}
for w in &rep.worktrees {
let branch = w.branch.as_deref().unwrap_or("(detached)");
let mut notes = Vec::new();
+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
+4
View File
@@ -5,3 +5,7 @@
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.
8. Merged worktrees are pruned (`prune-merged.md`), but the PR's head branch is left on the forge and this machine's `refs/sync/<machine>/<branch>` snapshot ref stays there too. Open: should grove delete either once the PR is merged (the forge's "delete branch after merge" covers the first)?
9. Open: a branch recreated under the name of a fast-forward-merged PR before the default branch moves has the PR head as tip and is pruned at once if clean (nothing is lost; a backup ref is kept). Options: accept it, or require the worktree to be older than the merge.
+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
+92
View File
@@ -0,0 +1,92 @@
# Pruning worktrees merged through a pull request
Worktrees of branches that were pushed, reviewed in a pull request and merged used to stay
forever: `archive_gone` only removes a worktree when its remote branch is deleted, the forge
often keeps the head branch, squash and rebase merges leave no ancestry for git to see, and a
Rust/Node worktree always holds ignored build output that kept it "dirty". The daemon now asks
the forge which pull requests were merged and removes those worktrees itself.
## Config
```toml
[sync]
prune_merged = true # default
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
```
- `prune_merged = false` turns the feature off.
- `prune_disposable`: names (not paths, not globs) of ignored files/directories that are
regenerable and may go with a pruned worktree. Entries must be plain names.
## What counts as merged
`Provider::merged_pulls(owner, repo)` lists one page of the most recently updated closed pull
requests (GitHub: 100, `merged_at` set; Gitea/Forgejo: 50, `merged: true`), keeping only those
whose head repo is the base repo: fork PRs reuse branch names freely. The repo is found from
`origin`'s fetch URL, matched to a configured provider like the visibility check (`phase6.md`),
with the token from `token::resolve`.
## When a worktree is removed
All of these must hold (`grove_core::prune::prune_merged`):
1. The repo is bare layout, the fetch of this pass worked, and the pass is not offline.
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch), and it lives
inside the repo directory (`root/<group>/<repo>/...`, so nested ones such as
`main/.claude/worktrees/x` count). Linked worktrees elsewhere are the user's and are never
touched.
3. A merged PR has that branch as head and its head commit equals the local tip, or contains it
(the PR got more commits from another machine before the merge).
4. No local work: no staged, modified or untracked file, no git operation in progress
(`index.lock`, rebase, merge, cherry-pick, revert, bisect), and no ignored entry whose name
is not in `prune_disposable` (`.env` keeps it, `target/` does not).
Then the tip is saved under `refs/sync-backup/<machine>/<stamp>/merged/<branch>`, the worktree
is removed (`git worktree remove --force`, needed for the disposable ignored files only) and the
local branch is deleted. Nothing on the forge changes: the remote branch, if any, stays.
A merged worktree with local work is kept and reported, once per change, as `prune_kept`
(`feat/x: merged in PR #12 but kept: ignored files: .env`).
## Not brought back by `auto_materialize`
`materialize` creates a worktree for every remote branch without one, so a pruned branch whose
head was not deleted on the forge would come back on the next pass. It now skips a remote
branch whose tip is the head of a merged PR or the tip this machine pruned (its `merged/` backup
ref), so this holds also offline or when the forge cannot be asked. New commits pushed to the
branch after the merge are new work: the worktree is materialized again.
## Daemon
- The forge is asked at most every 5 minutes per repo, and only when the repo has a worktree
on a non-default branch. The answer is in memory only.
- A failed lookup keeps the last answer and is logged once as `prune_lookup_failed` (until the
error changes).
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
from being materialized.
- Activity log: `pruned_merged` (removed, with the PR, path and backup ref) and `prune_kept`.
`grove sync <path>` does the same in one shot (no cache) and prints `pruned ...` / `kept ...`
lines; a failed lookup is a warning and prunes nothing.
## Validation
- `grove-core/tests/prune.rs`: squash merge with the head branch kept on the remote (pruned with
`target/` present, backup ref, not re-materialized with or without a forge answer, comes back
after a new commit), local work (untracked file, non-disposable ignored file, local commit)
keeps the worktree, an older tip contained in the PR head is pruned, the default branch and a
linked worktree outside the repo are never touched.
- `grove-providers/tests/api.rs`: request shape on both forges, only merged same-repo PRs kept
(fork and deleted-fork heads left out), API errors surface.
- `grove-daemon` `merged` unit tests: TTL cache, last answer kept on failure, error and kept
notes logged once.
- Config: defaults and validation of `prune_disposable`.
## Not verified
- Against a real GitHub or Gitea (mock-tested only).
- Only the first page of closed PRs is read: a branch merged long ago in a busy repo (more than
100 / 50 PRs closed since) is not found. `grove sync` on it does not help either; remove it by
hand.
+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.