Skip to content

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

Extract handler functions from main() dispatch (#1394)

Maximilian Roosc16d746e571d
diff --git a/src/main.rs b/src/main.rs
index a3526e22d..396d42488 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -10,11 +10,8 @@ use worktrunk::config::{UserConfig, set_config_path};
use worktrunk::git::{
Repository, ResolvedWorktree, current_or_recover, cwd_removed_hint, exit_code, set_base_path,
};
-use worktrunk::path::format_path_for_display;
-use worktrunk::shell::extract_filename_from_path;
use worktrunk::styling::{
- eprintln, error_message, format_with_gutter, hint_message, info_message, success_message,
- warning_message,
+ eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,
};
use commands::command_approval::approve_hooks;
@@ -231,6 +228,508 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {
}
}
+fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {
+ match action {
+ StepCommand::Commit {
+ yes,
+ verify,
+ stage,
+ show_prompt,
+ } => step_commit(yes, verify, stage, show_prompt),
+ StepCommand::Squash {
+ target,
+ yes,
+ verify,
+ stage,
+ show_prompt,
+ } => {
+ // Handle --show-prompt early: just build and output the prompt
+ if show_prompt {
+ commands::step_show_squash_prompt(target.as_deref())
+ } else {
+ // Approval is handled inside handle_squash (like step_commit)
+ handle_squash(target.as_deref(), yes, verify, stage).map(|result| match result {
+ SquashResult::Squashed | SquashResult::NoNetChanges => {}
+ SquashResult::NoCommitsAhead(branch) => {
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Nothing to squash; no commits ahead of {branch}"
+ ))
+ );
+ }
+ SquashResult::AlreadySingleCommit => {
+ eprintln!(
+ "{}",
+ info_message("Nothing to squash; already a single commit")
+ );
+ }
+ })
+ }
+ }
+ StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),
+ StepCommand::Rebase { target } => {
+ handle_rebase(target.as_deref()).map(|result| match result {
+ RebaseResult::Rebased => (),
+ RebaseResult::UpToDate(branch) => {
+ eprintln!(
+ "{}",
+ info_message(cformat!("Already up to date with <bold>{branch}</>"))
+ );
+ }
+ })
+ }
+ StepCommand::Diff { target, extra_args } => step_diff(target.as_deref(), &extra_args),
+ StepCommand::CopyIgnored {
+ from,
+ to,
+ dry_run,
+ force,
+ } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force),
+ StepCommand::ForEach { args } => step_for_each(args),
+ StepCommand::Promote { branch } => {
+ handle_promote(branch.as_deref()).map(|result| match result {
+ commands::PromoteResult::Promoted => (),
+ commands::PromoteResult::AlreadyInMain(branch) => {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Branch <bold>{branch}</> is already in main worktree"
+ ))
+ );
+ }
+ })
+ }
+ StepCommand::Prune {
+ dry_run,
+ yes,
+ min_age,
+ foreground,
+ } => step_prune(dry_run, yes, &min_age, foreground),
+ StepCommand::Relocate {
+ branches,
+ dry_run,
+ commit,
+ clobber,
+ } => step_relocate(branches, dry_run, commit, clobber),
+ StepCommand::External(args) => {
+ commands::AliasOptions::parse(args).and_then(commands::step_alias)
+ }
+ }
+}
+
+fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
+ match action {
+ StateCommand::DefaultBranch { action } => match action {
+ Some(DefaultBranchAction::Get) | None => handle_state_get("default-branch", None),
+ Some(DefaultBranchAction::Set { branch }) => {
+ handle_state_set("default-branch", branch, None)
+ }
+ Some(DefaultBranchAction::Clear) => handle_state_clear("default-branch", None, false),
+ },
+ StateCommand::PreviousBranch { action } => match action {
+ Some(PreviousBranchAction::Get) | None => handle_state_get("previous-branch", None),
+ Some(PreviousBranchAction::Set { branch }) => {
+ handle_state_set("previous-branch", branch, None)
+ }
+ Some(PreviousBranchAction::Clear) => handle_state_clear("previous-branch", None, false),
+ },
+ StateCommand::CiStatus { action } => match action {
+ Some(CiStatusAction::Get { branch }) => handle_state_get("ci-status", branch),
+ None => handle_state_get("ci-status", None),
+ Some(CiStatusAction::Clear { branch, all }) => {
+ handle_state_clear("ci-status", branch, all)
+ }
+ },
+ StateCommand::Marker { action } => match action {
+ Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch),
+ None => handle_state_get("marker", None),
+ Some(MarkerAction::Set { value, branch }) => handle_state_set("marker", value, branch),
+ Some(MarkerAction::Clear { branch, all }) => handle_state_clear("marker", branch, all),
+ },
+ StateCommand::Logs { action } => match action {
+ Some(LogsAction::Get { hook, branch }) => handle_logs_get(hook, branch),
+ None => handle_logs_get(None, None),
+ Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
+ },
+ StateCommand::Hints { action } => match action {
+ Some(HintsAction::Get) | None => handle_hints_get(),
+ Some(HintsAction::Clear { name }) => handle_hints_clear(name),
+ },
+ StateCommand::Get { format } => handle_state_show(format),
+ StateCommand::Clear => handle_state_clear_all(),
+ }
+}
+
+fn handle_config_shell_command(action: ConfigShellCommand) -> anyhow::Result<()> {
+ match action {
+ ConfigShellCommand::Init { shell, cmd } => {
+ // Generate shell code to stdout
+ let cmd = cmd.unwrap_or_else(binary_name);
+ handle_init(shell, cmd).map_err(|e| anyhow::anyhow!("{}", e))
+ }
+ ConfigShellCommand::Install {
+ shell,
+ yes,
+ dry_run,
+ cmd,
+ } => {
+ // Auto-write to shell config files and completions
+ let cmd = cmd.unwrap_or_else(binary_name);
+ handle_configure_shell(shell, yes, dry_run, cmd)
+ .map_err(|e| anyhow::anyhow!("{}", e))
+ .and_then(|scan_result| {
+ // Exit with error if no shells configured
+ // Show skipped shells first so user knows what was tried
+ if scan_result.configured.is_empty() {
+ crate::output::print_skipped_shells(&scan_result.skipped)?;
+ return Err(worktrunk::git::GitError::Other {
+ message: "No shell config files found".into(),
+ }
+ .into());
+ }
+ // For --dry-run, preview was already shown by handler
+ if dry_run {
+ return Ok(());
+ }
+ crate::output::print_shell_install_result(&scan_result)
+ })
+ }
+ ConfigShellCommand::Uninstall {
+ shell,
+ yes,
+ dry_run,
+ } => {
+ let explicit_shell = shell.is_some();
+ handle_unconfigure_shell(shell, yes, dry_run, &binary_name())
+ .map_err(|e| anyhow::anyhow!("{}", e))
+ .map(|result| {
+ if !dry_run {
+ crate::output::print_shell_uninstall_result(&result, explicit_shell);
+ }
+ })
+ }
+ ConfigShellCommand::ShowTheme => {
+ handle_show_theme();
+ Ok(())
+ }
+ ConfigShellCommand::Completions { shell } => handle_completions(shell),
+ }
+}
+
+fn handle_config_command(action: ConfigCommand) -> anyhow::Result<()> {
+ match action {
+ ConfigCommand::Shell { action } => handle_config_shell_command(action),
+ ConfigCommand::Create { project } => handle_config_create(project),
+ ConfigCommand::Show { full } => handle_config_show(full),
+ ConfigCommand::Update { yes } => handle_config_update(yes),
+ ConfigCommand::State { action } => handle_state_command(action),
+ }
+}
+
+fn handle_list_command(
+ subcommand: Option<ListSubcommand>,
+ format: OutputFormat,
+ branches: bool,
+ remotes: bool,
+ full: bool,
+ progressive: bool,
+ no_progressive: bool,
+) -> anyhow::Result<()> {
+ match subcommand {
+ Some(ListSubcommand::Statusline {
+ format,
+ claude_code,
+ }) => {
+ // Hidden --claude-code flag only applies when format is default (Table)
+ // Explicit --format=json takes precedence over --claude-code
+ let effective_format = if claude_code && matches!(format, OutputFormat::Table) {
+ OutputFormat::ClaudeCode
+ } else {
+ format
+ };
+ commands::statusline::run(effective_format)
+ }
+ None => {
+ let (repo, _recovered) = current_or_recover()?;
+ let render_mode = RenderMode::detect(flag_pair(progressive, no_progressive));
+ handle_list(repo, format, branches, remotes, full, render_mode)
+ }
+ }
+}
+
+#[cfg(unix)]
+fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {
+ // Deprecated: show warning and delegate to handle_select
+ warn_select_deprecated();
+ handle_select(branches, remotes, true)
+}
+
+#[cfg(not(unix))]
+fn handle_select_command(_branches: bool, _remotes: bool) -> anyhow::Result<()> {
+ warn_select_deprecated();
+ print_windows_picker_unavailable();
+ std::process::exit(1);
+}
+
+struct SwitchCommandArgs {
+ branch: Option<String>,
+ branches: bool,
+ remotes: bool,
+ create: bool,
+ base: Option<String>,
+ execute: Option<String>,
+ execute_args: Vec<String>,
+ yes: bool,
+ clobber: bool,
+ no_cd: bool,
+ verify: bool,
+}
+
+fn handle_switch_command(spec: SwitchCommandArgs) -> anyhow::Result<()> {
+ UserConfig::load()
+ .context("Failed to load config")
+ .and_then(|mut config| {
+ // No branch argument: open interactive picker
+ let Some(branch) = spec.branch else {
+ #[cfg(unix)]
+ {
+ return handle_select(spec.branches, spec.remotes, !spec.no_cd);
+ }
+
+ #[cfg(not(unix))]
+ {
+ // Suppress unused variable warnings on Windows
+ let _ = (spec.branches, spec.remotes);
+
+ print_windows_picker_unavailable();
+ std::process::exit(2);
+ }
+ };
+
+ handle_switch(
+ SwitchOptions {
+ branch: &branch,
+ create: spec.create,
+ base: spec.base.as_deref(),
+ execute: spec.execute.as_deref(),
+ execute_args: &spec.execute_args,
+ yes: spec.yes,
+ clobber: spec.clobber,
+ change_dir: !spec.no_cd,
+ verify: spec.verify,
+ },
+ &mut config,
+ &binary_name(),
+ )
+ })
+}
+
+struct RemoveCommandArgs {
+ branches: Vec<String>,
+ delete_branch: bool,
+ force_delete: bool,
+ foreground: bool,
+ verify: bool,
+ yes: bool,
+ force: bool,
+}
+
+fn handle_remove_command(spec: RemoveCommandArgs) -> anyhow::Result<()> {
+ UserConfig::load()
+ .context("Failed to load config")
+ .and_then(|config| {
+ // Validate conflicting flags
+ if !spec.delete_branch && spec.force_delete {
+ return Err(worktrunk::git::GitError::Other {
+ message: "Cannot use --force-delete with --no-delete-branch".into(),
+ }
+ .into());
+ }
+
+ let repo = Repository::current().context("Failed to remove worktree")?;
+
+ // Helper: approve remove hooks using current worktree context
+ // Returns true if hooks should run (user approved)
+ let approve_remove = |yes: bool| -> anyhow::Result<bool> {
+ let env = CommandEnv::for_action_branchless()?;
+ let ctx = env.context(yes);
+ let approved = approve_hooks(
+ &ctx,
+ &[
+ HookType::PreRemove,
+ HookType::PostRemove,
+ HookType::PostSwitch,
+ ],
+ )?;
+ if !approved {
+ eprintln!("{}", info_message("Commands declined, continuing removal"));
+ }
+ Ok(approved)
+ };
+
+ let branches = spec.branches;
+
+ if branches.is_empty() {
+ // Single worktree removal: validate FIRST, then approve, then execute
+ let result = handle_remove_current(
+ !spec.delete_branch,
+ spec.force_delete,
+ spec.force,
+ &config,
+ )
+ .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 run_hooks = spec.verify && approve_remove(spec.yes)?;
+
+ handle_remove_output(&result, spec.foreground, run_hooks, false)
+ } else {
+ // Multi-worktree removal: validate ALL first, then approve, then execute
+ // This supports partial success - some may fail validation while others succeed.
+ 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()
+ };
+
+ // Phase 1: Validate all targets (resolution + preparation)
+ // Store successful plans for execution after approval
+ let mut plans_others: Vec<RemoveResult> = Vec::new();
+ let mut plans_branch_only: Vec<RemoveResult> = Vec::new();
+ let mut plan_current: Option<RemoveResult> = None;
+ let mut all_errors: Vec<anyhow::Error> = Vec::new();
+
+ // Helper: record error and continue
+ let mut record_error = |e: anyhow::Error| {
+ eprintln!("{}", e);
+ all_errors.push(e);
+ };
+
+ for branch_name in &branches {
+ // Resolve the target
+ let resolved = match resolve_worktree_arg(
+ &repo,
+ branch_name,
+ &config,
+ OperationMode::Remove,
+ ) {
+ Ok(r) => r,
+ Err(e) => {
+ 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 {
+ // Current worktree - use handle_remove_current for detached HEAD
+ match handle_remove_current(
+ !spec.delete_branch,
+ spec.force_delete,
+ spec.force,
+ &config,
+ ) {
+ Ok(result) => plan_current = Some(result),
+ Err(e) => record_error(e),
+ }
+ continue;
+ }
+
+ // Non-current worktree - branch is always Some because:
+ // - "@" resolves to current worktree (handled by is_current branch above)
+ // - Other names resolve via resolve_worktree_arg which always sets branch: Some(...)
+ let branch_for_remove = branch.as_ref().unwrap();
+
+ match handle_remove(
+ branch_for_remove,
+ !spec.delete_branch,
+ spec.force_delete,
+ spec.force,
+ &config,
+ ) {
+ Ok(result) => plans_others.push(result),
+ Err(e) => record_error(e),
+ }
+ }
+ ResolvedWorktree::BranchOnly { branch } => {
+ match handle_remove(
+ &branch,
+ !spec.delete_branch,
+ spec.force_delete,
+ spec.force,
+ &config,
+ ) {
+ Ok(result) => plans_branch_only.push(result),
+ Err(e) => record_error(e),
+ }
+ }
+ }
+ }
+
+ // If no valid plans, bail early (all failed validation)
+ let has_valid_plans = !plans_others.is_empty()
+ || !plans_branch_only.is_empty()
+ || plan_current.is_some();
+ if !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(());
+ }
+
+ // Phase 2: Approve hooks (only if we have valid plans)
+ // TODO(pre-remove-context): Approval context uses current worktree,
+ // but hooks execute in each target worktree.
+ let run_hooks = spec.verify && approve_remove(spec.yes)?;
+
+ // Phase 3: Execute all validated plans
+ // Remove other worktrees first
+ for result in plans_others {
+ handle_remove_output(&result, spec.foreground, run_hooks, false)?;
+ }
+
+ // Handle branch-only cases
+ for result in plans_branch_only {
+ handle_remove_output(&result, spec.foreground, run_hooks, false)?;
+ }
+
+ // Remove current worktree last (if it was in the list)
+ if let Some(result) = plan_current {
+ handle_remove_output(&result, spec.foreground, run_hooks, false)?;
+ }
+
+ // Exit with failure if any validation errors occurred
+ if !all_errors.is_empty() {
+ anyhow::bail!("");
+ }
+
+ Ok(())
+ }
+ })
+}
+
fn main() {
// Configure Rayon's global thread pool for mixed I/O workloads.
// The `wt list` command runs git operations (CPU + disk I/O) and network
@@ -374,368 +873,10 @@ fn main() {
};
let result = match command {
- Commands::Config { action } => match action {
- ConfigCommand::Shell { action } => {
- match action {
- ConfigShellCommand::Init { shell, cmd } => {
- // Generate shell code to stdout
- let cmd = cmd.unwrap_or_else(binary_name);
- handle_init(shell, cmd).map_err(|e| anyhow::anyhow!("{}", e))
- }
- ConfigShellCommand::Install {
- shell,
- yes,
- dry_run,
- cmd,
- } => {
- // Auto-write to shell config files and completions
- let cmd = cmd.unwrap_or_else(binary_name);
- handle_configure_shell(shell, yes, dry_run, cmd)
- .map_err(|e| anyhow::anyhow!("{}", e))
- .and_then(|scan_result| {
- // Exit with error if no shells configured
- // Show skipped shells first so user knows what was tried
- if scan_result.configured.is_empty() {
- crate::output::print_skipped_shells(&scan_result.skipped)?;
- return Err(worktrunk::git::GitError::Other {
- message: "No shell config files found".into(),
- }
- .into());
- }
- // For --dry-run, preview was already shown by handler
- if dry_run {
- return Ok(());
- }
- crate::output::print_shell_install_result(&scan_result)
- })
- }
- ConfigShellCommand::Uninstall {
- shell,
- yes,
- dry_run,
- } => {
- let explicit_shell = shell.is_some();
- handle_unconfigure_shell(shell, yes, dry_run, &binary_name())
- .map_err(|e| anyhow::anyhow!("{}", e))
- .map(|scan_result| {
- // For --dry-run, preview was already shown by handler
- if dry_run {
- return;
- }
-
- // Count unique shells, not file results (fish may have 2 files: functions/ and legacy conf.d/)
- let mut shells: Vec<_> =
- scan_result.results.iter().map(|r| r.shell).collect();
- shells.sort_by_key(|s| s.to_string());
- shells.dedup();
- let shell_count = shells.len();
- let completion_count = scan_result.completion_results.len();
- let total_changes = shell_count + completion_count;
-
- // Show shell extension results
- for result in &scan_result.results {
- let shell = result.shell;
- let path = format_path_for_display(&result.path);
- // For bash/zsh, completions are inline in the init script
- let what = if matches!(
- shell,
- worktrunk::shell::Shell::Bash
- | worktrunk::shell::Shell::Zsh
- ) {
- "shell extension & completions"
- } else {
- "shell extension"
- };
-
- eprintln!(
- "{}",
- success_message(cformat!(
- "{} {what} for <bold>{shell}</> @ <bold>{path}</>",
- result.action.description(),
- ))
- );
- }
-
- // Show completion results
- for result in &scan_result.completion_results {
- let shell = result.shell;
- let path = format_path_for_display(&result.path);
-
- eprintln!(
- "{}",
- success_message(cformat!(
- "{} completions for <bold>{shell}</> @ <bold>{path}</>",
- result.action.description(),
- ))
- );
- }
-
- // Show not found - warning if explicit shell, hint if auto-scan
- for (shell, path) in &scan_result.not_found {
- let path = format_path_for_display(path);
- // Use consistent terminology matching install/uninstall messages
- let what = if matches!(
- shell,
- worktrunk::shell::Shell::Bash
- | worktrunk::shell::Shell::Zsh
- ) {
- "shell extension & completions"
- } else {
- "shell extension"
- };
- if explicit_shell {
- eprintln!(
- "{}",
- warning_message(format!("No {what} found in {path}"))
- );
- } else {
- eprintln!(
- "{}",
- hint_message(cformat!(
- "No <underline>{shell}</> {what} in {path}"
- ))
- );
- }
- }
-
- // Show completion files not found (only fish has separate completion files)
- // Only show this if the shell extension was ALSO not found - if we removed
- // the shell extension, no need to warn about missing completions
- for (shell, path) in &scan_result.completion_not_found {
- let shell_was_removed =
- scan_result.results.iter().any(|r| r.shell == *shell);
- if shell_was_removed {
- continue; // Shell extension was removed, don't warn about completions
- }
- let path = format_path_for_display(path);
- if explicit_shell {
- eprintln!(
- "{}",
- warning_message(format!(
- "No completions found in {path}"
- ))
- );
- } else {
- eprintln!(
- "{}",
- hint_message(cformat!(
- "No <underline>{shell}</> completions in {path}"
- ))
- );
- }
- }
-
- // Exit with info if nothing was found
- let all_not_found = scan_result.not_found.len()
- + scan_result.completion_not_found.len();
- if total_changes == 0 {
- if all_not_found == 0 {
- eprintln!();
- eprintln!(
- "{}",
- hint_message("No shell integration found to remove")
- );
- }
- return;
- }
-
- // Summary
- eprintln!();
- let plural = if shell_count == 1 { "" } else { "s" };
- eprintln!(
- "{}",
- success_message(format!(
- "Removed integration from {shell_count} shell{plural}"
- ))
- );
-
- // Hint about restarting shell (only if current shell was affected)
- let current_shell = std::env::var("SHELL")
- .ok()
- .and_then(|s| extract_filename_from_path(&s).map(String::from));
-
- let current_shell_affected =
- current_shell.as_ref().is_some_and(|shell_name| {
- scan_result.results.iter().any(|r| {
- r.shell.to_string().eq_ignore_ascii_case(shell_name)
- })
- });
-
- if current_shell_affected {
- eprintln!(
- "{}",
- hint_message("Restart shell to complete uninstall")
- );
- }
- })
- }
- ConfigShellCommand::ShowTheme => {
- handle_show_theme();
- Ok(())
- }
- ConfigShellCommand::Completions { shell } => handle_completions(shell),
- }
- }
- ConfigCommand::Create { project } => handle_config_create(project),
- ConfigCommand::Show { full } => handle_config_show(full),
- ConfigCommand::Update { yes } => handle_config_update(yes),
- ConfigCommand::State { action } => match action {
- StateCommand::DefaultBranch { action } => match action {
- Some(DefaultBranchAction::Get) | None => {
- handle_state_get("default-branch", None)
- }
- Some(DefaultBranchAction::Set { branch }) => {
- handle_state_set("default-branch", branch, None)
- }
- Some(DefaultBranchAction::Clear) => {
- handle_state_clear("default-branch", None, false)
- }
- },
- StateCommand::PreviousBranch { action } => match action {
- Some(PreviousBranchAction::Get) | None => {
- handle_state_get("previous-branch", None)
- }
- Some(PreviousBranchAction::Set { branch }) => {
- handle_state_set("previous-branch", branch, None)
- }
- Some(PreviousBranchAction::Clear) => {
- handle_state_clear("previous-branch", None, false)
- }
- },
- StateCommand::CiStatus { action } => match action {
- Some(CiStatusAction::Get { branch }) => handle_state_get("ci-status", branch),
- None => handle_state_get("ci-status", None),
- Some(CiStatusAction::Clear { branch, all }) => {
- handle_state_clear("ci-status", branch, all)
- }
- },
- StateCommand::Marker { action } => match action {
- Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch),
- None => handle_state_get("marker", None),
- Some(MarkerAction::Set { value, branch }) => {
- handle_state_set("marker", value, branch)
- }
- Some(MarkerAction::Clear { branch, all }) => {
- handle_state_clear("marker", branch, all)
- }
- },
- StateCommand::Logs { action } => match action {
- Some(LogsAction::Get { hook, branch }) => handle_logs_get(hook, branch),
- None => handle_logs_get(None, None),
- Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
- },
- StateCommand::Hints { action } => match action {
- Some(HintsAction::Get) | None => handle_hints_get(),
- Some(HintsAction::Clear { name }) => handle_hints_clear(name),
- },
- StateCommand::Get { format } => handle_state_show(format),
- StateCommand::Clear => handle_state_clear_all(),
- },
- },
- Commands::Step { action } => match action {
- StepCommand::Commit {
- yes,
- verify,
- stage,
- show_prompt,
- } => step_commit(yes, verify, stage, show_prompt),
- StepCommand::Squash {
- target,
- yes,
- verify,
- stage,
- show_prompt,
- } => {
- // Handle --show-prompt early: just build and output the prompt
- if show_prompt {
- commands::step_show_squash_prompt(target.as_deref())
- } else {
- // Approval is handled inside handle_squash (like step_commit)
- handle_squash(target.as_deref(), yes, verify, stage).map(
- |result| match result {
- SquashResult::Squashed | SquashResult::NoNetChanges => {}
- SquashResult::NoCommitsAhead(branch) => {
- eprintln!(
- "{}",
- info_message(format!(
- "Nothing to squash; no commits ahead of {branch}"
- ))
- );
- }
- SquashResult::AlreadySingleCommit => {
- eprintln!(
- "{}",
- info_message("Nothing to squash; already a single commit")
- );
- }
- },
- )
- }
- }
- StepCommand::Push { target } => handle_push(target.as_deref(), "Pushed to", None),
- StepCommand::Rebase { target } => {
- handle_rebase(target.as_deref()).map(|result| match result {
- RebaseResult::Rebased => (),
- RebaseResult::UpToDate(branch) => {
- eprintln!(
- "{}",
- info_message(cformat!("Already up to date with <bold>{branch}</>"))
- );
- }
- })
- }
- StepCommand::Diff { target, extra_args } => step_diff(target.as_deref(), &extra_args),
- StepCommand::CopyIgnored {
- from,
- to,
- dry_run,
- force,
- } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force),
- StepCommand::ForEach { args } => step_for_each(args),
- StepCommand::Promote { branch } => {
- use commands::PromoteResult;
- handle_promote(branch.as_deref()).map(|result| match result {
- PromoteResult::Promoted => (),
- PromoteResult::AlreadyInMain(branch) => {
- eprintln!(
- "{}",
- info_message(cformat!(
- "Branch <bold>{branch}</> is already in main worktree"
- ))
- );
- }
- })
- }
- StepCommand::Prune {
- dry_run,
- yes,
- min_age,
- foreground,
- } => step_prune(dry_run, yes, &min_age, foreground),
- StepCommand::Relocate {
- branches,
- dry_run,
- commit,
- clobber,
- } => step_relocate(branches, dry_run, commit, clobber),
- StepCommand::External(args) => {
- commands::AliasOptions::parse(args).and_then(commands::step_alias)
- }
- },
+ Commands::Config { action } => handle_config_command(action),
+ Commands::Step { action } => handle_step_command(action),
Commands::Hook { action } => handle_hook_command(action),
- #[cfg(unix)]
- Commands::Select { branches, remotes } => {
- // Deprecated: show warning and delegate to handle_select
- warn_select_deprecated();
-
- handle_select(branches, remotes, true)
- }
- #[cfg(not(unix))]
- Commands::Select { .. } => {
- warn_select_deprecated();
- print_windows_picker_unavailable();
- std::process::exit(1);
- }
+ Commands::Select { branches, remotes } => handle_select_command(branches, remotes),
Commands::List {
subcommand,
format,
@@ -744,28 +885,15 @@ fn main() {
full,
progressive,
no_progressive,
- } => match subcommand {
- Some(ListSubcommand::Statusline {
- format,
- claude_code,
- }) => {
- // Hidden --claude-code flag only applies when format is default (Table)
- // Explicit --format=json takes precedence over --claude-code
- let effective_format = if claude_code && matches!(format, OutputFormat::Table) {
- OutputFormat::ClaudeCode
- } else {
- format
- };
- commands::statusline::run(effective_format)
- }
- None => (|| {
- let (repo, _recovered) = current_or_recover()?;
-
- let progressive_opt = flag_pair(progressive, no_progressive);
- let render_mode = RenderMode::detect(progressive_opt);
- handle_list(repo, format, branches, remotes, full, render_mode)
- })(),
- },
+ } => handle_list_command(
+ subcommand,
+ format,
+ branches,
+ remotes,
+ full,
+ progressive,
+ no_progressive,
+ ),
Commands::Switch {
branch,
branches,
@@ -778,42 +906,19 @@ fn main() {
clobber,
no_cd,
verify,
- } => UserConfig::load()
- .context("Failed to load config")
- .and_then(|mut config| {
- // No branch argument: open interactive picker
- let Some(branch) = branch else {
- #[cfg(unix)]
- {
- return handle_select(branches, remotes, !no_cd);
- }
-
- #[cfg(not(unix))]
- {
- // Suppress unused variable warnings on Windows
- let _ = (branches, remotes);
-
- print_windows_picker_unavailable();
- std::process::exit(2);
- }
- };
-
- handle_switch(
- SwitchOptions {
- branch: &branch,
- create,
- base: base.as_deref(),
- execute: execute.as_deref(),
- execute_args: &execute_args,
- yes,
- clobber,
- change_dir: !no_cd,
- verify,
- },
- &mut config,
- &binary_name(),
- )
- }),
+ } => handle_switch_command(SwitchCommandArgs {
+ branch,
+ branches,
+ remotes,
+ create,
+ base,
+ execute,
+ execute_args,
+ yes,
+ clobber,
+ no_cd,
+ verify,
+ }),
Commands::Remove {
branches,
delete_branch,
@@ -822,192 +927,15 @@ fn main() {
verify,
yes,
force,
- } => UserConfig::load()
- .context("Failed to load config")
- .and_then(|config| {
- // Validate conflicting flags
- if !delete_branch && force_delete {
- return Err(worktrunk::git::GitError::Other {
- message: "Cannot use --force-delete with --no-delete-branch".into(),
- }
- .into());
- }
-
- let repo = Repository::current().context("Failed to remove worktree")?;
-
- // Helper: approve remove hooks using current worktree context
- // Returns true if hooks should run (user approved)
- let approve_remove = |yes: bool| -> anyhow::Result<bool> {
- let env = CommandEnv::for_action_branchless()?;
- let ctx = env.context(yes);
- let approved = approve_hooks(
- &ctx,
- &[
- HookType::PreRemove,
- HookType::PostRemove,
- HookType::PostSwitch,
- ],
- )?;
- if !approved {
- eprintln!("{}", info_message("Commands declined, continuing removal"));
- }
- Ok(approved)
- };
-
- if branches.is_empty() {
- // Single worktree removal: validate FIRST, then approve, then execute
- let result =
- handle_remove_current(!delete_branch, force_delete, force, &config)
- .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 run_hooks = verify && approve_remove(yes)?;
-
- handle_remove_output(&result, foreground, run_hooks, false)
- } else {
- // Multi-worktree removal: validate ALL first, then approve, then execute
- // This supports partial success - some may fail validation while others succeed.
- 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()
- };
-
- // Phase 1: Validate all targets (resolution + preparation)
- // Store successful plans for execution after approval
- let mut plans_others: Vec<RemoveResult> = Vec::new();
- let mut plans_branch_only: Vec<RemoveResult> = Vec::new();
- let mut plan_current: Option<RemoveResult> = None;
- let mut all_errors: Vec<anyhow::Error> = Vec::new();
-
- // Helper: record error and continue
- let mut record_error = |e: anyhow::Error| {
- eprintln!("{}", e);
- all_errors.push(e);
- };
-
- for branch_name in &branches {
- // Resolve the target
- let resolved = match resolve_worktree_arg(
- &repo,
- branch_name,
- &config,
- OperationMode::Remove,
- ) {
- Ok(r) => r,
- Err(e) => {
- 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 {
- // Current worktree - use handle_remove_current for detached HEAD
- match handle_remove_current(
- !delete_branch,
- force_delete,
- force,
- &config,
- ) {
- Ok(result) => plan_current = Some(result),
- Err(e) => record_error(e),
- }
- continue;
- }
-
- // Non-current worktree - branch is always Some because:
- // - "@" resolves to current worktree (handled by is_current branch above)
- // - Other names resolve via resolve_worktree_arg which always sets branch: Some(...)
- let branch_for_remove = branch.as_ref().unwrap();
-
- match handle_remove(
- branch_for_remove,
- !delete_branch,
- force_delete,
- force,
- &config,
- ) {
- Ok(result) => plans_others.push(result),
- Err(e) => record_error(e),
- }
- }
- ResolvedWorktree::BranchOnly { branch } => {
- match handle_remove(
- &branch,
- !delete_branch,
- force_delete,
- force,
- &config,
- ) {
- Ok(result) => plans_branch_only.push(result),
- Err(e) => record_error(e),
- }
- }
- }
- }
-
- // If no valid plans, bail early (all failed validation)
- let has_valid_plans = !plans_others.is_empty()
- || !plans_branch_only.is_empty()
- || plan_current.is_some();
- if !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(());
- }
-
- // Phase 2: Approve hooks (only if we have valid plans)
- // TODO(pre-remove-context): Approval context uses current worktree,
- // but hooks execute in each target worktree.
- let run_hooks = verify && approve_remove(yes)?;
-
- // Phase 3: Execute all validated plans
- // Remove other worktrees first
- for result in plans_others {
- handle_remove_output(&result, foreground, run_hooks, false)?;
- }
-
- // Handle branch-only cases
- for result in plans_branch_only {
- handle_remove_output(&result, foreground, run_hooks, false)?;
- }
-
- // Remove current worktree last (if it was in the list)
- if let Some(result) = plan_current {
- handle_remove_output(&result, foreground, run_hooks, false)?;
- }
-
- // Exit with failure if any validation errors occurred
- if !all_errors.is_empty() {
- anyhow::bail!("");
- }
-
- Ok(())
- }
- }),
+ } => handle_remove_command(RemoveCommandArgs {
+ branches,
+ delete_branch,
+ force_delete,
+ foreground,
+ verify,
+ yes,
+ force,
+ }),
Commands::Merge {
target,
squash,
diff --git a/src/output/mod.rs b/src/output/mod.rs
index a7bf51568..f3b3618b2 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -47,7 +47,8 @@ pub(crate) use handlers::{
};
// Re-export shell integration functions
pub(crate) use shell_integration::{
- print_shell_install_result, print_skipped_shells, prompt_shell_integration,
+ print_shell_install_result, print_shell_uninstall_result, print_skipped_shells,
+ prompt_shell_integration,
};
// Re-export commit generation functions
pub(crate) use commit_generation::prompt_commit_generation;
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 2ab7d2881..4440687e1 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -69,7 +69,8 @@ use worktrunk::styling::{
};
use crate::commands::configure_shell::{
- ConfigAction, handle_configure_shell, prompt_for_install, scan_shell_configs,
+ ConfigAction, UninstallScanResult, handle_configure_shell, prompt_for_install,
+ scan_shell_configs,
};
/// Shell integration install hint message.
@@ -198,6 +199,29 @@ pub fn print_skipped_shells(
Ok(())
}
+fn shell_extension_label(shell: Shell) -> &'static str {
+ // For bash/zsh, completions are inline in the init script.
+ if matches!(shell, Shell::Bash | Shell::Zsh) {
+ "shell extension & completions"
+ } else {
+ "shell extension"
+ }
+}
+
+fn print_config_action_result(action: &ConfigAction, message: String) {
+ match action {
+ ConfigAction::Added | ConfigAction::Created => {
+ eprintln!("{}", success_message(message));
+ }
+ ConfigAction::AlreadyExists => {
+ eprintln!("{}", info_message(message));
+ }
+ ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
+ unreachable!("Preview actions handled by confirmation prompt")
+ }
+ }
+}
+
/// Print the result of shell integration installation.
///
/// Shows:
@@ -231,28 +255,12 @@ pub fn print_shell_install_result(
for result in &scan_result.configured {
let shell = result.shell;
let path = format_path_for_display(&result.path);
- // For bash/zsh, completions are inline in the init script
- let what = if matches!(shell, Shell::Bash | Shell::Zsh) {
- "shell extension & completions"
- } else {
- "shell extension"
- };
+ let what = shell_extension_label(shell);
let message = cformat!(
"{} {what} for <bold>{shell}</> @ <bold>{path}</>",
result.action.description()
);
-
- match result.action {
- ConfigAction::Added | ConfigAction::Created => {
- eprintln!("{}", success_message(message));
- }
- ConfigAction::AlreadyExists => {
- eprintln!("{}", info_message(message));
- }
- ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
- unreachable!("Preview actions handled by confirmation prompt")
- }
- }
+ print_config_action_result(&result.action, message);
if matches!(shell, Shell::Nushell) && !matches!(result.action, ConfigAction::AlreadyExists)
{
@@ -270,17 +278,7 @@ pub fn print_shell_install_result(
"{} completions for <bold>{shell}</> @ <bold>{comp_path}</>",
comp_result.action.description()
);
- match comp_result.action {
- ConfigAction::Added | ConfigAction::Created => {
- eprintln!("{}", success_message(comp_message));
- }
- ConfigAction::AlreadyExists => {
- eprintln!("{}", info_message(comp_message));
- }
- ConfigAction::WouldAdd | ConfigAction::WouldCreate => {
- unreachable!("Preview actions handled by confirmation prompt")
- }
- }
+ print_config_action_result(&comp_result.action, comp_message);
}
}
@@ -451,6 +449,120 @@ pub fn prompt_shell_integration(
Ok(true)
}
+/// Print the result of shell integration uninstallation.
+///
+/// Shows removed extensions/completions, not-found warnings, summary, and restart hint.
+pub fn print_shell_uninstall_result(scan_result: &UninstallScanResult, explicit_shell: bool) {
+ // Count unique shells, not file results (fish may have 2 files: functions/ and legacy conf.d/)
+ let mut shells: Vec<_> = scan_result.results.iter().map(|r| r.shell).collect();
+ shells.sort_by_key(|s| s.to_string());
+ shells.dedup();
+ let shell_count = shells.len();
+ let completion_count = scan_result.completion_results.len();
+ let total_changes = shell_count + completion_count;
+
+ // Show shell extension results
+ for result in &scan_result.results {
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
+ let what = shell_extension_label(shell);
+
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "{} {what} for <bold>{shell}</> @ <bold>{path}</>",
+ result.action.description(),
+ ))
+ );
+ }
+
+ // Show completion results
+ for result in &scan_result.completion_results {
+ let shell = result.shell;
+ let path = format_path_for_display(&result.path);
+
+ eprintln!(
+ "{}",
+ success_message(cformat!(
+ "{} completions for <bold>{shell}</> @ <bold>{path}</>",
+ result.action.description(),
+ ))
+ );
+ }
+
+ // Show not found - warning if explicit shell, hint if auto-scan
+ for (shell, path) in &scan_result.not_found {
+ let path = format_path_for_display(path);
+ let what = shell_extension_label(*shell);
+ if explicit_shell {
+ eprintln!("{}", warning_message(format!("No {what} found in {path}")));
+ } else {
+ eprintln!(
+ "{}",
+ hint_message(cformat!("No <underline>{shell}</> {what} in {path}"))
+ );
+ }
+ }
+
+ // Show completion files not found (only fish has separate completion files)
+ // Only show this if the shell extension was ALSO not found - if we removed
+ // the shell extension, no need to warn about missing completions
+ for (shell, path) in &scan_result.completion_not_found {
+ let shell_was_removed = scan_result.results.iter().any(|r| r.shell == *shell);
+ if shell_was_removed {
+ continue; // Shell extension was removed, don't warn about completions
+ }
+ let path = format_path_for_display(path);
+ if explicit_shell {
+ eprintln!(
+ "{}",
+ warning_message(format!("No completions found in {path}"))
+ );
+ } else {
+ eprintln!(
+ "{}",
+ hint_message(cformat!("No <underline>{shell}</> completions in {path}"))
+ );
+ }
+ }
+
+ // Exit with info if nothing was found
+ let all_not_found = scan_result.not_found.len() + scan_result.completion_not_found.len();
+ if total_changes == 0 {
+ if all_not_found == 0 {
+ eprintln!();
+ eprintln!("{}", hint_message("No shell integration found to remove"));
+ }
+ return;
+ }
+
+ // Summary
+ eprintln!();
+ let plural = if shell_count == 1 { "" } else { "s" };
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Removed integration from {shell_count} shell{plural}"
+ ))
+ );
+
+ // Hint about restarting shell (only if current shell was affected)
+ let current_shell = std::env::var("SHELL")
+ .ok()
+ .and_then(|s| extract_filename_from_path(&s).map(String::from));
+
+ let current_shell_affected = current_shell.as_ref().is_some_and(|shell_name| {
+ scan_result
+ .results
+ .iter()
+ .any(|r| r.shell.to_string().eq_ignore_ascii_case(shell_name))
+ });
+
+ if current_shell_affected {
+ eprintln!("{}", hint_message("Restart shell to complete uninstall"));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;