Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: replace IntegrationProvider trait with IntegrationSignals struct (#604)
Maximilian Roos56c375df9d96
diff --git a/src/commands/branch_deletion.rs b/src/commands/branch_deletion.rsindex f9d588e00..7581e9a57 100644--- a/src/commands/branch_deletion.rs+++ b/src/commands/branch_deletion.rs@@ -4,7 +4,7 @@//! deleted after its worktree is removed. It checks if the branch's content has//! been integrated into the target branch.-use worktrunk::git::{IntegrationReason, Repository};+use worktrunk::git::{IntegrationReason, Repository, check_integration, compute_integration_lazy};/// Result of an integration check, including which target was used.pub struct IntegrationResult {@@ -34,40 +34,30 @@ pub struct BranchDeletionResult {////// Returns the reason if the branch is safe to delete (ordered by check cost):/// - `SameCommit`: Branch HEAD is literally the same commit as target+/// - `Ancestor`: Branch is ancestor of target (target has moved past)/// - `NoAddedChanges`: Branch has no file changes beyond merge-base (empty three-dot diff)/// - `TreesMatch`: The branch's tree SHA matches the target's tree SHA (squash merge/rebase)/// - `MergeAddsNothing`: Merge simulation shows branch would add nothing (squash + target advanced)////// Also returns the effective target used (may be upstream if it's ahead of local).///-/// Returns None reason if no condition is met, or if an error occurs (e.g., invalid refs).-/// This fail-safe default prevents accidental branch deletion when integration cannot-/// be determined.+/// Errors are propagated rather than silently returning None.pub fn get_integration_reason(repo: &Repository,branch_name: &str,target: &str,-) -> IntegrationResult {+) -> anyhow::Result<IntegrationResult> {let effective_target = repo.effective_integration_target(target);- let reason = check_integration_against(repo, branch_name, &effective_target);+ // Use lazy computation with short-circuit evaluation.+ // Expensive checks (would_merge_add) are skipped if cheaper ones succeed.+ let signals = compute_integration_lazy(repo, branch_name, &effective_target)?;+ let reason = check_integration(&signals);- IntegrationResult {+ Ok(IntegrationResult {reason,effective_target,- }-}--/// Check integration against a specific target ref.-fn check_integration_against(- repo: &Repository,- branch_name: &str,- target: &str,-) -> Option<IntegrationReason> {- // Use lazy provider for short-circuit evaluation.- // Expensive checks (would_merge_add) are skipped if cheaper ones succeed.- let mut provider = worktrunk::git::LazyGitIntegration::new(repo, branch_name, target);- worktrunk::git::check_integration(&mut provider)+ })}/// Attempt to delete a branch if it's integrated or force_delete is set.@@ -84,7 +74,7 @@ pub fn delete_branch_if_safe(let IntegrationResult {reason,effective_target,- } = get_integration_reason(repo, branch_name, target);+ } = get_integration_reason(repo, branch_name, target)?;// Determine outcome based on integration and force flaglet outcome = match (reason, force_delete) {diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex ae93b6708..5923a5364 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -1,5 +1,5 @@use std::path::PathBuf;-use worktrunk::git::{IntegrationReason, LineDiff, PrecomputedIntegration, check_integration};+use worktrunk::git::{IntegrationReason, IntegrationSignals, LineDiff, check_integration};use super::ci_status::PrStatus;use super::columns::ColumnKind;@@ -763,20 +763,17 @@ impl ListItem {// Compute is_same_commit from ahead/behind counts (vs stats_base/main)// This detects "same commit as main" for the _ symbol- let is_same_commit = self- .counts- .as_ref()- .is_some_and(|c| c.ahead == 0 && c.behind == 0);+ let is_same_commit = self.counts.as_ref().map(|c| c.ahead == 0 && c.behind == 0);// Use the shared integration check (same logic as wt remove)- let mut provider = PrecomputedIntegration {+ let signals = IntegrationSignals {is_same_commit,- is_ancestor: self.is_ancestor.unwrap_or(false),- has_added_changes: self.has_file_changes.unwrap_or(true), // default: assume has changes- trees_match: self.committed_trees_match.unwrap_or(false),- would_merge_add: self.would_merge_add.unwrap_or(true), // default: assume would add+ is_ancestor: self.is_ancestor,+ has_added_changes: self.has_file_changes,+ trees_match: self.committed_trees_match,+ would_merge_add: self.would_merge_add,};- let reason = check_integration(&mut provider);+ let reason = check_integration(&signals);// Convert to MainState, with SameCommit becoming Empty for displaymatch reason {diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 39508f11d..461fa8235 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -210,9 +210,9 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let worktree_root = repo.current_worktree().root()?.to_path_buf();// After a successful merge, compute integration reason from main_pathlet effective_target = repo.effective_integration_target(&target_branch);- let mut provider =- worktrunk::git::LazyGitIntegration::new(repo, ¤t_branch, &effective_target);- let integration_reason = worktrunk::git::check_integration(&mut provider);+ let signals =+ worktrunk::git::compute_integration_lazy(repo, ¤t_branch, &effective_target)?;+ let integration_reason = worktrunk::git::check_integration(&signals);// Compute expected_path for path mismatch detectionlet expected_path = get_path_mismatch(repo, ¤t_branch, &worktree_root, config);let remove_result = RemoveResult::RemovedWorktree {diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 545874f29..1e613c838 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -344,8 +344,10 @@ fn compute_integration_reason(// removed during the operation.let repo = Repository::at(main_path).ok()?;let effective_target = repo.effective_integration_target(target);- let mut provider = worktrunk::git::LazyGitIntegration::new(&repo, branch, &effective_target);- worktrunk::git::check_integration(&mut provider)+ // Use lazy computation with short-circuit. On error, return None (informational only).+ let signals =+ worktrunk::git::compute_integration_lazy(&repo, branch, &effective_target).ok()?;+ worktrunk::git::check_integration(&signals)}/// Warn about untracked files that will be auto-staged.diff --git a/src/git/mod.rs b/src/git/mod.rsindex a256b46a1..8f361ba66 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -122,138 +122,103 @@ impl IntegrationReason {}}-/// Provider of integration signals for checking if a branch is integrated into target.+/// Integration signals for checking if a branch is integrated into target.///-/// This trait enables short-circuit evaluation: methods are called in priority order,-/// and expensive checks (like `would_merge_add`) are skipped if cheaper checks succeed.+/// `None` means "unknown/failed to check". The check functions treat `None`+/// conservatively (as if not integrated).///-/// Implementations:-/// - [`LazyGitIntegration`]: Makes fresh git calls (for `wt remove`)-/// - [`PrecomputedIntegration`]: Uses cached data (for `wt list` progressive rendering)-pub trait IntegrationProvider {- fn is_same_commit(&mut self) -> bool;- fn is_ancestor(&mut self) -> bool;- fn has_added_changes(&mut self) -> bool;- fn trees_match(&mut self) -> bool;- fn would_merge_add(&mut self) -> bool;+/// Used by:+/// - `wt list`: Built from parallel task results+/// - `wt remove`/`wt merge`: Built via [`compute_integration_lazy`]+#[derive(Debug, Default)]+pub struct IntegrationSignals {+ pub is_same_commit: Option<bool>,+ pub is_ancestor: Option<bool>,+ pub has_added_changes: Option<bool>,+ pub trees_match: Option<bool>,+ pub would_merge_add: Option<bool>,}-/// Canonical integration check with short-circuit evaluation.+/// Canonical integration check using pre-computed signals.////// Checks signals in priority order (cheapest first). Returns as soon as any-/// integration reason is found, avoiding expensive checks when possible.+/// integration reason is found.///-/// This is the single source of truth for integration priority logic,-/// used by both `wt list` and `wt remove`.-pub fn check_integration(provider: &mut impl IntegrationProvider) -> Option<IntegrationReason> {+/// `None` values are treated conservatively: unknown signals don't match.+/// This is the single source of truth for integration priority logic.+pub fn check_integration(signals: &IntegrationSignals) -> Option<IntegrationReason> {// Priority 1 (cheapest): Same commit as target- if provider.is_same_commit() {+ if signals.is_same_commit == Some(true) {return Some(IntegrationReason::SameCommit);}// Priority 2 (cheap): Branch is ancestor of target (target has moved past)- if provider.is_ancestor() {+ if signals.is_ancestor == Some(true) {return Some(IntegrationReason::Ancestor);}// Priority 3: No file changes beyond merge-base (empty three-dot diff)- if !provider.has_added_changes() {+ if signals.has_added_changes == Some(false) {return Some(IntegrationReason::NoAddedChanges);}// Priority 4: Tree SHA matches target (handles squash merge/rebase)- if provider.trees_match() {+ if signals.trees_match == Some(true) {return Some(IntegrationReason::TreesMatch);}// Priority 5 (most expensive ~500ms-2s): Merge would not add anything- if !provider.would_merge_add() {+ if signals.would_merge_add == Some(false) {return Some(IntegrationReason::MergeAddsNothing);}None}-/// Lazy integration provider that makes fresh git calls.+/// Compute integration signals lazily with short-circuit evaluation.///-/// Used by `wt remove` where short-circuit evaluation matters:-/// expensive checks are skipped if cheaper ones succeed.-pub struct LazyGitIntegration<'a> {- repo: &'a Repository,- branch: &'a str,- target: &'a str,-}--impl<'a> LazyGitIntegration<'a> {- pub fn new(repo: &'a Repository, branch: &'a str, target: &'a str) -> Self {- Self {- repo,- branch,- target,- }- }-}+/// Runs git commands in priority order, stopping as soon as integration is+/// confirmed. This avoids expensive checks (like `would_merge_add` which+/// takes ~500ms-2s) when cheaper checks succeed.+///+/// Used by `wt remove` and `wt merge` for single-branch checks.+/// For batch operations, use parallel tasks to build [`IntegrationSignals`] directly.+#[allow(clippy::field_reassign_with_default)] // Intentional: short-circuit populates fields incrementally+pub fn compute_integration_lazy(+ repo: &Repository,+ branch: &str,+ target: &str,+) -> anyhow::Result<IntegrationSignals> {+ let mut signals = IntegrationSignals::default();-impl IntegrationProvider for LazyGitIntegration<'_> {- fn is_same_commit(&mut self) -> bool {- self.repo- .same_commit(self.branch, self.target)- .unwrap_or(false)+ // Priority 1: Same commit+ signals.is_same_commit = Some(repo.same_commit(branch, target)?);+ if signals.is_same_commit == Some(true) {+ return Ok(signals);}- fn is_ancestor(&mut self) -> bool {- self.repo- .is_ancestor(self.branch, self.target)- .unwrap_or(false)+ // Priority 2: Ancestor+ signals.is_ancestor = Some(repo.is_ancestor(branch, target)?);+ if signals.is_ancestor == Some(true) {+ return Ok(signals);}- fn has_added_changes(&mut self) -> bool {- self.repo- .has_added_changes(self.branch, self.target)- .unwrap_or(true) // Conservative: assume has changes+ // Priority 3: No added changes+ signals.has_added_changes = Some(repo.has_added_changes(branch, target)?);+ if signals.has_added_changes == Some(false) {+ return Ok(signals);}- fn trees_match(&mut self) -> bool {- self.repo- .trees_match(self.branch, self.target)- .unwrap_or(false)+ // Priority 4: Trees match+ signals.trees_match = Some(repo.trees_match(branch, target)?);+ if signals.trees_match == Some(true) {+ return Ok(signals);}- fn would_merge_add(&mut self) -> bool {- self.repo- .would_merge_add_to_target(self.branch, self.target)- .unwrap_or(true) // Conservative: assume would add- }-}+ // Priority 5: Would merge add (most expensive)+ signals.would_merge_add = Some(repo.would_merge_add_to_target(branch, target)?);-/// Pre-computed integration provider for cached data.-///-/// Used by `wt list` where signals are pre-computed during progressive rendering.-/// Short-circuit doesn't help here since data is already computed.-pub struct PrecomputedIntegration {- pub is_same_commit: bool,- pub is_ancestor: bool,- pub has_added_changes: bool,- pub trees_match: bool,- pub would_merge_add: bool,-}--impl IntegrationProvider for PrecomputedIntegration {- fn is_same_commit(&mut self) -> bool {- self.is_same_commit- }- fn is_ancestor(&mut self) -> bool {- self.is_ancestor- }- fn has_added_changes(&mut self) -> bool {- self.has_added_changes- }- fn trees_match(&mut self) -> bool {- self.trees_match- }- fn would_merge_add(&mut self) -> bool {- self.would_merge_add- }+ Ok(signals)}/// Category of branch for completion display@@ -496,35 +461,63 @@ mod tests {#[test]fn test_check_integration() {// Each integration reason + not integrated+ // Tuple: (is_same_commit, is_ancestor, has_added_changes, trees_match, would_merge_add)let cases = [(- (true, false, true, false, true),+ (Some(true), Some(false), Some(true), Some(false), Some(true)),Some(IntegrationReason::SameCommit),),(- (false, true, true, false, true),+ (Some(false), Some(true), Some(true), Some(false), Some(true)),Some(IntegrationReason::Ancestor),),(- (false, false, false, false, true),+ (+ Some(false),+ Some(false),+ Some(false),+ Some(false),+ Some(true),+ ),Some(IntegrationReason::NoAddedChanges),),(- (false, false, true, true, true),+ (Some(false), Some(false), Some(true), Some(true), Some(true)),Some(IntegrationReason::TreesMatch),),(- (false, false, true, false, false),+ (+ Some(false),+ Some(false),+ Some(true),+ Some(false),+ Some(false),+ ),Some(IntegrationReason::MergeAddsNothing),),- ((false, false, true, false, true), None), // Not integrated(- (true, true, false, true, false),+ (+ Some(false),+ Some(false),+ Some(true),+ Some(false),+ Some(true),+ ),+ None,+ ), // Not integrated+ (+ (Some(true), Some(true), Some(false), Some(true), Some(false)),Some(IntegrationReason::SameCommit),- ), // Priority test+ ), // Priority test: is_same_commit wins+ // None values are treated conservatively (as if not integrated)+ ((None, None, None, None, None), None),+ (+ (None, Some(true), Some(false), Some(true), Some(false)),+ Some(IntegrationReason::Ancestor),+ ),];for ((same, ancestor, added, trees, merge), expected) in cases {- let mut provider = PrecomputedIntegration {+ let signals = IntegrationSignals {is_same_commit: same,is_ancestor: ancestor,has_added_changes: added,@@ -532,9 +525,9 @@ mod tests {would_merge_add: merge,};assert_eq!(- check_integration(&mut provider),+ check_integration(&signals),expected,- "case: {same},{ancestor},{added},{trees},{merge}"+ "case: {same:?},{ancestor:?},{added:?},{trees:?},{merge:?}");}}