mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 23:36:11 +00:00
feat(daemon): prune branches merged without a PR, protect long-lived ones
- Prune a worktree whose pushed tip a merge commit brought into the default branch (not on its first-parent history), with no forge needed. - Never prune or keep from materializing main/master/development/... plus sync.prune_protected; this also stops a development->main PR pruning development. - Follow repos transferred or renamed on the forge when listing merged PRs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c7899bcdc0
commit
a1646bccb7
12 files changed
+323
-49
No files matched your search
@@ -167,6 +167,19 @@ pub struct Sync {
|
||||
/// regenerable build output and dependency caches. Any other ignored file keeps it.
|
||||
#[serde(default = "default_disposable")]
|
||||
pub prune_disposable: Vec<String>,
|
||||
/// Extra branches never pruned, on top of the built-in long-lived ones
|
||||
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
|
||||
#[serde(default)]
|
||||
pub prune_protected: Vec<String>,
|
||||
}
|
||||
|
||||
impl Sync {
|
||||
/// Branches never pruned: the built-in long-lived ones plus `prune_protected`.
|
||||
pub fn protected_branches(&self) -> Vec<String> {
|
||||
let mut all = crate::prune::default_protected();
|
||||
all.extend(self.prune_protected.iter().cloned());
|
||||
all
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Sync {
|
||||
@@ -180,6 +193,7 @@ impl Default for Sync {
|
||||
purged_dir: default_purged_dir(),
|
||||
prune_merged: true,
|
||||
prune_disposable: default_disposable(),
|
||||
prune_protected: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -457,10 +471,19 @@ name = "grove-config"
|
||||
let c = Config::parse(base).unwrap();
|
||||
assert!(c.sync.prune_merged);
|
||||
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
|
||||
assert!(
|
||||
c.sync
|
||||
.protected_branches()
|
||||
.iter()
|
||||
.any(|b| b == "development")
|
||||
);
|
||||
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()]);
|
||||
let t = format!("{base}[sync]\nprune_protected=[\"release\"]\n");
|
||||
let p = Config::parse(&t).unwrap().sync.protected_branches();
|
||||
assert!(p.iter().any(|b| b == "release") && p.iter().any(|b| b == "main"));
|
||||
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
|
||||
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
|
||||
assert!(Config::parse(&t).is_err(), "{bad}");
|
||||
|
||||
+104
-26
@@ -1,11 +1,18 @@
|
||||
//! Removing worktrees whose work was merged through a pull request on the forge.
|
||||
//! Removing worktrees whose work is already merged.
|
||||
//!
|
||||
//! 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.
|
||||
//! A branch counts as merged when either
|
||||
//! - it is the head of a pull request merged on the forge and its tip is that head (or an
|
||||
//! ancestor of it): squash and rebase merges leave no ancestry, so the forge has to say so; or
|
||||
//! - it was merged without a pull request: its tip was pushed (`<remote>/<branch>` points at it),
|
||||
//! is a strict ancestor of `<remote>/<default>` and is not on its first-parent history (a
|
||||
//! merge commit brought it in). A branch created from the default branch with no commits of
|
||||
//! its own is on that history, so it never counts; neither does a fast-forward merge.
|
||||
//!
|
||||
//! Branches named in `sync.prune_protected` (long-lived ones such as `development`) and the
|
||||
//! default branch are never pruned. A worktree is removed only when 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;
|
||||
@@ -27,18 +34,42 @@ pub enum Pruned {
|
||||
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
|
||||
Removed {
|
||||
branch: String,
|
||||
pr: u64,
|
||||
/// The merged pull request; `None` when merged into the default branch without one.
|
||||
pr: Option<u64>,
|
||||
path: PathBuf,
|
||||
backup_ref: String,
|
||||
},
|
||||
/// Merged, but the worktree holds something that is not on the forge: kept.
|
||||
Kept {
|
||||
branch: String,
|
||||
pr: u64,
|
||||
pr: Option<u64>,
|
||||
why: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// How a pruned branch was merged, for messages ("merged in PR #3").
|
||||
pub fn merged_how(pr: Option<u64>) -> String {
|
||||
match pr {
|
||||
Some(n) => format!("merged in PR #{n}"),
|
||||
None => "merged into the default branch".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Long-lived branches that are never pruned; `sync.prune_protected` adds to them.
|
||||
pub fn default_protected() -> Vec<String> {
|
||||
[
|
||||
"main",
|
||||
"master",
|
||||
"development",
|
||||
"develop",
|
||||
"dev",
|
||||
"staging",
|
||||
"production",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
|
||||
const KIND: &str = "merged";
|
||||
|
||||
@@ -94,19 +125,54 @@ 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).
|
||||
fn resolve(g: &Git, r: &str) -> Option<String> {
|
||||
g.probe(&["rev-parse", "-q", "--verify", &format!("{r}^{{commit}}")])
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Merged without a pull request: `tip` was pushed as `<remote>/<branch>`, is a strict ancestor
|
||||
/// of `<remote>/<default>` and is not on its first-parent history (a merge commit brought it).
|
||||
fn merged_by_ancestry(g: &Git, remote: &str, default: &str, branch: &str, tip: &str) -> bool {
|
||||
let Some(base) = resolve(g, &format!("refs/remotes/{remote}/{default}")) else {
|
||||
return false;
|
||||
};
|
||||
resolve(g, &format!("refs/remotes/{remote}/{branch}")).as_deref() == Some(tip)
|
||||
&& base != tip
|
||||
&& is_ancestor(g, tip, &base)
|
||||
&& !on_first_parent_chain(g, tip, &base)
|
||||
}
|
||||
|
||||
/// True when `tip` is on the first-parent history of `base`: the default branch passed through
|
||||
/// it. That is a branch created from the default branch with no commits of its own (or merged
|
||||
/// by fast-forward, which the PR path still covers), so ancestry says nothing about a merge.
|
||||
fn on_first_parent_chain(g: &Git, tip: &str, base: &str) -> bool {
|
||||
// On error, assume it is (never prune on doubt).
|
||||
g.run(&["rev-list", "--first-parent", base])
|
||||
.map_or(true, |l| l.lines().any(|c| c == tip))
|
||||
}
|
||||
|
||||
/// What to prune and what to keep.
|
||||
pub struct Rules<'a> {
|
||||
/// Remote whose default branch and branches the ancestry rule compares against.
|
||||
pub remote: &'a str,
|
||||
/// Heads of pull requests merged on the forge (may be empty: unknown).
|
||||
pub merged: &'a [MergedHead],
|
||||
/// Ignored file/directory names that do not count as local work.
|
||||
pub disposable: &'a [String],
|
||||
/// Branch names never pruned.
|
||||
pub protected: &'a [String],
|
||||
}
|
||||
|
||||
/// Removes the worktrees of the bare-layout repo at `root` whose branch is already merged (see
|
||||
/// the module docs). Only worktrees inside `root` are touched, never the one of the default
|
||||
/// branch (`.bare`'s HEAD) nor protected branches.
|
||||
pub fn prune_merged(
|
||||
root: &Path,
|
||||
merged: &[MergedHead],
|
||||
disposable: &[String],
|
||||
rules: &Rules,
|
||||
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"])?;
|
||||
@@ -116,27 +182,37 @@ pub fn prune_merged(
|
||||
let Some(branch) = wt.branch.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
if default.as_deref() == Some(branch) || !wt.path.starts_with(&canonical_root) {
|
||||
if default.as_deref() == Some(branch)
|
||||
|| rules.protected.iter().any(|p| p == 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
|
||||
// The newest merged PR of this branch whose head contains the local tip, else a merge
|
||||
// without a PR.
|
||||
let pr = rules
|
||||
.merged
|
||||
.iter()
|
||||
.filter(|m| m.branch == branch)
|
||||
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
|
||||
else {
|
||||
.map(|m| m.number);
|
||||
if pr.is_none()
|
||||
&& !default
|
||||
.as_deref()
|
||||
.is_some_and(|d| merged_by_ancestry(&g, rules.remote, d, branch, &tip))
|
||||
{
|
||||
continue;
|
||||
};
|
||||
}
|
||||
if !wt.path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if let Some(why) = local_work(&wt.path, disposable)? {
|
||||
if let Some(why) = local_work(&wt.path, rules.disposable)? {
|
||||
out.push(Pruned::Kept {
|
||||
branch: branch.to_string(),
|
||||
pr: pr.number,
|
||||
pr,
|
||||
why,
|
||||
});
|
||||
continue;
|
||||
@@ -148,7 +224,7 @@ pub fn prune_merged(
|
||||
g.run(&["branch", "-D", branch])?;
|
||||
out.push(Pruned::Removed {
|
||||
branch: branch.to_string(),
|
||||
pr: pr.number,
|
||||
pr,
|
||||
path: wt.path.clone(),
|
||||
backup_ref: bref,
|
||||
});
|
||||
@@ -158,11 +234,12 @@ pub fn prune_merged(
|
||||
|
||||
/// 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.
|
||||
/// branch after the merge make it materialize again. Protected branches are never settled.
|
||||
pub fn settled_branches(
|
||||
bare: &Path,
|
||||
remote: &str,
|
||||
merged: &[MergedHead],
|
||||
protected: &[String],
|
||||
machine: &str,
|
||||
) -> Result<Vec<String>, GitError> {
|
||||
let g = Git::new(bare);
|
||||
@@ -186,6 +263,7 @@ pub fn settled_branches(
|
||||
.lines()
|
||||
.filter_map(|l| l.split_once(' '))
|
||||
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
|
||||
.filter(|(_, b)| !protected.iter().any(|p| p == b))
|
||||
.filter(|(sha, b)| {
|
||||
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|
||||
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use crate::git::{Git, GitError};
|
||||
use crate::inspect::{facts, state, worktrees};
|
||||
use crate::prune::{MergedHead, Pruned, prune_merged, settled_branches};
|
||||
use crate::prune::{MergedHead, Pruned, Rules, prune_merged, settled_branches};
|
||||
use crate::receive::{
|
||||
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
|
||||
materialize_except, push_snapshot, receive,
|
||||
@@ -32,6 +32,10 @@ pub struct Options {
|
||||
pub merged: Vec<MergedHead>,
|
||||
/// Names of ignored files/directories that do not count as local work when pruning.
|
||||
pub disposable: Vec<String>,
|
||||
/// Prune worktrees of merged branches (bare layout only, see `prune`).
|
||||
pub prune: bool,
|
||||
/// Branch names never pruned.
|
||||
pub protected: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -82,14 +86,20 @@ pub fn sync_repo(path: &Path, o: &Options) -> Result<SyncReport, GitError> {
|
||||
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
|
||||
}
|
||||
}
|
||||
if bare_layout && rep.fetch_error.is_none() && !o.offline {
|
||||
match prune_merged(path, &o.merged, &o.disposable, &o.machine, &o.stamp) {
|
||||
if bare_layout && o.prune && rep.fetch_error.is_none() && !o.offline {
|
||||
let rules = Rules {
|
||||
remote: &o.remote,
|
||||
merged: &o.merged,
|
||||
disposable: &o.disposable,
|
||||
protected: &o.protected,
|
||||
};
|
||||
match prune_merged(path, &rules, &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);
|
||||
let skip = settled_branches(&gitdir, &o.remote, &o.merged, &o.protected, &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}")),
|
||||
|
||||
Reference in new issue
Block a user