mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16:11 +00:00
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:
19 files changed
+1070
-19
No files matched your search
@@ -5,6 +5,7 @@ Linux tool that keeps chosen git repos continuously in sync across machines, inc
|
||||
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 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`, `two-pc-run.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.
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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}")),
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -16,6 +16,8 @@ fn opts(machine: &str, stamp: &str) -> Options {
|
||||
offline: false,
|
||||
materialize: true,
|
||||
push_snapshots: true,
|
||||
merged: vec![],
|
||||
disposable: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +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};
|
||||
@@ -427,8 +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;
|
||||
// Repos whose forge first confirmed their deletion at this time (see `purge`).
|
||||
let mut gone_since: HashMap<PathBuf, (u64, u64)> = HashMap::new();
|
||||
// Deletions being confirmed and merged pull requests, per repo.
|
||||
let mut forge = ForgeMemory::default();
|
||||
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
@@ -518,15 +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,
|
||||
&mut gone_since,
|
||||
&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);
|
||||
@@ -563,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,
|
||||
@@ -570,9 +573,10 @@ fn pass(
|
||||
st: &Settings,
|
||||
visibility: &mut Visibility,
|
||||
offline: bool,
|
||||
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
|
||||
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.
|
||||
@@ -603,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(),
|
||||
@@ -610,6 +630,8 @@ 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) {
|
||||
@@ -679,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) {
|
||||
|
||||
@@ -6,6 +6,7 @@ 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"]
|
||||
|
||||
@@ -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()]);
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
})
|
||||
}
|
||||
@@ -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`.
|
||||
|
||||
@@ -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, .. }
|
||||
));
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -7,3 +7,5 @@
|
||||
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.
|
||||
@@ -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.
|
||||
Reference in new issue
Block a user