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.
|
/// regenerable build output and dependency caches. Any other ignored file keeps it.
|
||||||
#[serde(default = "default_disposable")]
|
#[serde(default = "default_disposable")]
|
||||||
pub prune_disposable: Vec<String>,
|
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 {
|
impl Default for Sync {
|
||||||
@@ -180,6 +193,7 @@ impl Default for Sync {
|
|||||||
purged_dir: default_purged_dir(),
|
purged_dir: default_purged_dir(),
|
||||||
prune_merged: true,
|
prune_merged: true,
|
||||||
prune_disposable: default_disposable(),
|
prune_disposable: default_disposable(),
|
||||||
|
prune_protected: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -457,10 +471,19 @@ name = "grove-config"
|
|||||||
let c = Config::parse(base).unwrap();
|
let c = Config::parse(base).unwrap();
|
||||||
assert!(c.sync.prune_merged);
|
assert!(c.sync.prune_merged);
|
||||||
assert!(c.sync.prune_disposable.iter().any(|d| d == "target"));
|
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 own = format!("{base}[sync]\nprune_merged=false\nprune_disposable=[\"out\"]\n");
|
||||||
let c = Config::parse(&own).unwrap();
|
let c = Config::parse(&own).unwrap();
|
||||||
assert!(!c.sync.prune_merged);
|
assert!(!c.sync.prune_merged);
|
||||||
assert_eq!(c.sync.prune_disposable, vec!["out".to_string()]);
|
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\"", "\"..\""] {
|
for bad in ["\"\"", "\"a/b\"", "\"..\""] {
|
||||||
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
|
let t = format!("{base}[sync]\nprune_disposable=[{bad}]\n");
|
||||||
assert!(Config::parse(&t).is_err(), "{bad}");
|
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
|
//! A branch counts as merged when either
|
||||||
//! ancestry, and a branch freshly created from the default branch is an ancestor of it too.
|
//! - it is the head of a pull request merged on the forge and its tip is that head (or an
|
||||||
//! A worktree is removed only when its branch is the head of a merged pull request, its tip is
|
//! ancestor of it): squash and rebase merges leave no ancestry, so the forge has to say so; or
|
||||||
//! that head (or an ancestor of it), and it holds no local work: no uncommitted or untracked
|
//! - it was merged without a pull request: its tip was pushed (`<remote>/<branch>` points at it),
|
||||||
//! files, no ignored files other than regenerable ones (`sync.prune_disposable`), no git
|
//! is a strict ancestor of `<remote>/<default>` and is not on its first-parent history (a
|
||||||
//! operation in progress. The tip is kept under a backup ref before anything is removed.
|
//! 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::git::{Git, GitError};
|
||||||
use crate::inspect::worktrees;
|
use crate::inspect::worktrees;
|
||||||
@@ -27,18 +34,42 @@ pub enum Pruned {
|
|||||||
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
|
/// Worktree removed and local branch deleted; the tip is kept under `backup_ref`.
|
||||||
Removed {
|
Removed {
|
||||||
branch: String,
|
branch: String,
|
||||||
pr: u64,
|
/// The merged pull request; `None` when merged into the default branch without one.
|
||||||
|
pr: Option<u64>,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
backup_ref: String,
|
backup_ref: String,
|
||||||
},
|
},
|
||||||
/// Merged, but the worktree holds something that is not on the forge: kept.
|
/// Merged, but the worktree holds something that is not on the forge: kept.
|
||||||
Kept {
|
Kept {
|
||||||
branch: String,
|
branch: String,
|
||||||
pr: u64,
|
pr: Option<u64>,
|
||||||
why: String,
|
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>`).
|
/// Backup-ref kind of a pruned branch (`refs/sync-backup/<machine>/<stamp>/merged/<branch>`).
|
||||||
const KIND: &str = "merged";
|
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(_)))
|
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
|
fn resolve(g: &Git, r: &str) -> Option<String> {
|
||||||
/// (see the module docs). Only worktrees inside `root` are touched, never the one of the
|
g.probe(&["rev-parse", "-q", "--verify", &format!("{r}^{{commit}}")])
|
||||||
/// default branch (`.bare`'s HEAD).
|
.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(
|
pub fn prune_merged(
|
||||||
root: &Path,
|
root: &Path,
|
||||||
merged: &[MergedHead],
|
rules: &Rules,
|
||||||
disposable: &[String],
|
|
||||||
machine: &str,
|
machine: &str,
|
||||||
stamp: &str,
|
stamp: &str,
|
||||||
) -> Result<Vec<Pruned>, GitError> {
|
) -> Result<Vec<Pruned>, GitError> {
|
||||||
if merged.is_empty() {
|
|
||||||
return Ok(vec![]);
|
|
||||||
}
|
|
||||||
let bare = root.join(".bare");
|
let bare = root.join(".bare");
|
||||||
let g = Git::new(&bare);
|
let g = Git::new(&bare);
|
||||||
let default = g.probe(&["symbolic-ref", "--short", "-q", "HEAD"])?;
|
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 {
|
let Some(branch) = wt.branch.as_deref() else {
|
||||||
continue;
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
|
let Ok(tip) = g.run(&["rev-parse", &format!("refs/heads/{branch}")]) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
// The newest merged PR of this branch whose head contains the local tip.
|
// The newest merged PR of this branch whose head contains the local tip, else a merge
|
||||||
let Some(pr) = merged
|
// without a PR.
|
||||||
|
let pr = rules
|
||||||
|
.merged
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|m| m.branch == branch)
|
.filter(|m| m.branch == branch)
|
||||||
.find(|m| m.sha == tip || is_ancestor(&g, &tip, &m.sha))
|
.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;
|
continue;
|
||||||
};
|
}
|
||||||
if !wt.path.is_dir() {
|
if !wt.path.is_dir() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Some(why) = local_work(&wt.path, disposable)? {
|
if let Some(why) = local_work(&wt.path, rules.disposable)? {
|
||||||
out.push(Pruned::Kept {
|
out.push(Pruned::Kept {
|
||||||
branch: branch.to_string(),
|
branch: branch.to_string(),
|
||||||
pr: pr.number,
|
pr,
|
||||||
why,
|
why,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
@@ -148,7 +224,7 @@ pub fn prune_merged(
|
|||||||
g.run(&["branch", "-D", branch])?;
|
g.run(&["branch", "-D", branch])?;
|
||||||
out.push(Pruned::Removed {
|
out.push(Pruned::Removed {
|
||||||
branch: branch.to_string(),
|
branch: branch.to_string(),
|
||||||
pr: pr.number,
|
pr,
|
||||||
path: wt.path.clone(),
|
path: wt.path.clone(),
|
||||||
backup_ref: bref,
|
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
|
/// 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
|
/// 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(
|
pub fn settled_branches(
|
||||||
bare: &Path,
|
bare: &Path,
|
||||||
remote: &str,
|
remote: &str,
|
||||||
merged: &[MergedHead],
|
merged: &[MergedHead],
|
||||||
|
protected: &[String],
|
||||||
machine: &str,
|
machine: &str,
|
||||||
) -> Result<Vec<String>, GitError> {
|
) -> Result<Vec<String>, GitError> {
|
||||||
let g = Git::new(bare);
|
let g = Git::new(bare);
|
||||||
@@ -186,6 +263,7 @@ pub fn settled_branches(
|
|||||||
.lines()
|
.lines()
|
||||||
.filter_map(|l| l.split_once(' '))
|
.filter_map(|l| l.split_once(' '))
|
||||||
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
|
.filter_map(|(sha, r)| Some((sha, r.strip_prefix(&prefix)?)))
|
||||||
|
.filter(|(_, b)| !protected.iter().any(|p| p == b))
|
||||||
.filter(|(sha, b)| {
|
.filter(|(sha, b)| {
|
||||||
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|
merged.iter().any(|m| m.branch == *b && m.sha == *sha)
|
||||||
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
|
|| pruned.iter().any(|(s, pb)| pb == b && s == sha)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
use crate::git::{Git, GitError};
|
use crate::git::{Git, GitError};
|
||||||
use crate::inspect::{facts, state, worktrees};
|
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::{
|
use crate::receive::{
|
||||||
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
|
Applied, Archived, Received, apply_snapshot, archive_gone, fetch, foreign_snapshots,
|
||||||
materialize_except, push_snapshot, receive,
|
materialize_except, push_snapshot, receive,
|
||||||
@@ -32,6 +32,10 @@ pub struct Options {
|
|||||||
pub merged: Vec<MergedHead>,
|
pub merged: Vec<MergedHead>,
|
||||||
/// Names of ignored files/directories that do not count as local work when pruning.
|
/// Names of ignored files/directories that do not count as local work when pruning.
|
||||||
pub disposable: Vec<String>,
|
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)]
|
#[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}")),
|
Err(e) => rep.fetch_error = Some(format!("archive: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if bare_layout && rep.fetch_error.is_none() && !o.offline {
|
if bare_layout && o.prune && rep.fetch_error.is_none() && !o.offline {
|
||||||
match prune_merged(path, &o.merged, &o.disposable, &o.machine, &o.stamp) {
|
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,
|
Ok(p) => rep.pruned = p,
|
||||||
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
|
Err(e) => rep.fetch_error = Some(format!("prune merged: {e}")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if bare_layout && o.materialize && rep.fetch_error.is_none() {
|
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)) {
|
match skip.and_then(|skip| materialize_except(path, &o.remote, &skip)) {
|
||||||
Ok(m) => rep.materialized = m,
|
Ok(m) => rep.materialized = m,
|
||||||
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
|
Err(e) => rep.fetch_error = Some(format!("materialize: {e}")),
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ mod common;
|
|||||||
use common::*;
|
use common::*;
|
||||||
use grove_core::git::Git;
|
use grove_core::git::Git;
|
||||||
use grove_core::migrate::migrate;
|
use grove_core::migrate::migrate;
|
||||||
use grove_core::prune::{MergedHead, Pruned, prune_merged};
|
use grove_core::prune::{MergedHead, Pruned, Rules, default_protected, prune_merged};
|
||||||
use grove_core::sync::{Options, sync_repo};
|
use grove_core::sync::{Options, sync_repo};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -58,6 +58,8 @@ fn opts(stamp: &str, merged: Vec<MergedHead>) -> Options {
|
|||||||
push_snapshots: false,
|
push_snapshots: false,
|
||||||
merged,
|
merged,
|
||||||
disposable: vec!["target".into()],
|
disposable: vec!["target".into()],
|
||||||
|
prune: true,
|
||||||
|
protected: default_protected(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +121,7 @@ fn a_squash_merged_worktree_is_removed_and_not_brought_back() {
|
|||||||
else {
|
else {
|
||||||
panic!("{:?}", rep.pruned);
|
panic!("{:?}", rep.pruned);
|
||||||
};
|
};
|
||||||
assert_eq!((branch.as_str(), *pr), ("feat/x", 7));
|
assert_eq!((branch.as_str(), *pr), ("feat/x", Some(7)));
|
||||||
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
|
assert!(!wt.exists() && !has_branch(&w.root, "feat/x"));
|
||||||
let bare = Git::new(w.root.join(".bare"));
|
let bare = Git::new(w.root.join(".bare"));
|
||||||
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
|
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
|
||||||
@@ -215,10 +217,82 @@ fn an_older_tip_is_pruned_but_the_default_branch_and_outside_worktrees_never_are
|
|||||||
head(5, "main", &main_tip),
|
head(5, "main", &main_tip),
|
||||||
head(6, "o", &tip_o),
|
head(6, "o", &tip_o),
|
||||||
];
|
];
|
||||||
let pruned = prune_merged(&w.root, &merged, &[], "me", "t").unwrap();
|
let rules = Rules {
|
||||||
|
remote: "origin",
|
||||||
|
merged: &merged,
|
||||||
|
disposable: &[],
|
||||||
|
protected: &[],
|
||||||
|
};
|
||||||
|
let pruned = prune_merged(&w.root, &rules, "me", "t").unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: 4, .. }] if branch == "f"),
|
matches!(pruned.as_slice(), [Pruned::Removed { branch, pr: Some(4), .. }] if branch == "f"),
|
||||||
"{pruned:?}"
|
"{pruned:?}"
|
||||||
);
|
);
|
||||||
assert!(w.root.join("main").exists() && ext.exists());
|
assert!(w.root.join("main").exists() && ext.exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_branch_merged_without_a_pr_is_removed_but_protected_and_fresh_ones_are_not() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "feat/ff");
|
||||||
|
push_branch(&w, "development");
|
||||||
|
push_branch(&w, "wip");
|
||||||
|
sync_repo(&w.root, &opts("s1", vec![])).unwrap();
|
||||||
|
// A branch at the default branch's tip has nothing of its own yet.
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main:fresh"]).unwrap();
|
||||||
|
|
||||||
|
// Merged into main without a pull request (no forge answer at all), with `development`
|
||||||
|
// (long-lived, protected); `wip` is not merged.
|
||||||
|
for b in ["feat/ff", "development"] {
|
||||||
|
w.dev
|
||||||
|
.run(&["merge", "-q", "--no-ff", "-m", "m", b])
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main"]).unwrap();
|
||||||
|
w.dev.run(&["push", "-q", "origin", "main:fresh2"]).unwrap();
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", vec![])).unwrap();
|
||||||
|
assert!(rep.fetch_error.is_none(), "{:?}", rep.fetch_error);
|
||||||
|
let [
|
||||||
|
Pruned::Removed {
|
||||||
|
branch,
|
||||||
|
pr: None,
|
||||||
|
backup_ref,
|
||||||
|
..
|
||||||
|
},
|
||||||
|
] = rep.pruned.as_slice()
|
||||||
|
else {
|
||||||
|
panic!("{:?}", rep.pruned);
|
||||||
|
};
|
||||||
|
assert_eq!(branch, "feat/ff");
|
||||||
|
let bare = Git::new(w.root.join(".bare"));
|
||||||
|
assert_eq!(bare.run(&["rev-parse", backup_ref]).unwrap(), tip);
|
||||||
|
assert!(!w.root.join("feat-ff").exists() && !has_branch(&w.root, "feat/ff"));
|
||||||
|
for d in ["development", "wip", "fresh2"] {
|
||||||
|
assert!(w.root.join(d).exists(), "{d}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// `feat/ff` stays on the remote and is not materialized again. `fresh` (materialized in
|
||||||
|
// s2) has no commits of its own: main's first-parent history passed through its tip, so it
|
||||||
|
// is not taken for a merge although main moved past it.
|
||||||
|
let rep = sync_repo(&w.root, &opts("s3", vec![])).unwrap();
|
||||||
|
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
|
||||||
|
assert!(!w.root.join("feat-ff").exists());
|
||||||
|
assert!(w.root.join("fresh").exists() && w.root.join("fresh2").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_protected_branch_is_kept_even_as_the_head_of_a_merged_pr() {
|
||||||
|
let w = world();
|
||||||
|
let tip = push_branch(&w, "development");
|
||||||
|
squash_merge(&w, "development");
|
||||||
|
// Not materialized yet: a merged PR head must not keep a protected branch away.
|
||||||
|
let rep = sync_repo(&w.root, &opts("s1", vec![head(9, "development", &tip)])).unwrap();
|
||||||
|
assert!(
|
||||||
|
w.root.join("development").exists(),
|
||||||
|
"{:?}",
|
||||||
|
rep.materialized
|
||||||
|
);
|
||||||
|
let rep = sync_repo(&w.root, &opts("s2", vec![head(9, "development", &tip)])).unwrap();
|
||||||
|
assert!(rep.pruned.is_empty(), "{:?}", rep.pruned);
|
||||||
|
assert!(w.root.join("development").exists());
|
||||||
|
}
|
||||||
@@ -388,6 +388,8 @@ fn archive_and_receive_in_one_pass_do_not_collide_on_backup_refs() {
|
|||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
merged: vec![],
|
merged: vec![],
|
||||||
disposable: vec![],
|
disposable: vec![],
|
||||||
|
prune: false,
|
||||||
|
protected: vec![],
|
||||||
};
|
};
|
||||||
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
|
w.g1.run(&["checkout", "-q", "-b", "feat/z"]).unwrap();
|
||||||
commit(&w.g1, "z.txt", "z\n");
|
commit(&w.g1, "z.txt", "z\n");
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ fn opts(machine: &str, stamp: &str) -> Options {
|
|||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
merged: vec![],
|
merged: vec![],
|
||||||
disposable: vec![],
|
disposable: vec![],
|
||||||
|
prune: false,
|
||||||
|
protected: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ use crate::merged::{MergedCache, has_candidates};
|
|||||||
use crate::purge;
|
use crate::purge;
|
||||||
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
use crate::visibility::{RealForge, Visibility, snapshot_gate};
|
||||||
use grove_core::config::Config;
|
use grove_core::config::Config;
|
||||||
use grove_core::prune::Pruned;
|
use grove_core::prune::{Pruned, merged_how};
|
||||||
use grove_core::receive::Received;
|
use grove_core::receive::Received;
|
||||||
use grove_core::sync::{Options, sync_repo};
|
use grove_core::sync::{Options, sync_repo};
|
||||||
use notify::{EventKind, RecursiveMode, Watcher};
|
use notify::{EventKind, RecursiveMode, Watcher};
|
||||||
@@ -632,6 +632,8 @@ fn pass(
|
|||||||
push_snapshots,
|
push_snapshots,
|
||||||
merged: merged_heads,
|
merged: merged_heads,
|
||||||
disposable: cfg.sync.prune_disposable.clone(),
|
disposable: cfg.sync.prune_disposable.clone(),
|
||||||
|
prune: cfg.sync.prune_merged,
|
||||||
|
protected: cfg.sync.protected_branches(),
|
||||||
};
|
};
|
||||||
let result = sync_repo(repo, &opts);
|
let result = sync_repo(repo, &opts);
|
||||||
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
|
if !offline && purge_if_gone(repo, cfg, st, &result, gone_since, ctx) {
|
||||||
@@ -713,12 +715,13 @@ fn pass(
|
|||||||
"pruned_merged",
|
"pruned_merged",
|
||||||
Some(&name),
|
Some(&name),
|
||||||
format!(
|
format!(
|
||||||
"{branch}: merged in PR #{pr}; removed {} (tip kept in {backup_ref})",
|
"{branch}: {}; removed {} (tip kept in {backup_ref})",
|
||||||
|
merged_how(*pr),
|
||||||
path.display()
|
path.display()
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Pruned::Kept { branch, pr, why } => {
|
Pruned::Kept { branch, pr, why } => {
|
||||||
kept.push(format!("{branch}: merged in PR #{pr} but kept: {why}"))
|
kept.push(format!("{branch}: {} but kept: {why}", merged_how(*pr)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ impl PullSource for RealForge {
|
|||||||
name: &str,
|
name: &str,
|
||||||
) -> Result<Vec<MergedHead>, String> {
|
) -> Result<Vec<MergedHead>, String> {
|
||||||
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
let (token, _) = grove_providers::token::resolve(id, pc).map_err(|e| e.to_string())?;
|
||||||
let pulls = grove_providers::build(pc, token)
|
let forge = grove_providers::build(pc, token);
|
||||||
.merged_pulls(owner, name)
|
let pulls = grove_providers::merged_pulls_following_moves(forge.as_ref(), owner, name)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
Ok(pulls
|
Ok(pulls
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
@@ -158,6 +158,30 @@ pub trait Provider: Send + Sync {
|
|||||||
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
|
fn merged_pulls(&self, owner: &str, name: &str) -> Result<Vec<MergedPull>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [`Provider::merged_pulls`] that also finds a repo transferred or renamed on the forge: `origin`
|
||||||
|
/// may still name the old place, which git and the repo endpoint follow by redirect but the
|
||||||
|
/// pulls endpoint does not. On failure the repo is looked up and, if its current owner/name
|
||||||
|
/// differ, its pulls are listed under those.
|
||||||
|
pub fn merged_pulls_following_moves(
|
||||||
|
p: &dyn Provider,
|
||||||
|
owner: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Vec<MergedPull>> {
|
||||||
|
let err = match p.merged_pulls(owner, name) {
|
||||||
|
Ok(pulls) => return Ok(pulls),
|
||||||
|
Err(e) => e,
|
||||||
|
};
|
||||||
|
match p.get_repo(owner, name) {
|
||||||
|
Ok(r)
|
||||||
|
if !r.owner.is_empty()
|
||||||
|
&& !(r.owner.eq_ignore_ascii_case(owner) && r.name.eq_ignore_ascii_case(name)) =>
|
||||||
|
{
|
||||||
|
p.merged_pulls(&r.owner, &r.name)
|
||||||
|
}
|
||||||
|
_ => Err(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds the provider described by `cfg`, using `token`.
|
/// Builds the provider described by `cfg`, using `token`.
|
||||||
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
|
pub fn build(cfg: &ProviderCfg, token: String) -> Box<dyn Provider> {
|
||||||
match cfg.kind {
|
match cfg.kind {
|
||||||
|
|||||||
@@ -526,3 +526,39 @@ fn merged_pulls_keep_only_merged_same_repo_heads() {
|
|||||||
Error::Api { status: 404, .. }
|
Error::Api { status: 404, .. }
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merged_pulls_follow_a_transferred_repo() {
|
||||||
|
let pulls = r#"[{"number":4,"merged":true,"head":{"ref":"f","sha":"fff","repo":{"full_name":"Org/r"}},"base":{"repo":{"full_name":"Org/r"}}}]"#;
|
||||||
|
let (url, rx) = mock(vec![
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
(
|
||||||
|
200,
|
||||||
|
r#"{"name":"r","owner":{"login":"Org"},"private":true}"#,
|
||||||
|
),
|
||||||
|
(200, pulls),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
|
||||||
|
let got = grove_providers::merged_pulls_following_moves(&g, "me", "r").unwrap();
|
||||||
|
assert_eq!(got.iter().map(|p| p.number).collect::<Vec<_>>(), vec![4]);
|
||||||
|
let asked: Vec<String> = rx
|
||||||
|
.try_iter()
|
||||||
|
.map(|l| l.lines().next().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
assert!(asked[1].starts_with("GET /api/v1/repos/me/r "), "{asked:?}");
|
||||||
|
assert!(
|
||||||
|
asked[2].starts_with("GET /api/v1/repos/Org/r/pulls?"),
|
||||||
|
"{asked:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Not moved: the original error stands.
|
||||||
|
let (url, _rx) = mock(vec![
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
(404, r#"{"message":"not found"}"#),
|
||||||
|
]);
|
||||||
|
let g = Gitea::new(ProviderKind::Gitea, &url, "t".into());
|
||||||
|
assert!(matches!(
|
||||||
|
grove_providers::merged_pulls_following_moves(&g, "me", "gone").unwrap_err(),
|
||||||
|
Error::Api { status: 404, .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ use grove_core::config::{Config, ProviderKind};
|
|||||||
use grove_core::git::Git;
|
use grove_core::git::Git;
|
||||||
use grove_core::inspect::{state, worktrees};
|
use grove_core::inspect::{state, worktrees};
|
||||||
use grove_core::migrate::migrate;
|
use grove_core::migrate::migrate;
|
||||||
use grove_core::prune::Pruned;
|
use grove_core::prune::{Pruned, merged_how};
|
||||||
use grove_core::receive::{Applied, Archived, Received};
|
use grove_core::receive::{Applied, Archived, Received};
|
||||||
use grove_core::resolve::{Choice, resolve};
|
use grove_core::resolve::{Choice, resolve};
|
||||||
use grove_core::snapshot::{Outcome, take};
|
use grove_core::snapshot::{Outcome, take};
|
||||||
@@ -377,6 +377,8 @@ fn main() -> Result<()> {
|
|||||||
push_snapshots: true,
|
push_snapshots: true,
|
||||||
merged,
|
merged,
|
||||||
disposable: cfg.sync.prune_disposable.clone(),
|
disposable: cfg.sync.prune_disposable.clone(),
|
||||||
|
prune: cfg.sync.prune_merged,
|
||||||
|
protected: cfg.sync.protected_branches(),
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
print_report(&rep)
|
print_report(&rep)
|
||||||
@@ -531,11 +533,12 @@ fn print_report(rep: &SyncReport) -> Result<()> {
|
|||||||
path,
|
path,
|
||||||
backup_ref,
|
backup_ref,
|
||||||
} => println!(
|
} => println!(
|
||||||
"pruned {branch}: merged in PR #{pr}, removed {} (backup {backup_ref})",
|
"pruned {branch}: {}, removed {} (backup {backup_ref})",
|
||||||
|
merged_how(*pr),
|
||||||
path.display()
|
path.display()
|
||||||
),
|
),
|
||||||
Pruned::Kept { branch, pr, why } => {
|
Pruned::Kept { branch, pr, why } => {
|
||||||
println!("kept {branch}: merged in PR #{pr} but {why}")
|
println!("kept {branch}: {} but {why}", merged_how(*pr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+26
-7
@@ -1,10 +1,11 @@
|
|||||||
# Pruning worktrees merged through a pull request
|
# Pruning merged worktrees
|
||||||
|
|
||||||
Worktrees of branches that were pushed, reviewed in a pull request and merged used to stay
|
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
|
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
|
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
|
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.
|
the forge which pull requests were merged and removes those worktrees itself. Branches merged
|
||||||
|
into the default branch without a pull request (merged locally and pushed) are removed too.
|
||||||
|
|
||||||
## Config
|
## Config
|
||||||
|
|
||||||
@@ -14,9 +15,15 @@ prune_merged = true # default
|
|||||||
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
|
prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".pytest_cache",
|
||||||
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
|
".mypy_cache", ".ruff_cache", ".tox", ".gradle", ".next", ".nuxt", ".svelte-kit", ".turbo",
|
||||||
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
|
".parcel-cache", "dist", "build", "out", "coverage", ".cache"] # default
|
||||||
|
prune_protected = [] # default; extra branch names never pruned
|
||||||
```
|
```
|
||||||
|
|
||||||
- `prune_merged = false` turns the feature off.
|
- `prune_merged = false` turns the feature off.
|
||||||
|
- `prune_protected`: extra branch names (exact, no globs) never pruned nor kept from being
|
||||||
|
materialized, added to the built-in `main`, `master`, `development`, `develop`, `dev`,
|
||||||
|
`staging`, `production` (a `development` -> `main` PR has `development` as its head). The
|
||||||
|
default branch (`.bare`'s HEAD) never is either. Other long-lived branches (`release/1.2`,
|
||||||
|
`hotfix/x`) merged back with no new commits are pruned like any other: list them here.
|
||||||
- `prune_disposable`: names (not paths, not globs) of ignored files/directories that are
|
- `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.
|
regenerable and may go with a pruned worktree. Entries must be plain names.
|
||||||
|
|
||||||
@@ -26,19 +33,29 @@ prune_disposable = ["target", "node_modules", ".venv", "venv", "__pycache__", ".
|
|||||||
requests (GitHub: 100, `merged_at` set; Gitea/Forgejo: 50, `merged: true`), keeping only those
|
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
|
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`),
|
`origin`'s fetch URL, matched to a configured provider like the visibility check (`phase6.md`),
|
||||||
with the token from `token::resolve`.
|
with the token from `token::resolve`. When that fails, the repo is looked up and, if the forge
|
||||||
|
reports another owner/name (transferred or renamed: git and the repo endpoint follow the old
|
||||||
|
`origin` by redirect, the pulls endpoint does not), its pulls are listed under the current one.
|
||||||
|
|
||||||
|
Without a pull request, a branch counts as merged when its tip was pushed
|
||||||
|
(`origin/<branch>` points at it), is a strict ancestor of `origin/<default>` and is not on its
|
||||||
|
first-parent history, i.e. a merge commit brought it in. This needs no forge. A branch created
|
||||||
|
from the default branch with no commits of its own is on that history and is never pruned this
|
||||||
|
way; neither is a fast-forward merge (only the PR path catches those).
|
||||||
|
|
||||||
## When a worktree is removed
|
## When a worktree is removed
|
||||||
|
|
||||||
All of these must hold (`grove_core::prune::prune_merged`):
|
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.
|
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
|
2. The worktree is on a branch that is not `.bare`'s HEAD (the default branch) nor in
|
||||||
|
`prune_protected`, and it lives
|
||||||
inside the repo directory (`root/<group>/<repo>/...`, so nested ones such as
|
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
|
`main/.claude/worktrees/x` count). Linked worktrees elsewhere are the user's and are never
|
||||||
touched.
|
touched.
|
||||||
3. A merged PR has that branch as head and its head commit equals the local tip, or contains it
|
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).
|
(the PR got more commits from another machine before the merge); or, without a PR, the
|
||||||
|
ancestry rule above holds.
|
||||||
4. No local work: no staged, modified or untracked file, no git operation in progress
|
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
|
(`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).
|
is not in `prune_disposable` (`.env` keeps it, `target/` does not).
|
||||||
@@ -66,10 +83,12 @@ branch after the merge are new work: the worktree is materialized again.
|
|||||||
error changes).
|
error changes).
|
||||||
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
|
- Offline passes (backoff) prune nothing, but still use the last answer to keep pruned branches
|
||||||
from being materialized.
|
from being materialized.
|
||||||
- Activity log: `pruned_merged` (removed, with the PR, path and backup ref) and `prune_kept`.
|
- The ancestry rule runs on every online pass, also when the forge lookup fails.
|
||||||
|
- Activity log: `pruned_merged` (removed, with the PR or "merged into the default branch", path
|
||||||
|
and backup ref) and `prune_kept`.
|
||||||
|
|
||||||
`grove sync <path>` does the same in one shot (no cache) and prints `pruned ...` / `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.
|
lines; a failed lookup is a warning, and only the ancestry rule applies.
|
||||||
|
|
||||||
## Validation
|
## Validation
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user