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
This commit is contained in:
Claude committed 2026-11-16 21:41:56 +00:00
1 parent d281c91c30
commit e9ac627863
19 files changed
+1070 -19

No files matched your search

+63
View File
@@ -159,6 +159,14 @@ pub struct Sync {
/// 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 {
@@ -170,6 +178,8 @@ impl Default for Sync {
max_file_mb: default_max_file_mb(),
snapshots: SnapshotPolicy::default(),
purged_dir: default_purged_dir(),
prune_merged: true,
prune_disposable: default_disposable(),
}
}
}
@@ -192,6 +202,33 @@ fn default_max_file_mb() -> u64 {
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
}
@@ -296,6 +333,16 @@ impl Config {
));
}
}
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(['/', '\\']) {
@@ -404,6 +451,22 @@ 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";
+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![],
}
}