Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(commands): move switch/remove orchestration out of main.rs (#3049)

Maximilian Roos3a6db54aa8b4
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 04ef73b78..d11090b24 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -29,7 +29,7 @@
//!
//! | Plan-backed hook | Runs in (the anchor) | Gate |
//! |---|---|---|
-//! | `pre-merge`, `pre-remove`, `post-remove` | the feature/removed worktree | `merge::approve_merge_plan`, `main.rs`'s `approve_remove`, `step::prune::approve_prune_hooks` |
+//! | `pre-merge`, `pre-remove`, `post-remove` | the feature/removed worktree | `merge::approve_merge_plan`, `remove::handle_remove_command`'s `approve_remove`, `step::prune::approve_prune_hooks` |
//! | `post-merge`, `post-switch` (after a removal) | the merge/removal destination | the same gates |
//! | `pre-start`, `post-start`, `post-switch` (on switch) | the new/destination worktree | `worktree::switch::approve_switch_hooks` |
//!
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 518019c01..2fd583221 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -10,6 +10,7 @@ use super::command_approval::approve_commit_template_append;
use super::command_executor::FailureStrategy;
use super::commit::{CommitOptions, HookGate};
use super::context::CommandEnv;
+use super::flag_pair;
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder, execute_planned_hook};
use super::hooks::HookAnnouncer;
use super::repository_ext::RepositoryCliExt;
@@ -33,12 +34,12 @@ pub struct MergeFlagOverrides {
impl MergeFlagOverrides {
pub fn from_cli(args: &crate::cli::MergeArgs) -> Self {
Self {
- squash: crate::flag_pair(args.squash, args.no_squash),
- commit: crate::flag_pair(args.commit, args.no_commit),
- rebase: crate::flag_pair(args.rebase, args.no_rebase),
- remove: crate::flag_pair(args.remove, args.no_remove),
- ff: crate::flag_pair(args.ff, args.no_ff),
- verify: crate::flag_pair(args.verify, args.no_hooks || args.no_verify),
+ squash: flag_pair(args.squash, args.no_squash),
+ commit: flag_pair(args.commit, args.no_commit),
+ rebase: flag_pair(args.rebase, args.no_rebase),
+ remove: flag_pair(args.remove, args.no_remove),
+ ff: flag_pair(args.ff, args.no_ff),
+ verify: flag_pair(args.verify, args.no_hooks || args.no_verify),
}
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index f0fc3fa5e..dd3c30e6d 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -23,6 +23,7 @@ pub(crate) mod pipeline_spec;
pub(crate) mod process;
pub(crate) mod project_config;
mod relocate;
+pub(crate) mod remove;
pub(crate) mod repository_ext;
mod run_pipeline;
pub(crate) mod statusline;
@@ -55,6 +56,7 @@ pub(crate) use list::handle_list;
pub(crate) use merge::{MergeFlagOverrides, MergeOptions, handle_merge};
#[cfg(unix)]
pub(crate) use picker::handle_picker;
+pub(crate) use remove::handle_remove_command;
pub(crate) use repository_ext::RemoveTarget;
pub(crate) use run_pipeline::run_pipeline;
pub(crate) use step::{
@@ -63,7 +65,7 @@ pub(crate) use step::{
step_relocate, step_show_squash_prompt, step_tether,
};
pub(crate) use worktree::{
- SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,
+ handle_switch_command, is_worktree_at_expected_path, resolve_worktree_arg,
worktree_display_name,
};
@@ -73,6 +75,28 @@ pub(crate) use worktrunk::shell::Shell;
use color_print::cformat;
use worktrunk::styling::{eprintln, format_with_gutter};
+pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
+ match (positive, negative) {
+ (true, _) => Some(true),
+ (_, true) => Some(false),
+ _ => None,
+ }
+}
+
+#[cfg(not(unix))]
+pub(crate) fn print_windows_picker_unavailable() {
+ use worktrunk::styling::{error_message, hint_message};
+
+ eprintln!(
+ "{}",
+ error_message("Interactive picker is not available on Windows")
+ );
+ eprintln!(
+ "{}",
+ hint_message(cformat!("Specify a branch: <underline>wt switch BRANCH</>"))
+ );
+}
+
/// Format command execution label with optional command name.
///
/// Examples:
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
new file mode 100644
index 000000000..cdf50449d
--- /dev/null
+++ b/src/commands/remove.rs
@@ -0,0 +1,392 @@
+//! The `wt remove` command: validate removal targets, approve hooks, and
+//! dispatch each removal to the output handler.
+
+use std::collections::HashSet;
+use std::path::Path;
+
+use anyhow::Context;
+use worktrunk::HookType;
+use worktrunk::config::UserConfig;
+use worktrunk::git::{BranchDeletionMode, ErrorExt, Repository, ResolvedWorktree};
+use worktrunk::styling::{eprintln, info_message};
+
+use crate::cli::{RemoveArgs, SwitchFormat};
+use crate::output::{BackgroundFallbackMode, handle_remove_output};
+
+use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
+use super::hooks::HookAnnouncer;
+use super::repository_ext::RepositoryCliExt;
+use super::worktree::RemoveResult;
+use super::{RemoveTarget, flag_pair, resolve_worktree_arg};
+
+/// Validated removal plans, categorized for ordered execution.
+///
+/// Multi-worktree removal validates all targets upfront, then executes in order:
+/// other worktrees first, branch-only cases next, current worktree last.
+struct RemovePlans {
+ others: Vec<RemoveResult>,
+ branch_only: Vec<RemoveResult>,
+ current: Option<RemoveResult>,
+ errors: Vec<anyhow::Error>,
+}
+
+impl RemovePlans {
+ fn has_valid_plans(&self) -> bool {
+ !self.others.is_empty() || !self.branch_only.is_empty() || self.current.is_some()
+ }
+
+ fn record_error(&mut self, e: anyhow::Error) {
+ // The remove command collects per-target errors and surfaces each
+ // individually (partial-success path). Render the typed
+ // diagnostic block when present so locked/dirty/etc. errors
+ // carry their hint, falling back to the short label otherwise.
+ let rendered = e.render_diagnostic().unwrap_or_else(|| e.to_string());
+ if !rendered.is_empty() {
+ eprintln!("{rendered}");
+ }
+ self.errors.push(e);
+ }
+}
+
+/// Validate all removal targets, returning categorized plans.
+///
+/// Resolves each branch name, determines whether it's the current worktree,
+/// another worktree, or branch-only, and prepares the removal plan.
+/// Errors are collected (not fatal) to support partial success.
+fn validate_remove_targets(
+ repo: &Repository,
+ branches: Vec<String>,
+ config: &UserConfig,
+ keep_branch: bool,
+ force_delete: bool,
+ force: bool,
+) -> RemovePlans {
+ let current_worktree = repo
+ .current_worktree()
+ .root()
+ .ok()
+ .and_then(|p| dunce::canonicalize(&p).ok());
+
+ // Dedupe inputs to avoid redundant planning/execution
+ let branches: Vec<_> = {
+ let mut seen = HashSet::new();
+ branches
+ .into_iter()
+ .filter(|b| seen.insert(b.clone()))
+ .collect()
+ };
+
+ let deletion_mode = BranchDeletionMode::from_flags(keep_branch, force_delete);
+ let worktrees = repo.list_worktrees().ok();
+
+ // Capture once for the validation loop. Validation only reads — actual
+ // removals run later in `handle_remove_output`, so ref state is stable
+ // across candidates here. Errors propagate to per-candidate calls, which
+ // fall back to capturing internally when None.
+ let snapshot = repo.capture_refs().ok();
+
+ let mut plans = RemovePlans {
+ others: Vec::new(),
+ branch_only: Vec::new(),
+ current: None,
+ errors: Vec::new(),
+ };
+
+ for branch_name in &branches {
+ let resolved = match resolve_worktree_arg(repo, branch_name) {
+ Ok(r) => r,
+ Err(e) => {
+ plans.record_error(e);
+ continue;
+ }
+ };
+
+ match resolved {
+ ResolvedWorktree::Worktree { path, branch } => {
+ // Use canonical paths to avoid symlink/normalization mismatches
+ let path_canonical = dunce::canonicalize(&path).unwrap_or(path);
+ let is_current = current_worktree.as_ref() == Some(&path_canonical);
+
+ if is_current {
+ match repo.prepare_worktree_removal(
+ RemoveTarget::Current,
+ deletion_mode,
+ force,
+ config,
+ None,
+ worktrees,
+ snapshot.as_ref(),
+ ) {
+ Ok(result) => plans.current = Some(result),
+ Err(e) => plans.record_error(e),
+ }
+ continue;
+ }
+
+ // Non-current worktree: remove by branch name, or by path for
+ // detached worktrees (which have no branch).
+ let target = if let Some(ref branch_name) = branch {
+ RemoveTarget::Branch(branch_name)
+ } else {
+ RemoveTarget::Path(&path_canonical)
+ };
+ match repo.prepare_worktree_removal(
+ target,
+ deletion_mode,
+ force,
+ config,
+ None,
+ worktrees,
+ snapshot.as_ref(),
+ ) {
+ Ok(result) => plans.others.push(result),
+ Err(e) => plans.record_error(e),
+ }
+ }
+ ResolvedWorktree::BranchOnly { branch } => {
+ match repo.prepare_worktree_removal(
+ RemoveTarget::Branch(&branch),
+ deletion_mode,
+ force,
+ config,
+ None,
+ worktrees,
+ snapshot.as_ref(),
+ ) {
+ Ok(result) => plans.branch_only.push(result),
+ Err(e) => plans.record_error(e),
+ }
+ }
+ }
+ }
+
+ plans
+}
+
+/// Entry point for the `wt remove` command.
+///
+/// # Command flow
+///
+/// 1. **Validate** all target worktrees up front via `prepare_worktree_removal`
+/// (clean check, branch-deletion-safety check, force-flag handling).
+/// 2. **Approve hooks** (`pre-remove`, `post-remove`, `post-switch`) if
+/// running interactively and any hooks are configured.
+/// 3. **Dispatch to `handle_remove_output`** per target. For each, the output
+/// handler runs `pre-remove` hooks in the worktree, then either:
+/// - **Foreground** (`--foreground`): stop fsmonitor → rename into
+/// `.git/wt/trash/<name>-<timestamp>/` → prune metadata → delete branch
+/// → synchronous `remove_dir_all` on the staged directory.
+/// - **Background** (default): stop fsmonitor → rename + prune +
+/// synchronous branch delete → spawn detached `rm -rf` on the staged
+/// directory. Cross-filesystem or locked worktrees fall back to
+/// `git worktree remove` in the detached process.
+/// 4. **Post-remove hooks** run in the background after dispatch.
+/// 5. **Internal sweep** (fire-and-forget, after primary output): stale
+/// `.git/wt/trash/` entries older than 24 hours are removed by a detached
+/// `rm -rf`, and orphaned `git fsmonitor--daemon` processes (worktree gone)
+/// are terminated. Runs last so it never delays the user-visible progress
+/// or success message. See [`super::process::run_internal_sweep`].
+pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
+ let json_mode = args.format == SwitchFormat::Json;
+ let verify = args.hooks.resolve();
+ UserConfig::load()
+ .context("Failed to load config")
+ .and_then(|config| {
+ let repo = Repository::current().context("Failed to remove worktree")?;
+
+ // CLI flags override config; otherwise fall through to [remove] delete-branch
+ // (defaults to true).
+ let project = repo.project_identifier().ok();
+ let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);
+ let delete_branch =
+ cli_override.unwrap_or_else(|| config.remove(project.as_deref()).delete_branch());
+
+ // Validate conflicting flags
+ if !delete_branch && args.force_delete {
+ return Err(worktrunk::git::GitError::Other {
+ message: "Cannot use --force-delete with delete-branch=false (set via --no-delete-branch or [remove] delete-branch = false)".into(),
+ }
+ .into());
+ }
+
+ // Helper: build and approve, once, the frozen hook plan the
+ // removal will run. Every hook (`pre-remove` / `post-remove` per
+ // removed worktree, `post-switch` per post-removal destination) is
+ // selected from the invoking worktree's `.config/wt.toml` — the
+ // worktree `wt remove` ran in. `!verify` (`--no-hooks`) or a
+ // declined prompt yields an empty plan — every executor then runs
+ // no project hooks.
+ let approve_remove = |removed_worktree_paths: &[&Path],
+ destination_paths: &[&Path],
+ yes: bool|
+ -> anyhow::Result<ApprovedHookPlan> {
+ if !verify {
+ return Ok(ApprovedHookPlan::empty());
+ }
+ // Non-fatal: a worktree with no project hooks must remove even
+ // when the project identifier can't be resolved (the plan ends
+ // up empty and `approve` never needs it). Matches the pre-plan
+ // behaviour where the empty-batch fast path ran first.
+ let project_id = repo.project_identifier().ok();
+ let pid = project_id.as_deref();
+ let project_config = repo.load_project_config()?;
+ let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);
+ for &wt_path in removed_worktree_paths {
+ builder.add(wt_path, &[HookType::PreRemove, HookType::PostRemove]);
+ }
+ let mut seen_dests = std::collections::HashSet::new();
+ for &dest in destination_paths {
+ if !seen_dests.insert(dest) {
+ continue;
+ }
+ builder.add(dest, &[HookType::PostSwitch]);
+ }
+ match builder.finish().approve(pid, yes)? {
+ Some(plan) => Ok(plan),
+ None => {
+ eprintln!(
+ "{}",
+ info_message("Commands declined, continuing removal without hooks")
+ );
+ Ok(ApprovedHookPlan::empty())
+ }
+ }
+ };
+
+ let branches = args.branches;
+
+ if branches.is_empty() {
+ // Single worktree removal: validate FIRST, then approve, then execute
+ let result = repo
+ .prepare_worktree_removal(
+ RemoveTarget::Current,
+ BranchDeletionMode::from_flags(!delete_branch, args.force_delete),
+ args.force,
+ &config,
+ None,
+ None,
+ None,
+ )
+ .context("Failed to remove worktree")?;
+
+ // Early exit for benchmarking time-to-first-output
+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
+ return Ok(());
+ }
+
+ // "Approve at the Gate": approval happens AFTER validation passes
+ let plan = approve_remove(
+ result.removed_worktree_path().as_slice(),
+ result.destination_path().as_slice(),
+ yes,
+ )?;
+
+ let mut announcer = HookAnnouncer::new(&repo, false);
+ handle_remove_output(
+ &result,
+ args.foreground,
+ &plan,
+ false,
+ false,
+ &mut announcer,
+ BackgroundFallbackMode::Detached,
+ )?;
+ announcer.flush()?;
+ if json_mode {
+ let json = serde_json::json!([result.to_json()]);
+ println!("{}", serde_json::to_string_pretty(&json)?);
+ }
+ // Fire-and-forget repo-wide internal cleanup (stale trash +
+ // orphaned fsmonitor daemons) — runs after primary output so
+ // it never delays the user-visible progress/success message.
+ super::process::run_internal_sweep(&repo);
+ Ok(())
+ } else {
+ // Multi-worktree removal: validate ALL first, then approve, then execute
+ let plans = validate_remove_targets(
+ &repo,
+ branches,
+ &config,
+ !delete_branch,
+ args.force_delete,
+ args.force,
+ );
+
+ if !plans.has_valid_plans() {
+ anyhow::bail!("");
+ }
+
+ // Early exit for benchmarking time-to-first-output
+ if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
+ return Ok(());
+ }
+
+ // Approve hooks (only if we have valid plans). Each removed
+ // worktree's `pre-remove` / `post-remove` is approved against
+ // that worktree's config, and its `post-switch` against the
+ // worktree the user lands in — see `approve_remove` above.
+ // (`destination_targets` is mostly the primary worktree
+ // repeated; the helper dedups by template.)
+ let all_plans = || {
+ plans
+ .others
+ .iter()
+ .chain(&plans.branch_only)
+ .chain(plans.current.iter())
+ };
+ let removed_targets: Vec<&Path> =
+ all_plans().filter_map(|r| r.removed_worktree_path()).collect();
+ let destination_targets: Vec<&Path> =
+ all_plans().filter_map(|r| r.destination_path()).collect();
+ let plan = approve_remove(&removed_targets, &destination_targets, yes)?;
+
+ // Execute all validated plans: others first, branch-only next, current last
+ let show_branch =
+ plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;
+ let run = |result: &RemoveResult| -> anyhow::Result<()> {
+ let mut announcer = HookAnnouncer::new(&repo, show_branch);
+ handle_remove_output(
+ result,
+ args.foreground,
+ &plan,
+ false,
+ false,
+ &mut announcer,
+ BackgroundFallbackMode::Detached,
+ )?;
+ announcer.flush()
+ };
+ for result in &plans.others {
+ run(result)?;
+ }
+ for result in &plans.branch_only {
+ run(result)?;
+ }
+ if let Some(ref result) = plans.current {
+ run(result)?;
+ }
+
+ if json_mode {
+ let json_items: Vec<serde_json::Value> = plans
+ .others
+ .iter()
+ .chain(&plans.branch_only)
+ .chain(plans.current.as_ref())
+ .map(RemoveResult::to_json)
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&json_items)?);
+ }
+
+ // Fire-and-forget repo-wide internal cleanup (stale trash +
+ // orphaned fsmonitor daemons) — runs after primary output so
+ // it never delays the user-visible progress/success messages.
+ super::process::run_internal_sweep(&repo);
+
+ if !plans.errors.is_empty() {
+ anyhow::bail!("");
+ }
+
+ Ok(())
+ }
+ })
+}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 4de2b51a5..7b361f745 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -308,8 +308,8 @@ impl RepositoryCliExt for Repository {
// No `.config/wt.toml` snapshot: `pre-remove` / `post-remove` were
// selected and frozen into the `ApprovedHookPlan` at the gate
- // (`main.rs`'s `approve_remove`), anchored at this worktree's path, so
- // the executor needs no config — it runs only the frozen plan.
+ // (`remove.rs`'s `approve_remove`), anchored at this worktree's path,
+ // so the executor needs no config — it runs only the frozen plan.
Ok(RemoveResult::RemovedWorktree {
main_path,
worktree_path,
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 3e5a93649..c386b5e50 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -97,5 +97,5 @@ pub use resolve::{
};
#[cfg(unix)]
pub(crate) use switch::SwitchPipeline;
-pub use switch::{SwitchOptions, run_switch};
+pub use switch::handle_switch_command;
pub use types::{MergeOperations, RemoveResult, SwitchBranchInfo, SwitchResult};
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index aeb170a1c..1985130c1 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -32,11 +32,12 @@ use worktrunk::styling::{
use super::resolve::{compute_worktree_path, offer_bare_repo_worktree_path_fix, path_mismatch};
use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};
-use crate::cli::SwitchFormat;
+use crate::cli::{SwitchArgs, SwitchFormat};
use crate::commands::backup::back_up_clobbered_path_now;
use crate::commands::command_approval::approve_hooks;
use crate::commands::command_executor::FailureStrategy;
use crate::commands::command_executor::{CommandContext, build_hook_context};
+use crate::commands::flag_pair;
use crate::commands::hook_plan::{ApprovedHookPlan, HookPlanBuilder, register_planned};
use crate::commands::hooks::{HookAnnouncer, execute_hook};
use crate::commands::template_vars::TemplateVars;
@@ -1298,18 +1299,18 @@ fn emit_switch_json(
}
/// Options for the switch command
-pub struct SwitchOptions<'a> {
- pub branch: &'a str,
- pub create: bool,
- pub base: Option<&'a str>,
- pub execute: Option<&'a str>,
- pub execute_args: &'a [String],
- pub yes: bool,
- pub clobber: bool,
+struct SwitchOptions<'a> {
+ branch: &'a str,
+ create: bool,
+ base: Option<&'a str>,
+ execute: Option<&'a str>,
+ execute_args: &'a [String],
+ yes: bool,
+ clobber: bool,
/// Resolved from --cd/--no-cd flags: Some(true) = cd, Some(false) = no cd, None = use config
- pub change_dir: Option<bool>,
- pub verify: bool,
- pub format: crate::cli::SwitchFormat,
+ change_dir: Option<bool>,
+ verify: bool,
+ format: crate::cli::SwitchFormat,
}
/// Run pre-switch hooks before branch resolution or worktree creation.
@@ -1768,7 +1769,7 @@ impl SwitchPipeline<'_> {
}
/// Handle the switch command.
-pub fn run_switch(
+fn run_switch(
opts: SwitchOptions<'_>,
config: &mut UserConfig,
binary_name: &str,
@@ -1827,6 +1828,64 @@ pub fn run_switch(
.run()
}
+/// Entry point for the `wt switch` command.
+pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()> {
+ let verify = args.hooks.resolve();
+
+ // With no branch argument, `wt switch` opens a TUI picker — config
+ // deprecation warnings would render above the picker and push it down.
+ // They're still shown by other commands (`wt list`, `wt merge`, …).
+ if args.branch.is_none() {
+ worktrunk::config::suppress_warnings();
+ }
+
+ UserConfig::load()
+ .context("Failed to load config")
+ .and_then(|mut config| {
+ // No branch argument: open interactive picker
+ let change_dir_flag = flag_pair(args.cd, args.no_cd);
+
+ let Some(branch) = args.branch else {
+ #[cfg(unix)]
+ {
+ return crate::commands::handle_picker(
+ args.branches,
+ args.remotes,
+ change_dir_flag,
+ args.format,
+ );
+ }
+
+ #[cfg(not(unix))]
+ {
+ use worktrunk::git::WorktrunkError;
+ // Suppress unused variable warnings on Windows
+ let _ = (args.branches, args.remotes, change_dir_flag);
+
+ crate::commands::print_windows_picker_unavailable();
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());
+ }
+ };
+
+ run_switch(
+ SwitchOptions {
+ branch: &branch,
+ create: args.create,
+ base: args.base.as_deref(),
+ execute: args.execute.as_deref(),
+ execute_args: &args.execute_args,
+ yes,
+ clobber: args.clobber,
+ change_dir: change_dir_flag,
+ verify,
+ format: args.format,
+ },
+ &mut config,
+ &crate::binary_name(),
+ )
+ })
+}
+
/// Whether `value` is a single clean program-name token — the form `--execute`
/// keeps accepting unchanged once it switches to the argv input model.
///
diff --git a/src/main.rs b/src/main.rs
index 181558243..6a1951527 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,24 +1,16 @@
-use std::collections::HashSet;
-use std::path::Path;
-
-use anyhow::Context;
use clap::FromArgMatches;
use clap::error::ErrorKind as ClapErrorKind;
use color_print::{ceprintln, cformat};
use std::process;
-use worktrunk::config::{UserConfig, set_config_path};
+use worktrunk::config::set_config_path;
use worktrunk::git::{
- ErrorExt, Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint,
- set_base_path,
+ ErrorExt, Repository, WorktrunkError, current_or_recover, cwd_removed_hint, set_base_path,
};
use worktrunk::styling::{
eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,
};
-use commands::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use commands::hooks::HookAnnouncer;
-use commands::worktree::RemoveResult;
-use worktrunk::HookType;
mod cli;
mod commands;
@@ -46,32 +38,29 @@ pub(crate) use crate::cli::OutputFormat;
use commands::commit::HookGate;
#[cfg(unix)]
use commands::handle_picker;
-use commands::repository_ext::RepositoryCliExt;
use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
use commands::{
- HookCliArgs, MergeFlagOverrides, MergeOptions, RebaseResult, RemoveTarget, SquashResult,
- SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show,
- handle_cache_clear, handle_cache_get, handle_claude_install, handle_claude_install_statusline,
+ HookCliArgs, MergeFlagOverrides, MergeOptions, RebaseResult, SquashResult, add_approvals,
+ clear_approvals, flag_pair, handle_alias_dry_run, handle_alias_show, handle_cache_clear,
+ handle_cache_get, handle_claude_install, handle_claude_install_statusline,
handle_claude_uninstall, handle_codex_install, handle_codex_uninstall, handle_completions,
handle_config_create, handle_config_show, handle_config_update, handle_configure_shell,
handle_custom_command, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,
handle_list, handle_logs_list, handle_merge, handle_opencode_install,
- handle_opencode_uninstall, handle_promote, handle_rebase, handle_show_theme, handle_squash,
- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
- handle_state_show, handle_unconfigure_shell, handle_vars_clear, handle_vars_get,
- handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch, step_commit,
+ handle_opencode_uninstall, handle_promote, handle_rebase, handle_remove_command,
+ handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,
+ handle_state_set, handle_state_show, handle_switch_command, handle_unconfigure_shell,
+ handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set, run_hook, step_commit,
step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate, step_tether,
};
-use output::{BackgroundFallbackMode, handle_remove_output};
-use worktrunk::git::BranchDeletionMode;
use cli::{
ApprovalsCommand, CacheAction, CiStatusAction, Cli, Commands, ConfigAliasCommand,
ConfigCommand, ConfigPluginsClaudeCommand, ConfigPluginsCodexCommand, ConfigPluginsCommand,
ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction, GlobalFormatFlag,
HintsAction, HookCommand, HookOptions, ListArgs, ListSubcommand, LogsAction, MarkerAction,
- MergeArgs, PreviousBranchAction, RemoveArgs, StateCommand, StateWrite, StepCommand, SwitchArgs,
- SwitchFormat, VarsAction,
+ MergeArgs, PreviousBranchAction, StateCommand, StateWrite, StepCommand, SwitchFormat,
+ VarsAction,
};
/// Render a clap error to stderr, appending a wt-specific nested-subcommand
@@ -117,26 +106,6 @@ pub(crate) fn enhance_clap_error(err: clap::Error) -> anyhow::Error {
WorktrunkError::AlreadyDisplayed { exit_code }.into()
}
-#[cfg(not(unix))]
-fn print_windows_picker_unavailable() {
- eprintln!(
- "{}",
- error_message("Interactive picker is not available on Windows")
- );
- eprintln!(
- "{}",
- hint_message(cformat!("Specify a branch: <underline>wt switch BRANCH</>"))
- );
-}
-
-pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
- match (positive, negative) {
- (true, _) => Some(true),
- (_, true) => Some(false),
- _ => None,
- }
-}
-
fn warn_select_deprecated() {
eprintln!(
"{}",
@@ -710,439 +679,10 @@ fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {
fn handle_select_command(_branches: bool, _remotes: bool) -> anyhow::Result<()> {
use worktrunk::git::WorktrunkError;
warn_select_deprecated();
- print_windows_picker_unavailable();
+ commands::print_windows_picker_unavailable();
Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())
}
-fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()> {
- let verify = args.hooks.resolve();
-
- // With no branch argument, `wt switch` opens a TUI picker — config
- // deprecation warnings would render above the picker and push it down.
- // They're still shown by other commands (`wt list`, `wt merge`, …).
- if args.branch.is_none() {
- worktrunk::config::suppress_warnings();
- }
-
- UserConfig::load()
- .context("Failed to load config")
- .and_then(|mut config| {
- // No branch argument: open interactive picker
- let change_dir_flag = flag_pair(args.cd, args.no_cd);
-
- let Some(branch) = args.branch else {
- #[cfg(unix)]
- {
- return handle_picker(
- args.branches,
- args.remotes,
- change_dir_flag,
- args.format,
- );
- }
-
- #[cfg(not(unix))]
- {
- use worktrunk::git::WorktrunkError;
- // Suppress unused variable warnings on Windows
- let _ = (args.branches, args.remotes, change_dir_flag);
-
- print_windows_picker_unavailable();
- return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());
- }
- };
-
- run_switch(
- SwitchOptions {
- branch: &branch,
- create: args.create,
- base: args.base.as_deref(),
- execute: args.execute.as_deref(),
- execute_args: &args.execute_args,
- yes,
- clobber: args.clobber,
- change_dir: change_dir_flag,
- verify,
- format: args.format,
- },
- &mut config,
- &binary_name(),
- )
- })
-}
-
-/// Validated removal plans, categorized for ordered execution.
-///
-/// Multi-worktree removal validates all targets upfront, then executes in order:
-/// other worktrees first, branch-only cases next, current worktree last.
-struct RemovePlans {
- others: Vec<RemoveResult>,
- branch_only: Vec<RemoveResult>,
- current: Option<RemoveResult>,
- errors: Vec<anyhow::Error>,
-}
-
-impl RemovePlans {
- fn has_valid_plans(&self) -> bool {
- !self.others.is_empty() || !self.branch_only.is_empty() || self.current.is_some()
- }
-
- fn record_error(&mut self, e: anyhow::Error) {
- // The remove command collects per-target errors and surfaces each
- // individually (partial-success path). Render the typed
- // diagnostic block when present so locked/dirty/etc. errors
- // carry their hint, falling back to the short label otherwise.
- let rendered = e.render_diagnostic().unwrap_or_else(|| e.to_string());
- if !rendered.is_empty() {
- eprintln!("{rendered}");
- }
- self.errors.push(e);
- }
-}
-
-/// Validate all removal targets, returning categorized plans.
-///
-/// Resolves each branch name, determines whether it's the current worktree,
-/// another worktree, or branch-only, and prepares the removal plan.
-/// Errors are collected (not fatal) to support partial success.
-fn validate_remove_targets(
- repo: &Repository,
- branches: Vec<String>,
- config: &UserConfig,
- keep_branch: bool,
- force_delete: bool,
- force: bool,
-) -> RemovePlans {
- let current_worktree = repo
- .current_worktree()
- .root()
- .ok()
- .and_then(|p| dunce::canonicalize(&p).ok());
-
- // Dedupe inputs to avoid redundant planning/execution
- let branches: Vec<_> = {
- let mut seen = HashSet::new();
- branches
- .into_iter()
- .filter(|b| seen.insert(b.clone()))
- .collect()
- };
-
- let deletion_mode = BranchDeletionMode::from_flags(keep_branch, force_delete);
- let worktrees = repo.list_worktrees().ok();
-
- // Capture once for the validation loop. Validation only reads — actual
- // removals run later in `handle_remove_output`, so ref state is stable
- // across candidates here. Errors propagate to per-candidate calls, which
- // fall back to capturing internally when None.
- let snapshot = repo.capture_refs().ok();
-
- let mut plans = RemovePlans {
- others: Vec::new(),
- branch_only: Vec::new(),
- current: None,
- errors: Vec::new(),
- };
-
- for branch_name in &branches {
- let resolved = match resolve_worktree_arg(repo, branch_name) {
- Ok(r) => r,
- Err(e) => {
- plans.record_error(e);
- continue;
- }
- };
-
- match resolved {
- ResolvedWorktree::Worktree { path, branch } => {
- // Use canonical paths to avoid symlink/normalization mismatches
- let path_canonical = dunce::canonicalize(&path).unwrap_or(path);
- let is_current = current_worktree.as_ref() == Some(&path_canonical);
-
- if is_current {
- match repo.prepare_worktree_removal(
- RemoveTarget::Current,
- deletion_mode,
- force,
- config,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.current = Some(result),
- Err(e) => plans.record_error(e),
- }
- continue;
- }
-
- // Non-current worktree: remove by branch name, or by path for
- // detached worktrees (which have no branch).
- let target = if let Some(ref branch_name) = branch {
- RemoveTarget::Branch(branch_name)
- } else {
- RemoveTarget::Path(&path_canonical)
- };
- match repo.prepare_worktree_removal(
- target,
- deletion_mode,
- force,
- config,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.others.push(result),
- Err(e) => plans.record_error(e),
- }
- }
- ResolvedWorktree::BranchOnly { branch } => {
- match repo.prepare_worktree_removal(
- RemoveTarget::Branch(&branch),
- deletion_mode,
- force,
- config,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.branch_only.push(result),
- Err(e) => plans.record_error(e),
- }
- }
- }
- }
-
- plans
-}
-
-/// Entry point for the `wt remove` command.
-///
-/// # Command flow
-///
-/// 1. **Validate** all target worktrees up front via `prepare_worktree_removal`
-/// (clean check, branch-deletion-safety check, force-flag handling).
-/// 2. **Approve hooks** (`pre-remove`, `post-remove`, `post-switch`) if
-/// running interactively and any hooks are configured.
-/// 3. **Dispatch to `handle_remove_output`** per target. For each, the output
-/// handler runs `pre-remove` hooks in the worktree, then either:
-/// - **Foreground** (`--foreground`): stop fsmonitor → rename into
-/// `.git/wt/trash/<name>-<timestamp>/` → prune metadata → delete branch
-/// → synchronous `remove_dir_all` on the staged directory.
-/// - **Background** (default): stop fsmonitor → rename + prune +
-/// synchronous branch delete → spawn detached `rm -rf` on the staged
-/// directory. Cross-filesystem or locked worktrees fall back to
-/// `git worktree remove` in the detached process.
-/// 4. **Post-remove hooks** run in the background after dispatch.
-/// 5. **Internal sweep** (fire-and-forget, after primary output): stale
-/// `.git/wt/trash/` entries older than 24 hours are removed by a detached
-/// `rm -rf`, and orphaned `git fsmonitor--daemon` processes (worktree gone)
-/// are terminated. Runs last so it never delays the user-visible progress
-/// or success message. See [`commands::process::run_internal_sweep`].
-fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
- let json_mode = args.format == SwitchFormat::Json;
- let verify = args.hooks.resolve();
- UserConfig::load()
- .context("Failed to load config")
- .and_then(|config| {
- let repo = Repository::current().context("Failed to remove worktree")?;
-
- // CLI flags override config; otherwise fall through to [remove] delete-branch
- // (defaults to true).
- let project = repo.project_identifier().ok();
- let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);
- let delete_branch =
- cli_override.unwrap_or_else(|| config.remove(project.as_deref()).delete_branch());
-
- // Validate conflicting flags
- if !delete_branch && args.force_delete {
- return Err(worktrunk::git::GitError::Other {
- message: "Cannot use --force-delete with delete-branch=false (set via --no-delete-branch or [remove] delete-branch = false)".into(),
- }
- .into());
- }
-
- // Helper: build and approve, once, the frozen hook plan the
- // removal will run. Every hook (`pre-remove` / `post-remove` per
- // removed worktree, `post-switch` per post-removal destination) is
- // selected from the invoking worktree's `.config/wt.toml` — the
- // worktree `wt remove` ran in. `!verify` (`--no-hooks`) or a
- // declined prompt yields an empty plan — every executor then runs
- // no project hooks.
- let approve_remove = |removed_worktree_paths: &[&Path],
- destination_paths: &[&Path],
- yes: bool|
- -> anyhow::Result<ApprovedHookPlan> {
- if !verify {
- return Ok(ApprovedHookPlan::empty());
- }
- // Non-fatal: a worktree with no project hooks must remove even
- // when the project identifier can't be resolved (the plan ends
- // up empty and `approve` never needs it). Matches the pre-plan
- // behaviour where the empty-batch fast path ran first.
- let project_id = repo.project_identifier().ok();
- let pid = project_id.as_deref();
- let project_config = repo.load_project_config()?;
- let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);
- for &wt_path in removed_worktree_paths {
- builder.add(wt_path, &[HookType::PreRemove, HookType::PostRemove]);
- }
- let mut seen_dests = std::collections::HashSet::new();
- for &dest in destination_paths {
- if !seen_dests.insert(dest) {
- continue;
- }
- builder.add(dest, &[HookType::PostSwitch]);
- }
- match builder.finish().approve(pid, yes)? {
- Some(plan) => Ok(plan),
- None => {
- eprintln!(
- "{}",
- info_message("Commands declined, continuing removal without hooks")
- );
- Ok(ApprovedHookPlan::empty())
- }
- }
- };
-
- let branches = args.branches;
-
- if branches.is_empty() {
- // Single worktree removal: validate FIRST, then approve, then execute
- let result = repo
- .prepare_worktree_removal(
- RemoveTarget::Current,
- BranchDeletionMode::from_flags(!delete_branch, args.force_delete),
- args.force,
- &config,
- None,
- None,
- None,
- )
- .context("Failed to remove worktree")?;
-
- // Early exit for benchmarking time-to-first-output
- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
- return Ok(());
- }
-
- // "Approve at the Gate": approval happens AFTER validation passes
- let plan = approve_remove(
- result.removed_worktree_path().as_slice(),
- result.destination_path().as_slice(),
- yes,
- )?;
-
- let mut announcer = HookAnnouncer::new(&repo, false);
- handle_remove_output(
- &result,
- args.foreground,
- &plan,
- false,
- false,
- &mut announcer,
- BackgroundFallbackMode::Detached,
- )?;
- announcer.flush()?;
- if json_mode {
- let json = serde_json::json!([result.to_json()]);
- println!("{}", serde_json::to_string_pretty(&json)?);
- }
- // Fire-and-forget repo-wide internal cleanup (stale trash +
- // orphaned fsmonitor daemons) — runs after primary output so
- // it never delays the user-visible progress/success message.
- commands::process::run_internal_sweep(&repo);
- Ok(())
- } else {
- // Multi-worktree removal: validate ALL first, then approve, then execute
- let plans = validate_remove_targets(
- &repo,
- branches,
- &config,
- !delete_branch,
- args.force_delete,
- args.force,
- );
-
- if !plans.has_valid_plans() {
- anyhow::bail!("");
- }
-
- // Early exit for benchmarking time-to-first-output
- if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
- return Ok(());
- }
-
- // Approve hooks (only if we have valid plans). Each removed
- // worktree's `pre-remove` / `post-remove` is approved against
- // that worktree's config, and its `post-switch` against the
- // worktree the user lands in — see `approve_remove` above.
- // (`destination_targets` is mostly the primary worktree
- // repeated; the helper dedups by template.)
- let all_plans = || {
- plans
- .others
- .iter()
- .chain(&plans.branch_only)
- .chain(plans.current.iter())
- };
- let removed_targets: Vec<&Path> =
- all_plans().filter_map(|r| r.removed_worktree_path()).collect();
- let destination_targets: Vec<&Path> =
- all_plans().filter_map(|r| r.destination_path()).collect();
- let plan = approve_remove(&removed_targets, &destination_targets, yes)?;
-
- // Execute all validated plans: others first, branch-only next, current last
- let show_branch =
- plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;
- let run = |result: &RemoveResult| -> anyhow::Result<()> {
- let mut announcer = HookAnnouncer::new(&repo, show_branch);
- handle_remove_output(
- result,
- args.foreground,
- &plan,
- false,
- false,
- &mut announcer,
- BackgroundFallbackMode::Detached,
- )?;
- announcer.flush()
- };
- for result in &plans.others {
- run(result)?;
- }
- for result in &plans.branch_only {
- run(result)?;
- }
- if let Some(ref result) = plans.current {
- run(result)?;
- }
-
- if json_mode {
- let json_items: Vec<serde_json::Value> = plans
- .others
- .iter()
- .chain(&plans.branch_only)
- .chain(plans.current.as_ref())
- .map(RemoveResult::to_json)
- .collect();
- println!("{}", serde_json::to_string_pretty(&json_items)?);
- }
-
- // Fire-and-forget repo-wide internal cleanup (stale trash +
- // orphaned fsmonitor daemons) — runs after primary output so
- // it never delays the user-visible progress/success messages.
- commands::process::run_internal_sweep(&repo);
-
- if !plans.errors.is_empty() {
- anyhow::bail!("");
- }
-
- Ok(())
- }
- })
-}
-
/// Rayon thread count sized for mixed git+network I/O workloads.
///
/// `wt list` and the picker's preview pre-compute both run git subprocesses
@@ -1569,6 +1109,7 @@ fn main() {
#[cfg(test)]
mod tests {
use super::*;
+ use anyhow::Context;
use worktrunk::git::CommandError;
fn permission_denied_command_error() -> CommandError {
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index d52e3ee04..6b7adbfa6 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -63,6 +63,8 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"for_each.rs",
// JSON output for wt merge --format=json
"merge.rs",
+ // JSON output for wt remove --format=json
+ "remove.rs",
// Hook listing output for wt hook show (paged)
"hook_commands.rs",
];