Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(step): extract internal helpers in promote/prune (#2609)
Maximilian Roos290302b5d1f7
diff --git a/src/commands/step/promote.rs b/src/commands/step/promote.rsindex 42271fb44..22b0bf428 100644--- a/src/commands/step/promote.rs+++ b/src/commands/step/promote.rs@@ -160,6 +160,74 @@ pub enum PromoteResult {AlreadyInMain(String),}+/// Resolve the branch to promote when no explicit argument was passed.+///+/// From the main worktree, restore the default branch. From a linked worktree,+/// promote the current branch.+fn resolve_target_branch(branch: Option<&str>, repo: &Repository) -> anyhow::Result<String> {+ use worktrunk::git::GitError;++ if let Some(b) = branch {+ return Ok(b.to_string());+ }++ let current_wt = repo.current_worktree();+ if !current_wt.is_linked()? {+ // From main worktree with no args: restore default branch+ repo.default_branch()+ .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))+ } else {+ // From other worktree with no args: promote current branch+ current_wt.branch()?.ok_or_else(|| {+ GitError::DetachedHead {+ action: Some("promote".into()),+ }+ .into()+ })+ }+}++/// Bail if a leftover staging dir exists from a previous interrupted promote —+/// it may contain the user's only copy of files from the failed swap.+/// Checked BEFORE `ensure_clean` so users see the recovery path first.+fn check_leftover_staging(staging_path: &Path) -> anyhow::Result<()> {+ if !staging_path.exists() {+ return Ok(());+ }+ let display = staging_path.to_slash_lossy();+ Err(anyhow::anyhow!(+ "Files may need manual recovery from: {display}\n\+ Remove it to retry: rm -rf \"{display}\""+ )+ .context("Found leftover staging directory from an interrupted promote"))+}++/// Print the user-facing announcement for the promote operation: either a+/// "restoring main worktree" info line or a mismatch warning plus a hint+/// for restoring canonical locations.+fn print_promote_announcement(is_restoring: bool, default_branch: Option<&str>) {+ if is_restoring {+ // Restoring default branch to main worktree - no warning needed+ eprintln!("{}", info_message("Restoring main worktree"));+ return;+ }++ // Creating mismatch - show warning and how to restore+ eprintln!(+ "{}",+ warning_message("Promoting creates mismatched worktree state (shown as ⚑ in wt list)",)+ );+ // Only show restore hint if we know the default branch+ if let Some(default) = default_branch {+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Run <underline>wt step promote {default}</> to restore canonical locations"+ ))+ );+ }+}+/// Exchange branches between two worktrees.////// Steps: detach target → detach main → switch main → switch target.@@ -233,22 +301,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {})?;// Resolve the branch to promote (default_branch computed lazily, only when needed)- let target_branch = match branch {- Some(b) => b.to_string(),- None => {- let current_wt = repo.current_worktree();- if !current_wt.is_linked()? {- // From main worktree with no args: restore default branch- repo.default_branch()- .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))?- } else {- // From other worktree with no args: promote current branch- current_wt.branch()?.ok_or_else(|| GitError::DetachedHead {- action: Some("promote".into()),- })?- }- }- };+ let target_branch = resolve_target_branch(branch, &repo)?;// Check if target is already in main worktreeif target_branch == main_branch {@@ -267,17 +320,9 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {let target_path = &target_wt.path;// Bail early if a leftover staging dir exists from a previous interrupted promote —- // it may contain the user's only copy of files from the failed swap.- // Check BEFORE ensure_clean so users see the recovery path first.+ // checked before `ensure_clean` so users see the recovery path first.let staging_path = repo.wt_dir().join(PROMOTE_STAGING_DIR);- if staging_path.exists() {- let display = staging_path.to_slash_lossy();- return Err(anyhow::anyhow!(- "Files may need manual recovery from: {display}\n\- Remove it to retry: rm -rf \"{display}\""- )- .context("Found leftover staging directory from an interrupted promote"));- }+ check_leftover_staging(&staging_path)?;// Ensure both worktrees are cleanlet main_working_tree = repo.worktree_at(main_path);@@ -290,26 +335,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {// Only lookup default_branch if needed for messaging (already resolved if no-arg from main)let default_branch = repo.default_branch();let is_restoring = default_branch.as_ref() == Some(&target_branch);-- if is_restoring {- // Restoring default branch to main worktree - no warning needed- eprintln!("{}", info_message("Restoring main worktree"));- } else {- // Creating mismatch - show warning and how to restore- eprintln!(- "{}",- warning_message("Promoting creates mismatched worktree state (shown as ⚑ in wt list)",)- );- // Only show restore hint if we know the default branch- if let Some(default) = &default_branch {- eprintln!(- "{}",- hint_message(cformat!(- "Run <underline>wt step promote {default}</> to restore canonical locations"- ))- );- }- }+ print_promote_announcement(is_restoring, default_branch.as_deref());// Discover gitignored entries BEFORE branch exchange — .gitignore rules belong// to the current branch and will change after `git switch`.diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 06b76aa80..456ec77ae 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -1,5 +1,6 @@//! `wt step prune` — remove worktrees and branches integrated into the default branch.+use std::collections::HashSet;use std::fs;use std::path::PathBuf;use std::time::Duration;@@ -10,7 +11,7 @@ use crossbeam_channel as chan;use rayon::prelude::*;use worktrunk::HookType;use worktrunk::config::UserConfig;-use worktrunk::git::{BranchDeletionMode, Repository, WorktreeInfo};+use worktrunk::git::{BranchDeletionMode, RefSnapshot, Repository, WorktreeInfo};use worktrunk::styling::{eprintln, hint_message, info_message, println, success_message};use super::super::command_approval::approve_or_skip;@@ -19,214 +20,170 @@ use super::super::hooks::HookAnnouncer;use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;-/// Remove worktrees and branches integrated into the default branch.-///-/// Handles four cases: live worktrees with branches (removed + branch deleted),-/// detached HEAD worktrees (directory removed, no branch to delete), stale worktree-/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).-/// Skips the main/primary worktree, locked worktrees, and worktrees younger than-/// `min_age`. Removes the current worktree last to trigger cd to primary.-pub fn step_prune(- dry_run: bool,- yes: bool,- min_age: &str,- foreground: bool,- format: crate::cli::SwitchFormat,-) -> anyhow::Result<()> {- let min_age_duration =- humantime::parse_duration(min_age).context("Invalid --min-age duration")?;-- let repo = Repository::current()?;- let config = UserConfig::load()?;+/// A candidate worktree or branch selected for removal.+struct Candidate {+ /// Original index in `check_items` (for deterministic output ordering)+ check_idx: usize,+ /// Branch name (None for detached HEAD worktrees)+ branch: Option<String>,+ /// Display label: branch name or abbreviated commit SHA+ label: String,+ /// Worktree path (for Path-based removal of detached worktrees)+ path: Option<PathBuf>,+ /// Current worktree, other worktree, or branch-only (no worktree)+ kind: CandidateKind,+}- // Capture once at command entry. Reused for every per-branch- // `integration_reason` probe later in this function.- let snapshot = repo.capture_refs().context("capturing repository refs")?;+enum CandidateKind {+ Current,+ Other,+ BranchOnly,+}- // Pass the local default branch (e.g. "main") directly — `integration_reason`- // ORs over local + upstream internally, so a branch merged into either side- // counts as integrated.- let integration_target = repo- .default_branch()- .context("cannot determine default branch")?;+impl CandidateKind {+ fn as_str(&self) -> &'static str {+ match self {+ CandidateKind::Current => "current",+ CandidateKind::Other => "worktree",+ CandidateKind::BranchOnly => "branch_only",+ }+ }+}- let worktrees = repo.list_worktrees().context("listing worktrees")?;- let current_root = repo- .current_worktree()- .root()- .context("resolving current worktree root")?- .to_path_buf();- let current_root = dunce::canonicalize(¤t_root).unwrap_or(current_root);- let now_secs = worktrunk::utils::epoch_now();+/// Where a candidate originated, used to drive integration checks and dry-run labels.+enum CheckSource {+ /// Worktree with directory gone (prunable)+ Prunable { branch: String },+ /// Linked worktree+ Linked { wt_idx: usize },+ /// Local branch without a worktree entry+ Orphan,+}- let default_branch = repo.default_branch();+struct CheckItem {+ integration_ref: String,+ source: CheckSource,+}- // Gather candidates: integrated worktrees + integrated branch-only refs- struct Candidate {- /// Original index in check_items (for deterministic output ordering)- check_idx: usize,- /// Branch name (None for detached HEAD worktrees)- branch: Option<String>,- /// Display label: branch name or abbreviated commit SHA- label: String,- /// Worktree path (for Path-based removal of detached worktrees)- path: Option<PathBuf>,- /// Current worktree, other worktree, or branch-only (no worktree)- kind: CandidateKind,- }- enum CandidateKind {- Current,- Other,- BranchOnly,- }+/// Per-candidate context displayed only in dry-run output.+struct DryRunInfo {+ reason_desc: String,+ effective_target: String,+ suffix: &'static str,+}- impl CandidateKind {- fn as_str(&self) -> &'static str {- match self {- CandidateKind::Current => "current",- CandidateKind::Other => "worktree",- CandidateKind::BranchOnly => "branch_only",+/// Build a human-readable count like "3 worktrees & branches".+///+/// Worktree + branch is the default pair (matching progress messages'+/// "worktree & branch" pattern). Unpaired items listed separately.+fn prune_summary(candidates: &[Candidate]) -> String {+ let mut worktree_with_branch = 0usize;+ let mut detached_worktree = 0usize;+ let mut branch_only = 0usize;+ for c in candidates {+ match (&c.kind, &c.branch) {+ (CandidateKind::BranchOnly, _) => branch_only += 1,+ (CandidateKind::Current | CandidateKind::Other, Some(_)) => {+ worktree_with_branch += 1;}- }- }-- /// Build a human-readable count like "3 worktrees & branches".- ///- /// Worktree + branch is the default pair (matching progress messages'- /// "worktree & branch" pattern). Unpaired items listed separately.- fn prune_summary(candidates: &[Candidate]) -> String {- let mut worktree_with_branch = 0usize;- let mut detached_worktree = 0usize;- let mut branch_only = 0usize;- for c in candidates {- match (&c.kind, &c.branch) {- (CandidateKind::BranchOnly, _) => branch_only += 1,- (CandidateKind::Current | CandidateKind::Other, Some(_)) => {- worktree_with_branch += 1;- }- (CandidateKind::Current | CandidateKind::Other, None) => {- detached_worktree += 1;- }+ (CandidateKind::Current | CandidateKind::Other, None) => {+ detached_worktree += 1;}}- let mut parts = Vec::new();- if worktree_with_branch > 0 {- let noun = if worktree_with_branch == 1 {- "worktree & branch"- } else {- "worktrees & branches"- };- parts.push(format!("{worktree_with_branch} {noun}"));- }- if detached_worktree > 0 {- let noun = if detached_worktree == 1 {- "worktree"- } else {- "worktrees"- };- parts.push(format!("{detached_worktree} {noun}"));- }- if branch_only > 0 {- let noun = if branch_only == 1 {- "branch"- } else {- "branches"- };- parts.push(format!("{branch_only} {noun}"));- }- parts.join(", ")}-- // For non-dry-run, approve hooks upfront so we can remove inline.- let run_hooks = if dry_run {- false // unused in dry-run path- } else {- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- approve_or_skip(- &ctx,- &[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ],- "Commands declined, continuing removal",- )?- };-- let mut removed: Vec<Candidate> = Vec::new();- let mut deferred_current: Option<Candidate> = None;- let mut skipped_young: Vec<String> = Vec::new();- // Track branches seen via worktree entries so we don't double-count- // in the orphan branch scan below.- let mut seen_branches: std::collections::HashSet<String> = std::collections::HashSet::new();-- /// Try to remove a candidate immediately. Returns Ok(true) if removed,- /// Ok(false) if skipped (preparation error), Err on execution error.- fn try_remove(- candidate: &Candidate,- repo: &Repository,- config: &UserConfig,- foreground: bool,- run_hooks: bool,- worktrees: &[WorktreeInfo],- snapshot: &worktrunk::git::RefSnapshot,- ) -> anyhow::Result<bool> {- let target = match candidate.kind {- CandidateKind::Current => RemoveTarget::Current,- CandidateKind::BranchOnly => RemoveTarget::Branch(- candidate- .branch- .as_ref()- .context("BranchOnly candidate missing branch")?,- ),- CandidateKind::Other => match &candidate.branch {- Some(branch) => RemoveTarget::Branch(branch),- None => RemoveTarget::Path(- candidate- .path- .as_ref()- .context("detached candidate missing path")?,- ),- },+ let mut parts = Vec::new();+ if worktree_with_branch > 0 {+ let noun = if worktree_with_branch == 1 {+ "worktree & branch"+ } else {+ "worktrees & branches"};- let plan = match repo.prepare_worktree_removal(- target,- BranchDeletionMode::SafeDelete,- false,- config,- None,- Some(worktrees),- Some(snapshot),- ) {- Ok(plan) => plan,- Err(_) => {- // prepare_worktree_removal is the gate: if the worktree can't- // be removed (dirty, locked, etc.), it's simply not selected.- return Ok(false);- }+ parts.push(format!("{worktree_with_branch} {noun}"));+ }+ if detached_worktree > 0 {+ let noun = if detached_worktree == 1 {+ "worktree"+ } else {+ "worktrees"};- let mut announcer = HookAnnouncer::new(repo, config, true);- handle_remove_output(&plan, foreground, run_hooks, true, &mut announcer)?;- announcer.flush()?;- Ok(true)+ parts.push(format!("{detached_worktree} {noun}"));}-- enum CheckSource {- /// Worktree with directory gone (prunable)- Prunable { branch: String },- /// Linked worktree- Linked { wt_idx: usize },- /// Local branch without a worktree entry- Orphan,+ if branch_only > 0 {+ let noun = if branch_only == 1 {+ "branch"+ } else {+ "branches"+ };+ parts.push(format!("{branch_only} {noun}"));}+ parts.join(", ")+}- struct CheckItem {- integration_ref: String,- source: CheckSource,- }+/// Try to remove a candidate immediately. Returns Ok(true) if removed,+/// Ok(false) if skipped (preparation error), Err on execution error.+fn try_remove(+ candidate: &Candidate,+ repo: &Repository,+ config: &UserConfig,+ foreground: bool,+ run_hooks: bool,+ worktrees: &[WorktreeInfo],+ snapshot: &RefSnapshot,+) -> anyhow::Result<bool> {+ let target = match candidate.kind {+ CandidateKind::Current => RemoveTarget::Current,+ CandidateKind::BranchOnly => RemoveTarget::Branch(+ candidate+ .branch+ .as_ref()+ .context("BranchOnly candidate missing branch")?,+ ),+ CandidateKind::Other => match &candidate.branch {+ Some(branch) => RemoveTarget::Branch(branch),+ None => RemoveTarget::Path(+ candidate+ .path+ .as_ref()+ .context("detached candidate missing path")?,+ ),+ },+ };+ let plan = match repo.prepare_worktree_removal(+ target,+ BranchDeletionMode::SafeDelete,+ false,+ config,+ None,+ Some(worktrees),+ Some(snapshot),+ ) {+ Ok(plan) => plan,+ Err(_) => {+ // prepare_worktree_removal is the gate: if the worktree can't+ // be removed (dirty, locked, etc.), it's simply not selected.+ return Ok(false);+ }+ };+ let mut announcer = HookAnnouncer::new(repo, config, true);+ handle_remove_output(&plan, foreground, run_hooks, true, &mut announcer)?;+ announcer.flush()?;+ Ok(true)+}+/// Walk the worktree list and the local branch list to build the set of+/// candidates whose integration status needs checking.+///+/// Returns the items in a deterministic order: worktree entries first+/// (preserving `worktrees` order), then orphan branches.+fn gather_check_items(+ repo: &Repository,+ worktrees: &[WorktreeInfo],+ default_branch: Option<&str>,+) -> anyhow::Result<Vec<CheckItem>> {let mut check_items: Vec<CheckItem> = Vec::new();+ // Track branches seen via worktree entries so we don't double-count+ // in the orphan branch scan below.+ let mut seen_branches: HashSet<String> = HashSet::new();for (idx, wt) in worktrees.iter().enumerate() {if let Some(branch) = &wt.branch {@@ -238,7 +195,7 @@ pub fn step_prune(}if let Some(branch) = &wt.branch- && default_branch.as_deref() == Some(branch.as_str())+ && default_branch == Some(branch.as_str()){continue;}@@ -280,7 +237,7 @@ pub fn step_prune(if seen_branches.contains(&branch) {continue;}- if default_branch.as_deref() == Some(branch.as_str()) {+ if default_branch == Some(branch.as_str()) {continue;}check_items.push(CheckItem {@@ -289,6 +246,190 @@ pub fn step_prune(});}+ Ok(check_items)+}++/// Resolve the age of a linked worktree from filesystem metadata.+///+/// Tries `git_dir.created()` first; on filesystems that don't track creation+/// time (e.g. older ext4) falls back to the `commondir` mtime, which git+/// touches when the worktree is first created.+fn worktree_age(+ repo: &Repository,+ wt: &WorktreeInfo,+ now_secs: u64,+) -> anyhow::Result<Option<Duration>> {+ let wt_tree = repo.worktree_at(&wt.path);+ let git_dir = wt_tree.git_dir().context("resolving worktree git dir")?;+ let metadata = fs::metadata(&git_dir).context("Failed to read worktree git dir")?;+ let created = metadata+ .created()+ .or_else(|_| fs::metadata(git_dir.join("commondir")).and_then(|m| m.modified()));++ let Ok(created) = created else {+ return Ok(None);+ };+ let Ok(created_epoch) = created.duration_since(std::time::UNIX_EPOCH) else {+ return Ok(None);+ };+ Ok(Some(Duration::from_secs(+ now_secs.saturating_sub(created_epoch.as_secs()),+ )))+}++/// Resolve the age of an orphan branch via its reflog creation timestamp.+///+/// Returns `None` if the reflog is missing or unparsable — callers treat+/// "unknown age" as "old enough", matching the previous inline behavior.+fn orphan_branch_age(repo: &Repository, branch: &str, now_secs: u64) -> Option<Duration> {+ let ref_name = format!("refs/heads/{branch}");+ let stdout = repo+ .run_command(&["reflog", "show", "--format=%ct", &ref_name])+ .ok()?;+ let created_epoch = stdout+ .trim()+ .lines()+ .last()+ .and_then(|s| s.parse::<u64>().ok())?;+ Some(Duration::from_secs(now_secs.saturating_sub(created_epoch)))+}++/// Render dry-run output (text or JSON) and the `Skipped (younger than ...)`+/// trailer. Returns once printing is complete; the caller exits early.+fn render_dry_run(+ mut dry_run_info: Vec<(Candidate, DryRunInfo)>,+ mut skipped_young: Vec<String>,+ min_age: &str,+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {+ // Sort by original check order for deterministic output regardless of+ // channel completion order.+ dry_run_info.sort_by_key(|(c, _)| c.check_idx);++ if format == crate::cli::SwitchFormat::Json {+ let items: Vec<serde_json::Value> = dry_run_info+ .iter()+ .map(|(c, info)| {+ serde_json::json!({+ "branch": c.branch,+ "path": c.path,+ "kind": c.kind.as_str(),+ "reason": info.reason_desc,+ "target": info.effective_target,+ })+ })+ .collect();+ println!("{}", serde_json::to_string_pretty(&items)?);+ return Ok(());+ }++ let mut dry_candidates = Vec::new();+ for (candidate, info) in dry_run_info {+ eprintln!(+ "{}",+ info_message(cformat!(+ "<bold>{}</>{} — {} {}",+ candidate.label,+ info.suffix,+ info.reason_desc,+ info.effective_target+ ))+ );+ dry_candidates.push(candidate);+ }++ // Report skipped worktrees (after candidates, before summary).+ // Sort for deterministic output regardless of channel completion order.+ skipped_young.sort();+ if !skipped_young.is_empty() {+ let names = skipped_young.join(", ");+ eprintln!(+ "{}",+ info_message(format!("Skipped {names} (younger than {min_age})"))+ );+ }++ if dry_candidates.is_empty() {+ if skipped_young.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ return Ok(());+ }+ eprintln!(+ "{}",+ hint_message(format!(+ "{} would be removed (dry run)",+ prune_summary(&dry_candidates)+ ))+ );+ Ok(())+}++/// Remove worktrees and branches integrated into the default branch.+///+/// Handles four cases: live worktrees with branches (removed + branch deleted),+/// detached HEAD worktrees (directory removed, no branch to delete), stale worktree+/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).+/// Skips the main/primary worktree, locked worktrees, and worktrees younger than+/// `min_age`. Removes the current worktree last to trigger cd to primary.+pub fn step_prune(+ dry_run: bool,+ yes: bool,+ min_age: &str,+ foreground: bool,+ format: crate::cli::SwitchFormat,+) -> anyhow::Result<()> {+ let min_age_duration =+ humantime::parse_duration(min_age).context("Invalid --min-age duration")?;++ let repo = Repository::current()?;+ let config = UserConfig::load()?;++ // Capture once at command entry. Reused for every per-branch+ // `integration_reason` probe later in this function.+ let snapshot = repo.capture_refs().context("capturing repository refs")?;++ // Pass the local default branch (e.g. "main") directly — `integration_reason`+ // ORs over local + upstream internally, so a branch merged into either side+ // counts as integrated.+ let integration_target = repo+ .default_branch()+ .context("cannot determine default branch")?;++ let worktrees = repo.list_worktrees().context("listing worktrees")?;+ let current_root = repo+ .current_worktree()+ .root()+ .context("resolving current worktree root")?+ .to_path_buf();+ let current_root = dunce::canonicalize(¤t_root).unwrap_or(current_root);+ let now_secs = worktrunk::utils::epoch_now();++ let default_branch = repo.default_branch();++ // For non-dry-run, approve hooks upfront so we can remove inline.+ let run_hooks = if dry_run {+ false // unused in dry-run path+ } else {+ let env = CommandEnv::for_action_branchless()?;+ let ctx = env.context(yes);+ approve_or_skip(+ &ctx,+ &[+ HookType::PreRemove,+ HookType::PostRemove,+ HookType::PostSwitch,+ ],+ "Commands declined, continuing removal",+ )?+ };++ let mut removed: Vec<Candidate> = Vec::new();+ let mut deferred_current: Option<Candidate> = None;+ let mut skipped_young: Vec<String> = Vec::new();++ let check_items = gather_check_items(&repo, worktrees, default_branch.as_deref())?;+// Parallel integration checks with inline removals.//// Spawn integration checks on a background thread via rayon par_iter,@@ -325,11 +466,6 @@ pub fn step_prune(});// Collect integration context alongside candidates for dry-run display.- struct DryRunInfo {- reason_desc: String,- effective_target: String,- suffix: &'static str,- }let mut dry_run_info: Vec<(Candidate, DryRunInfo)> = Vec::new();// Process results as they arrive from the channel.@@ -352,28 +488,18 @@ pub fn step_prune(// Skip recently-created worktrees that look "merged" because// they were just created from the default branch- if min_age_duration > Duration::ZERO {- let wt_tree = repo.worktree_at(&wt.path);- let git_dir = wt_tree.git_dir().context("resolving worktree git dir")?;- let metadata = fs::metadata(&git_dir).context("Failed to read worktree git dir")?;- let created = metadata.created().or_else(|_| {- fs::metadata(git_dir.join("commondir")).and_then(|m| m.modified())- });- if let Ok(created) = created- && let Ok(created_epoch) = created.duration_since(std::time::UNIX_EPOCH)- {- let age = Duration::from_secs(now_secs.saturating_sub(created_epoch.as_secs()));- if age < min_age_duration {- if !dry_run {- eprintln!(- "{}",- info_message(format!("Skipped {label} (younger than {min_age})"))- );- }- skipped_young.push(label);- continue;- }+ if min_age_duration > Duration::ZERO+ && let Some(age) = worktree_age(&repo, wt, now_secs)?+ && age < min_age_duration+ {+ if !dry_run {+ eprintln!(+ "{}",+ info_message(format!("Skipped {label} (younger than {min_age})"))+ );}+ skipped_young.push(label);+ continue;}let wt_path = dunce::canonicalize(&wt.path).unwrap_or(wt.path.clone());@@ -422,27 +548,19 @@ pub fn step_prune(};// Age check for orphan branches via reflog creation timestamp- if matches!(&item.source, CheckSource::Orphan) && min_age_duration > Duration::ZERO {- let ref_name = format!("refs/heads/{branch}");- if let Ok(stdout) = repo.run_command(&["reflog", "show", "--format=%ct", &ref_name])- && let Some(created_epoch) = stdout- .trim()- .lines()- .last()- .and_then(|s| s.parse::<u64>().ok())- {- let age = Duration::from_secs(now_secs.saturating_sub(created_epoch));- if age < min_age_duration {- if !dry_run {- eprintln!(- "{}",- info_message(format!("Skipped {branch} (younger than {min_age})"))- );- }- skipped_young.push(branch.clone());- continue;- }+ if matches!(&item.source, CheckSource::Orphan)+ && min_age_duration > Duration::ZERO+ && let Some(age) = orphan_branch_age(&repo, branch, now_secs)+ && age < min_age_duration+ {+ if !dry_run {+ eprintln!(+ "{}",+ info_message(format!("Skipped {branch} (younger than {min_age})"))+ );}+ skipped_young.push(branch.clone());+ continue;}let candidate = Candidate {@@ -475,67 +593,7 @@ pub fn step_prune(}if dry_run {- // Sort by original check order for deterministic output regardless of- // channel completion order.- dry_run_info.sort_by_key(|(c, _)| c.check_idx);-- if format == crate::cli::SwitchFormat::Json {- let items: Vec<serde_json::Value> = dry_run_info- .iter()- .map(|(c, info)| {- serde_json::json!({- "branch": c.branch,- "path": c.path,- "kind": c.kind.as_str(),- "reason": info.reason_desc,- "target": info.effective_target,- })- })- .collect();- println!("{}", serde_json::to_string_pretty(&items)?);- return Ok(());- }-- let mut dry_candidates = Vec::new();- for (candidate, info) in dry_run_info {- eprintln!(- "{}",- info_message(cformat!(- "<bold>{}</>{} — {} {}",- candidate.label,- info.suffix,- info.reason_desc,- info.effective_target- ))- );- dry_candidates.push(candidate);- }-- // Report skipped worktrees (after candidates, before summary).- // Sort for deterministic output regardless of channel completion order.- skipped_young.sort();- if !skipped_young.is_empty() {- let names = skipped_young.join(", ");- eprintln!(- "{}",- info_message(format!("Skipped {names} (younger than {min_age})"))- );- }-- if dry_candidates.is_empty() {- if skipped_young.is_empty() {- eprintln!("{}", info_message("No merged worktrees to remove"));- }- return Ok(());- }- eprintln!(- "{}",- hint_message(format!(- "{} would be removed (dry run)",- prune_summary(&dry_candidates)- ))- );- return Ok(());+ return render_dry_run(dry_run_info, skipped_young, min_age, format);}// Remove deferred current worktree last (cd-to-primary happens here)