Skip to content

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

Simplify hook dispatch and dedupe command helpers (#1248)

Maximilian Roosae89125d88ac
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 4c7028a9d..2b555a183 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -7,7 +7,7 @@ use worktrunk::styling::{
};
use super::command_executor::CommandContext;
-use super::hooks::HookFailureStrategy;
+use super::hooks::{HookCommandSpec, HookFailureStrategy};
use super::repository_ext::RepositoryCliExt;
// Re-export StageMode from config for use by CLI
@@ -182,15 +182,17 @@ impl CommitOptions<'_> {
// Run pre-commit hooks (user first, then project)
super::hooks::run_hook_with_filter(
self.ctx,
- user_hooks.pre_commit.as_ref(),
- project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_commit.as_ref()),
- HookType::PreCommit,
- &extra_vars,
+ HookCommandSpec {
+ user_config: user_hooks.pre_commit.as_ref(),
+ project_config: project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_commit.as_ref()),
+ hook_type: HookType::PreCommit,
+ extra_vars: &extra_vars,
+ name_filter: None,
+ display_path: crate::output::pre_hook_display_path(self.ctx.worktree_path),
+ },
HookFailureStrategy::FailFast,
- None,
- crate::output::pre_hook_display_path(self.ctx.worktree_path),
)
.map_err(worktrunk::git::add_hook_skip_hint)?;
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 09f370626..8a93ced18 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -27,11 +27,80 @@ use super::command_executor::build_hook_context;
use super::command_executor::CommandContext;
use super::context::CommandEnv;
use super::hooks::{
- HookFailureStrategy, check_name_filter_matched, prepare_hook_commands, run_hook_with_filter,
- spawn_background_hooks,
+ HookCommandSpec, HookFailureStrategy, check_name_filter_matched, prepare_hook_commands,
+ run_hook_with_filter, spawn_background_hooks,
};
use super::project_config::collect_commands_for_hooks;
+fn run_filtered_hook(
+ ctx: &CommandContext,
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
+ failure_strategy: HookFailureStrategy,
+) -> anyhow::Result<()> {
+ run_hook_with_filter(
+ ctx,
+ HookCommandSpec {
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ display_path: crate::output::pre_hook_display_path(ctx.worktree_path),
+ },
+ failure_strategy,
+ )
+}
+
+fn run_post_hook(
+ ctx: &CommandContext,
+ foreground: Option<bool>,
+ user_config: Option<&CommandConfig>,
+ project_config: Option<&CommandConfig>,
+ hook_type: HookType,
+ extra_vars: &[(&str, &str)],
+ name_filter: Option<&str>,
+) -> anyhow::Result<()> {
+ // Default to background execution; --foreground is for debugging.
+ if !foreground.unwrap_or(false) {
+ let commands = prepare_hook_commands(
+ ctx,
+ HookCommandSpec {
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ display_path: None,
+ },
+ )?;
+ check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;
+ return spawn_background_hooks(ctx, commands);
+ }
+
+ run_filtered_hook(
+ ctx,
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ HookFailureStrategy::Warn,
+ )
+}
+
+fn build_target_vars<'a>(
+ target: Option<&'a str>,
+ custom_vars: &'a [(&'a str, &'a str)],
+) -> Vec<(&'a str, &'a str)> {
+ let mut vars: Vec<(&str, &str)> = target.into_iter().map(|t| ("target", t)).collect();
+ vars.extend(custom_vars.iter().copied());
+ vars
+}
+
/// Handle `wt hook` command
///
/// When explicitly invoking hooks, ALL hooks run (both user and project).
@@ -94,247 +163,90 @@ pub fn run_hook(
// Get effective user hooks (global + per-project merged)
let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
+ let hook_configs = |hook: HookType| {
+ (
+ user_hooks.get(hook),
+ project_config.as_ref().and_then(|c| c.hooks.get(hook)),
+ )
+ };
// Execute the hook based on type
match hook_type {
- HookType::PreSwitch => {
- let user_config = user_hooks.pre_switch.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_switch.as_ref());
+ HookType::PreSwitch | HookType::PostCreate | HookType::PreRemove => {
+ let (user_config, project_config) = hook_configs(hook_type);
require_hooks(user_config, project_config, hook_type)?;
// Manual wt hook: user stays at cwd (no cd happens)
- run_hook_with_filter(
+ run_filtered_hook(
&ctx,
user_config,
project_config,
hook_type,
&custom_vars_refs,
- HookFailureStrategy::FailFast,
name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
+ HookFailureStrategy::FailFast,
)
}
- HookType::PostCreate => {
- let user_config = user_hooks.post_create.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.post_create.as_ref());
+ HookType::PostStart | HookType::PostSwitch | HookType::PostRemove => {
+ let (user_config, project_config) = hook_configs(hook_type);
require_hooks(user_config, project_config, hook_type)?;
- // Manual wt hook: user stays at cwd (no cd happens)
- run_hook_with_filter(
+ run_post_hook(
&ctx,
+ foreground,
user_config,
project_config,
hook_type,
&custom_vars_refs,
- HookFailureStrategy::FailFast,
name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
)
}
- HookType::PostStart => {
- let user_config = user_hooks.post_start.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.post_start.as_ref());
- require_hooks(user_config, project_config, hook_type)?;
-
- // Default to background (matching normal behavior during switch)
- // Use --foreground to run in foreground for debugging
- if !foreground.unwrap_or(false) {
- let commands = prepare_hook_commands(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- name_filter,
- None,
- )?;
- check_name_filter_matched(
- name_filter,
- commands.len(),
- user_config,
- project_config,
- )?;
- spawn_background_hooks(&ctx, commands)
- } else {
- run_hook_with_filter(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- HookFailureStrategy::Warn,
- name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
- )
- }
- }
- HookType::PostSwitch => {
- let user_config = user_hooks.post_switch.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.post_switch.as_ref());
- require_hooks(user_config, project_config, hook_type)?;
-
- // Default to background (matching normal behavior during switch)
- // Use --foreground to run in foreground for debugging
- if !foreground.unwrap_or(false) {
- let commands = prepare_hook_commands(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- name_filter,
- None,
- )?;
- check_name_filter_matched(
- name_filter,
- commands.len(),
- user_config,
- project_config,
- )?;
- spawn_background_hooks(&ctx, commands)
- } else {
- run_hook_with_filter(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- HookFailureStrategy::Warn,
- name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
- )
- }
- }
HookType::PreCommit => {
- let user_config = user_hooks.pre_commit.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_commit.as_ref());
+ let (user_config, project_config) = hook_configs(hook_type);
require_hooks(user_config, project_config, hook_type)?;
// Pre-commit hook can optionally use target branch context
// Custom vars take precedence (added last)
let target_branch = repo.default_branch();
- let mut extra_vars: Vec<(&str, &str)> = target_branch
- .as_deref()
- .into_iter()
- .map(|t| ("target", t))
- .collect();
- extra_vars.extend(&custom_vars_refs);
+ let extra_vars = build_target_vars(target_branch.as_deref(), &custom_vars_refs);
// Manual wt hook: user stays at cwd (no cd happens)
- run_hook_with_filter(
+ run_filtered_hook(
&ctx,
user_config,
project_config,
hook_type,
&extra_vars,
- HookFailureStrategy::FailFast,
name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
+ HookFailureStrategy::FailFast,
)
}
HookType::PreMerge => {
- let user_config = user_hooks.pre_merge.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_merge.as_ref());
+ let (user_config, project_config) = hook_configs(hook_type);
require_hooks(user_config, project_config, hook_type)?;
// Use current branch as target (matches approval prompt for wt hook)
- let mut vars = vec![("target", ctx.branch_or_head())];
- vars.extend(custom_vars_refs.iter().cloned());
- run_hook_with_filter(
+ let vars = build_target_vars(Some(ctx.branch_or_head()), &custom_vars_refs);
+ run_filtered_hook(
&ctx,
user_config,
project_config,
hook_type,
&vars,
- HookFailureStrategy::FailFast,
name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
+ HookFailureStrategy::FailFast,
)
}
HookType::PostMerge => {
- let user_config = user_hooks.post_merge.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.post_merge.as_ref());
+ let (user_config, project_config) = hook_configs(hook_type);
require_hooks(user_config, project_config, hook_type)?;
// Manual wt hook: user stays at cwd (no cd happens)
- let mut vars = vec![("target", ctx.branch_or_head())];
- vars.extend(custom_vars_refs.iter().cloned());
- run_hook_with_filter(
+ let vars = build_target_vars(Some(ctx.branch_or_head()), &custom_vars_refs);
+ run_filtered_hook(
&ctx,
user_config,
project_config,
hook_type,
&vars,
- HookFailureStrategy::Warn,
- name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
- )
- }
- HookType::PreRemove => {
- let user_config = user_hooks.pre_remove.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_remove.as_ref());
- require_hooks(user_config, project_config, hook_type)?;
- // Manual wt hook: user stays at cwd (no cd happens)
- run_hook_with_filter(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- HookFailureStrategy::FailFast,
name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
+ HookFailureStrategy::Warn,
)
}
- HookType::PostRemove => {
- let user_config = user_hooks.post_remove.as_ref();
- let project_config = project_config
- .as_ref()
- .and_then(|c| c.hooks.post_remove.as_ref());
- require_hooks(user_config, project_config, hook_type)?;
-
- // Default to background (matching normal behavior during remove)
- // Use --foreground to run in foreground for debugging
- if !foreground.unwrap_or(false) {
- let commands = prepare_hook_commands(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- name_filter,
- None,
- )?;
- check_name_filter_matched(
- name_filter,
- commands.len(),
- user_config,
- project_config,
- )?;
- spawn_background_hooks(&ctx, commands)
- } else {
- run_hook_with_filter(
- &ctx,
- user_config,
- project_config,
- hook_type,
- &custom_vars_refs,
- HookFailureStrategy::Warn,
- name_filter,
- crate::output::pre_hook_display_path(ctx.worktree_path),
- )
- }
- }
}
}
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 7e01e357f..13cdb8642 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -75,6 +75,17 @@ pub enum HookFailureStrategy {
// Re-export for backward compatibility with existing imports
pub use super::hook_filter::{HookSource, ParsedFilter};
+/// Shared hook selection and rendering inputs for preparation/execution.
+#[derive(Clone, Copy)]
+pub struct HookCommandSpec<'cfg, 'vars, 'name, 'path> {
+ pub user_config: Option<&'cfg CommandConfig>,
+ pub project_config: Option<&'cfg CommandConfig>,
+ pub hook_type: HookType,
+ pub extra_vars: &'vars [(&'vars str, &'vars str)],
+ pub name_filter: Option<&'name str>,
+ pub display_path: Option<&'path Path>,
+}
+
/// Prepare hook commands from both user and project configs.
///
/// Collects commands from user config first, then project config, applying the name filter.
@@ -83,16 +94,19 @@ pub use super::hook_filter::{HookSource, ParsedFilter};
///
/// `display_path`: When `Some`, the path is shown in hook announcements (e.g., "@ ~/repo").
/// Use this when commands run in a different directory than where the user invoked the command.
-#[allow(clippy::too_many_arguments)]
pub fn prepare_hook_commands(
ctx: &CommandContext,
- user_config: Option<&CommandConfig>,
- project_config: Option<&CommandConfig>,
- hook_type: HookType,
- extra_vars: &[(&str, &str)],
- name_filter: Option<&str>,
- display_path: Option<&Path>,
+ spec: HookCommandSpec<'_, '_, '_, '_>,
) -> anyhow::Result<Vec<SourcedCommand>> {
+ let HookCommandSpec {
+ user_config,
+ project_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ display_path,
+ } = spec;
+
let parsed_filter = name_filter.map(ParsedFilter::parse);
let mut commands = Vec::new();
@@ -313,26 +327,19 @@ pub(crate) fn check_name_filter_matched(
///
/// `display_path`: Pass `ctx.hooks_display_path()` for automatic detection, or
/// explicit `Some(path)` when hooks run somewhere the user won't be cd'd to.
-#[allow(clippy::too_many_arguments)]
pub fn run_hook_with_filter(
ctx: &CommandContext,
- user_config: Option<&CommandConfig>,
- project_config: Option<&CommandConfig>,
- hook_type: HookType,
- extra_vars: &[(&str, &str)],
+ spec: HookCommandSpec<'_, '_, '_, '_>,
failure_strategy: HookFailureStrategy,
- name_filter: Option<&str>,
- display_path: Option<&Path>,
) -> anyhow::Result<()> {
- let commands = prepare_hook_commands(
- ctx,
+ let commands = prepare_hook_commands(ctx, spec)?;
+ let HookCommandSpec {
user_config,
project_config,
hook_type,
- extra_vars,
name_filter,
- display_path,
- )?;
+ ..
+ } = spec;
check_name_filter_matched(name_filter, commands.len(), user_config, project_config)?;
@@ -437,13 +444,15 @@ pub fn execute_hook(
run_hook_with_filter(
ctx,
- user_config,
- proj_config,
- hook_type,
- extra_vars,
+ HookCommandSpec {
+ user_config,
+ project_config: proj_config,
+ hook_type,
+ extra_vars,
+ name_filter,
+ display_path,
+ },
failure_strategy,
- name_filter,
- display_path,
)
.map_err(worktrunk::git::add_hook_skip_hint)
}
@@ -470,12 +479,14 @@ pub(crate) fn prepare_background_hooks(
prepare_hook_commands(
ctx,
- user_config,
- proj_config,
- hook_type,
- extra_vars,
- None, // no filter for automatic background hooks
- display_path,
+ HookCommandSpec {
+ user_config,
+ project_config: proj_config,
+ hook_type,
+ extra_vars,
+ name_filter: None, // no filter for automatic background hooks
+ display_path,
+ },
)
}
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 1a209aaf9..a0cc2f2cf 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -32,7 +32,7 @@ use worktrunk::styling::{
use super::command_approval::approve_hooks;
use super::commit::{CommitGenerator, CommitOptions, StageMode};
use super::context::CommandEnv;
-use super::hooks::{HookFailureStrategy, run_hook_with_filter};
+use super::hooks::{HookCommandSpec, HookFailureStrategy, run_hook_with_filter};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::BranchDeletionMode;
use crate::output::handle_remove_output;
@@ -192,15 +192,17 @@ pub fn handle_squash(
let extra_vars = [("target", integration_target.as_str())];
run_hook_with_filter(
&ctx,
- user_hooks.pre_commit.as_ref(),
- project_config
- .as_ref()
- .and_then(|c| c.hooks.pre_commit.as_ref()),
- HookType::PreCommit,
- &extra_vars,
+ HookCommandSpec {
+ user_config: user_hooks.pre_commit.as_ref(),
+ project_config: project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_commit.as_ref()),
+ hook_type: HookType::PreCommit,
+ extra_vars: &extra_vars,
+ name_filter: None,
+ display_path: crate::output::pre_hook_display_path(ctx.worktree_path),
+ },
HookFailureStrategy::FailFast,
- None,
- crate::output::pre_hook_display_path(ctx.worktree_path),
)
.map_err(worktrunk::git::add_hook_skip_hint)?;
}
diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rs
index aed44015e..08ed8d9f2 100644
--- a/src/commands/worktree/hooks.rs
+++ b/src/commands/worktree/hooks.rs
@@ -9,7 +9,7 @@ use worktrunk::path::to_posix_path;
use crate::commands::command_executor::CommandContext;
use crate::commands::hooks::{
- HookFailureStrategy, SourcedCommand, execute_hook, prepare_hook_commands,
+ HookCommandSpec, HookFailureStrategy, SourcedCommand, execute_hook, prepare_hook_commands,
};
impl<'a> CommandContext<'a> {
@@ -81,14 +81,16 @@ impl<'a> CommandContext<'a> {
let user_hooks = self.config.hooks(self.project_id().as_deref());
prepare_hook_commands(
self,
- user_hooks.post_remove.as_ref(),
- project_config
- .as_ref()
- .and_then(|c| c.hooks.post_remove.as_ref()),
- HookType::PostRemove,
- &extra_vars,
- None,
- display_path,
+ HookCommandSpec {
+ user_config: user_hooks.post_remove.as_ref(),
+ project_config: project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_remove.as_ref()),
+ hook_type: HookType::PostRemove,
+ extra_vars: &extra_vars,
+ name_filter: None,
+ display_path,
+ },
)
}
}
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 52b64d54c..da7029191 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -649,6 +649,15 @@ impl DeprecationInfo {
}
}
+fn migration_path(path: &Path) -> PathBuf {
+ // config.toml -> config.toml.new
+ // config -> config.new
+ match path.extension() {
+ Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),
+ None => path.with_extension("new"),
+ }
+}
+
/// Check config content for deprecated patterns and optionally create migration file
///
/// Detects and migrates:
@@ -699,12 +708,7 @@ pub fn check_and_migrate(
return Ok(None);
}
- // Build the .new path: "config.toml" -> "config.toml.new"
- // For files without extension: "config" -> "config.new" (not "config..new")
- let new_path = match path.extension() {
- Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),
- None => path.with_extension("new"),
- };
+ let new_path = migration_path(path);
// Skip writing if: (a) this is a brief warning (not `wt config show`), AND
// (b) migration file already exists
@@ -818,11 +822,7 @@ pub fn write_migration_file(
deprecations: &Deprecations,
repo: Option<&crate::git::Repository>,
) -> Option<PathBuf> {
- // Build the .new path: "config.toml" -> "config.toml.new"
- let new_path = path.with_extension(format!(
- "{}.new",
- path.extension().unwrap_or_default().to_string_lossy()
- ));
+ let new_path = migration_path(path);
// Apply all migrations to generate new content
let mut new_content = content.to_string();
@@ -1370,10 +1370,7 @@ approved-commands = [
fn test_migration_path_with_extension() {
// config.toml -> config.toml.new
let path = std::path::Path::new("/tmp/config.toml");
- let new_path = match path.extension() {
- Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),
- None => path.with_extension("new"),
- };
+ let new_path = migration_path(path);
assert_eq!(new_path.to_str().unwrap(), "/tmp/config.toml.new");
}
@@ -1381,10 +1378,7 @@ approved-commands = [
fn test_migration_path_without_extension() {
// config -> config.new (not config..new)
let path = std::path::Path::new("/tmp/config");
- let new_path = match path.extension() {
- Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),
- None => path.with_extension("new"),
- };
+ let new_path = migration_path(path);
assert_eq!(new_path.to_str().unwrap(), "/tmp/config.new");
}
@@ -1393,10 +1387,7 @@ approved-commands = [
// .hidden -> .hidden.new (not .hidden..new)
// Note: .hidden has no extension (the dot is part of the filename)
let path = std::path::Path::new("/tmp/.hidden");
- let new_path = match path.extension() {
- Some(ext) => path.with_extension(format!("{}.new", ext.to_string_lossy())),
- None => path.with_extension("new"),
- };
+ let new_path = migration_path(path);
assert_eq!(new_path.to_str().unwrap(), "/tmp/.hidden.new");
}
diff --git a/src/main.rs b/src/main.rs
index 3b4688ffd..b741ef421 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -66,6 +66,9 @@ use cli::{
};
use worktrunk::HookType;
+const NO_BACKGROUND_DEPRECATED_MSG: &str =
+ "--no-background is deprecated; use --foreground instead";
+
/// Enhance clap errors with command-specific hints, then exit.
///
/// For unrecognized subcommands that match nested commands, suggests the full path.
@@ -92,6 +95,138 @@ fn enhance_and_exit_error(err: clap::Error) -> ! {
err.exit()
}
+fn warn_no_background_deprecated() {
+ eprintln!("{}", warning_message(NO_BACKGROUND_DEPRECATED_MSG));
+}
+
+#[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: <bright-black>wt switch BRANCH</>"
+ ))
+ );
+}
+
+fn is_foreground_mode(foreground: bool, no_background: bool) -> bool {
+ if no_background {
+ warn_no_background_deprecated();
+ }
+ foreground || no_background
+}
+
+fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
+ match (positive, negative) {
+ (true, _) => Some(true),
+ (_, true) => Some(false),
+ _ => None,
+ }
+}
+
+fn run_non_toggle_hook(
+ hook_type: HookType,
+ yes: bool,
+ name: Option<&str>,
+ vars: &[(String, String)],
+) -> anyhow::Result<()> {
+ run_hook(hook_type, yes, None, name, vars)
+}
+
+fn run_toggleable_hook(
+ hook_type: HookType,
+ yes: bool,
+ foreground: bool,
+ no_background: bool,
+ name: Option<&str>,
+ vars: &[(String, String)],
+) -> anyhow::Result<()> {
+ let foreground = is_foreground_mode(foreground, no_background);
+ run_hook(hook_type, yes, Some(foreground), name, vars)
+}
+
+fn warn_select_deprecated() {
+ eprintln!(
+ "{}",
+ warning_message("wt select is deprecated; use wt switch instead")
+ );
+}
+
+fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {
+ match action {
+ HookCommand::Show {
+ hook_type,
+ expanded,
+ } => handle_hook_show(hook_type.as_deref(), expanded),
+ HookCommand::PreSwitch { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PreSwitch, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PostCreate { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PostCreate, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PostStart {
+ name,
+ yes,
+ foreground,
+ no_background,
+ vars,
+ } => run_toggleable_hook(
+ HookType::PostStart,
+ yes,
+ foreground,
+ no_background,
+ name.as_deref(),
+ &vars,
+ ),
+ HookCommand::PostSwitch {
+ name,
+ yes,
+ foreground,
+ no_background,
+ vars,
+ } => run_toggleable_hook(
+ HookType::PostSwitch,
+ yes,
+ foreground,
+ no_background,
+ name.as_deref(),
+ &vars,
+ ),
+ HookCommand::PreCommit { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PreCommit, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PreMerge { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PreMerge, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PostMerge { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PostMerge, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PreRemove { name, yes, vars } => {
+ run_non_toggle_hook(HookType::PreRemove, yes, name.as_deref(), &vars)
+ }
+ HookCommand::PostRemove {
+ name,
+ yes,
+ foreground,
+ vars,
+ } => run_hook(
+ HookType::PostRemove,
+ yes,
+ Some(foreground),
+ name.as_deref(),
+ &vars,
+ ),
+ HookCommand::Approvals { action } => match action {
+ ApprovalsCommand::Add { all } => add_approvals(all),
+ ApprovalsCommand::Clear { global } => clear_approvals(global),
+ },
+ }
+}
+
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
@@ -579,114 +714,18 @@ fn main() {
clobber,
} => step_relocate(branches, dry_run, commit, clobber),
},
- Commands::Hook { action } => match action {
- HookCommand::Show {
- hook_type,
- expanded,
- } => handle_hook_show(hook_type.as_deref(), expanded),
- HookCommand::PreSwitch { name, yes, vars } => {
- run_hook(HookType::PreSwitch, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PostCreate { name, yes, vars } => {
- run_hook(HookType::PostCreate, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PostStart {
- name,
- yes,
- foreground,
- no_background,
- vars,
- } => {
- if no_background {
- eprintln!(
- "{}",
- warning_message("--no-background is deprecated; use --foreground instead")
- );
- }
- run_hook(
- HookType::PostStart,
- yes,
- Some(foreground || no_background),
- name.as_deref(),
- &vars,
- )
- }
- HookCommand::PostSwitch {
- name,
- yes,
- foreground,
- no_background,
- vars,
- } => {
- if no_background {
- eprintln!(
- "{}",
- warning_message("--no-background is deprecated; use --foreground instead")
- );
- }
- run_hook(
- HookType::PostSwitch,
- yes,
- Some(foreground || no_background),
- name.as_deref(),
- &vars,
- )
- }
- HookCommand::PreCommit { name, yes, vars } => {
- run_hook(HookType::PreCommit, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PreMerge { name, yes, vars } => {
- run_hook(HookType::PreMerge, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PostMerge { name, yes, vars } => {
- run_hook(HookType::PostMerge, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PreRemove { name, yes, vars } => {
- run_hook(HookType::PreRemove, yes, None, name.as_deref(), &vars)
- }
- HookCommand::PostRemove {
- name,
- yes,
- foreground,
- vars,
- } => run_hook(
- HookType::PostRemove,
- yes,
- Some(foreground),
- name.as_deref(),
- &vars,
- ),
- HookCommand::Approvals { action } => match action {
- ApprovalsCommand::Add { all } => add_approvals(all),
- ApprovalsCommand::Clear { global } => clear_approvals(global),
- },
- },
+ Commands::Hook { action } => handle_hook_command(action),
#[cfg(unix)]
Commands::Select { branches, remotes } => {
// Deprecated: show warning and delegate to handle_select
- eprintln!(
- "{}",
- warning_message("wt select is deprecated; use wt switch instead")
- );
+ warn_select_deprecated();
handle_select(branches, remotes)
}
#[cfg(not(unix))]
Commands::Select { .. } => {
- eprintln!(
- "{}",
- warning_message("wt select is deprecated; use wt switch instead")
- );
- eprintln!(
- "{}",
- error_message("Interactive picker is not available on Windows")
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "Specify a branch: <bright-black>wt switch BRANCH</>"
- ))
- );
+ warn_select_deprecated();
+ print_windows_picker_unavailable();
std::process::exit(1);
}
Commands::List {
@@ -750,16 +789,7 @@ fn main() {
// Suppress unused variable warnings on Windows
let _ = (branches, remotes);
- eprintln!(
- "{}",
- error_message("Interactive picker is not available on Windows")
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "Specify a branch: <bright-black>wt switch BRANCH</>"
- ))
- );
+ print_windows_picker_unavailable();
std::process::exit(2);
}
};
@@ -792,14 +822,7 @@ fn main() {
} => UserConfig::load()
.context("Failed to load config")
.and_then(|config| {
- // Handle deprecated --no-background flag
- if no_background {
- eprintln!(
- "{}",
- warning_message("--no-background is deprecated; use --foreground instead")
- );
- }
- let background = !(foreground || no_background);
+ let background = !is_foreground_mode(foreground, no_background);
// Validate conflicting flags
if !delete_branch && force_delete {
@@ -999,15 +1022,6 @@ fn main() {
yes,
stage,
} => {
- // Convert paired flags to Option<bool>
- fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
- match (positive, negative) {
- (true, _) => Some(true),
- (_, true) => Some(false),
- _ => None,
- }
- }
-
// Pass CLI flags as options; handle_merge determines effective defaults
// using per-project config merged with global config
handle_merge(MergeOptions {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 7621314ad..4542769de 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -650,20 +650,20 @@ pub fn handle_remove_output(
force_worktree,
expected_path,
removed_commit,
- } => handle_removed_worktree_output(
+ } => handle_removed_worktree_output(RemovedWorktreeOutputContext {
main_path,
worktree_path,
- *changed_directory,
- branch_name.as_deref(),
- *deletion_mode,
- target_branch.as_deref(),
- *integration_reason,
- *force_worktree,
- expected_path.as_ref(),
- removed_commit.as_deref(),
+ changed_directory: *changed_directory,
+ branch_name: branch_name.as_deref(),
+ deletion_mode: *deletion_mode,
+ target_branch: target_branch.as_deref(),
+ pre_computed_integration: *integration_reason,
+ force_worktree: *force_worktree,
+ expected_path: expected_path.as_deref(),
+ removed_commit: removed_commit.as_deref(),
background,
verify,
- ),
+ }),
RemoveResult::BranchOnly {
branch_name,
deletion_mode,
@@ -1008,22 +1008,38 @@ impl RemovalDisplayInfo {
// ============================================================================
-/// Handle output for RemovedWorktree removal
-#[allow(clippy::too_many_arguments)]
-fn handle_removed_worktree_output(
- main_path: &std::path::Path,
- worktree_path: &std::path::Path,
+struct RemovedWorktreeOutputContext<'a> {
+ main_path: &'a Path,
+ worktree_path: &'a Path,
changed_directory: bool,
- branch_name: Option<&str>,
+ branch_name: Option<&'a str>,
deletion_mode: BranchDeletionMode,
- target_branch: Option<&str>,
+ target_branch: Option<&'a str>,
pre_computed_integration: Option<IntegrationReason>,
force_worktree: bool,
- expected_path: Option<&PathBuf>,
- removed_commit: Option<&str>,
+ expected_path: Option<&'a Path>,
+ removed_commit: Option<&'a str>,
background: bool,
verify: bool,
-) -> anyhow::Result<()> {
+}
+
+/// Handle output for RemovedWorktree removal
+fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhow::Result<()> {
+ let RemovedWorktreeOutputContext {
+ main_path,
+ worktree_path,
+ changed_directory,
+ branch_name,
+ deletion_mode,
+ target_branch,
+ pre_computed_integration,
+ force_worktree,
+ expected_path,
+ removed_commit,
+ background,
+ verify,
+ } = ctx;
+
// Use main_path for discovery - the worktree being removed might be cwd,
// and git operations after removal need a valid working directory.
let repo = worktrunk::git::Repository::at(main_path)?;