Skip to content

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

Refactor config to consolidate hooks into HooksConfig struct

Maximilian Roosb25ee1c5c52f
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index c9ddc4e25..6cf333df4 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -17,12 +17,12 @@
//! This ensures approval happens exactly once at the command entry point,
//! eliminating the need to thread `auto_trust` through execution layers.
-use super::project_config::collect_commands_for_hooks;
+use super::project_config::{HookCommand, collect_commands_for_hooks};
use super::repository_ext::RepositoryCliExt;
use crate::output;
use anyhow::Context;
use color_print::cformat;
-use worktrunk::config::{Command, WorktrunkConfig};
+use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
INFO_SYMBOL, PROMPT_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_bash_with_gutter,
@@ -39,16 +39,17 @@ use worktrunk::styling::{
/// # Parameters
/// - `commands_already_filtered`: If true, commands list is pre-filtered; skip filtering by approval status
pub fn approve_command_batch(
- commands: &[Command],
+ commands: &[HookCommand],
project_id: &str,
config: &WorktrunkConfig,
force: bool,
commands_already_filtered: bool,
) -> anyhow::Result<bool> {
- let needs_approval: Vec<&Command> = commands
+ let needs_approval: Vec<&HookCommand> = commands
.iter()
.filter(|cmd| {
- commands_already_filtered || !config.is_command_approved(project_id, &cmd.template)
+ commands_already_filtered
+ || !config.is_command_approved(project_id, &cmd.command.template)
})
.collect();
@@ -77,8 +78,13 @@ pub fn approve_command_batch(
let mut updated = false;
for cmd in &needs_approval {
- if !project_entry.approved_commands.contains(&cmd.template) {
- project_entry.approved_commands.push(cmd.template.clone());
+ if !project_entry
+ .approved_commands
+ .contains(&cmd.command.template)
+ {
+ project_entry
+ .approved_commands
+ .push(cmd.command.template.clone());
updated = true;
}
}
@@ -94,7 +100,7 @@ pub fn approve_command_batch(
Ok(true)
}
-fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> anyhow::Result<bool> {
+fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> anyhow::Result<bool> {
use std::io::{self, IsTerminal, Write};
let project_name = project_id.split('/').next_back().unwrap_or(project_id);
@@ -115,15 +121,15 @@ fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> anyhow:
for cmd in commands {
// Format as: {phase} {bold}{name}{bold:#}:
- // Phase comes from the command itself (e.g., "pre-commit", "pre-merge")
+ // Phase comes from the hook type (e.g., "pre-commit", "pre-merge")
// Uses INFO_SYMBOL (○) since this is a preview, not active execution
- let phase = cmd.phase.to_string();
- let label = match &cmd.name {
+ let phase = cmd.hook_type.to_string();
+ let label = match &cmd.command.name {
Some(name) => cformat!("{INFO_SYMBOL} {phase} <bold>{name}</>:"),
None => format!("{INFO_SYMBOL} {phase}:"),
};
eprintln!("{label}");
- eprint!("{}", format_bash_with_gutter(&cmd.template, ""));
+ eprint!("{}", format_bash_with_gutter(&cmd.command.template, ""));
}
// Check if stdin is a TTY before attempting to prompt
@@ -193,7 +199,7 @@ pub fn approve_hooks_filtered(
// Apply name filter before approval to only prompt for targeted commands
if let Some(name) = name_filter {
- commands.retain(|cmd| cmd.name.as_deref() == Some(name));
+ commands.retain(|cmd| cmd.command.name.as_deref() == Some(name));
}
if commands.is_empty() {
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 292cb1ef3..c3478446e 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -123,6 +123,7 @@ fn expand_commands(
commands: &[Command],
ctx: &CommandContext<'_>,
extra_vars: &[(&str, &str)],
+ hook_type: HookType,
) -> anyhow::Result<Vec<(Command, String)>> {
if commands.is_empty() {
return Ok(Vec::new());
@@ -149,7 +150,7 @@ fn expand_commands(
// Build per-command JSON with hook_type and hook_name
let mut cmd_context = base_context.clone();
- cmd_context.insert("hook_type".into(), cmd.phase.to_string());
+ cmd_context.insert("hook_type".into(), hook_type.to_string());
if let Some(ref name) = cmd.name {
cmd_context.insert("hook_name".into(), name.clone());
}
@@ -157,12 +158,7 @@ fn expand_commands(
.expect("HashMap<String, String> serialization should never fail");
result.push((
- Command::with_expansion(
- cmd.name.clone(),
- cmd.template.clone(),
- expanded_str,
- cmd.phase,
- ),
+ Command::with_expansion(cmd.name.clone(), cmd.template.clone(), expanded_str),
context_json,
));
}
@@ -184,12 +180,12 @@ pub fn prepare_commands(
extra_vars: &[(&str, &str)],
hook_type: HookType,
) -> anyhow::Result<Vec<PreparedCommand>> {
- let commands = command_config.commands_with_phase(hook_type);
+ let commands = command_config.commands();
if commands.is_empty() {
return Ok(Vec::new());
}
- let expanded_with_json = expand_commands(&commands, ctx, extra_vars)?;
+ let expanded_with_json = expand_commands(commands, ctx, extra_vars, hook_type)?;
Ok(expanded_with_json
.into_iter()
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index ea1aae84d..0ce9e2614 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -145,10 +145,10 @@ impl<'a> CommitGenerator<'a> {
impl CommitOptions<'_> {
pub fn commit(self) -> anyhow::Result<()> {
let project_config = self.ctx.repo.load_project_config()?;
- let user_hooks_exist = self.ctx.config.pre_commit.is_some();
+ let user_hooks_exist = self.ctx.config.hooks.pre_commit.is_some();
let project_hooks_exist = project_config
.as_ref()
- .map(|c| c.pre_commit.is_some())
+ .map(|c| c.hooks.pre_commit.is_some())
.unwrap_or(false);
let any_hooks_exist = user_hooks_exist || project_hooks_exist;
@@ -168,7 +168,7 @@ impl CommitOptions<'_> {
.collect();
// Run user pre-commit hooks first (no approval required)
- if let Some(user_config) = &self.ctx.config.pre_commit {
+ if let Some(user_config) = &self.ctx.config.hooks.pre_commit {
pipeline
.run_sequential(
user_config,
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 8d11f3be9..7a3f77e57 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -74,6 +74,17 @@ impl<'a> HookPipeline<'a> {
Ok(Self::filter_by_name(commands, name_filter))
}
+ fn announce_command(
+ &self,
+ label_prefix: &str,
+ prepared: &PreparedCommand,
+ ) -> anyhow::Result<()> {
+ let label = crate::commands::format_command_label(label_prefix, prepared.name.as_deref());
+ crate::output::print(progress_message(format!("{label}:")))?;
+ crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
+ Ok(())
+ }
+
/// Filter commands by name (returns empty vec if name not found - caller decides if that's an error)
fn filter_by_name(
commands: Vec<PreparedCommand>,
@@ -112,10 +123,7 @@ impl<'a> HookPipeline<'a> {
let label_prefix = source.format_label(hook_type);
for prepared in commands {
- let label =
- crate::commands::format_command_label(&label_prefix, prepared.name.as_deref());
- crate::output::print(progress_message(format!("{label}:")))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
+ self.announce_command(&label_prefix, &prepared)?;
if let Err(err) = execute_command_in_worktree(
self.ctx.worktree_path,
@@ -201,10 +209,7 @@ impl<'a> HookPipeline<'a> {
let label_prefix = source.format_label(hook_type);
for prepared in commands {
- let label =
- crate::commands::format_command_label(&label_prefix, prepared.name.as_deref());
- crate::output::print(progress_message(format!("{label}:")))?;
- crate::output::gutter(format_bash_with_gutter(&prepared.expanded, ""))?;
+ self.announce_command(&label_prefix, &prepared)?;
let name = prepared.name.as_deref().unwrap_or("cmd");
// Include source in operation name to prevent log file collisions between
@@ -237,7 +242,7 @@ impl<'a> HookPipeline<'a> {
target_branch: Option<&str>,
name_filter: Option<&str>,
) -> anyhow::Result<()> {
- let Some(pre_commit_config) = &project_config.pre_commit else {
+ let Some(pre_commit_config) = &project_config.hooks.pre_commit else {
return Ok(());
};
diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rs
index 31b284674..21aac8abb 100644
--- a/src/commands/list/collect_progressive_impl.rs
+++ b/src/commands/list/collect_progressive_impl.rs
@@ -606,6 +606,26 @@ fn parse_port_from_url(url: &str) -> Option<u16> {
// Collection Entry Points
// ============================================================================
+fn collect_progressive(
+ ctx: TaskContext,
+ include_worktree_tasks: bool,
+ options: &CollectOptions,
+ tx: Sender<Result<TaskResult, TaskError>>,
+ expected_results: &Arc<ExpectedResults>,
+) {
+ let spawner = TaskSpawner::new(tx, expected_results.clone());
+ let skip = &options.skip_tasks;
+
+ std::thread::scope(|s| {
+ // Core tasks (always run)
+ spawner.spawn_core_tasks(s, &ctx);
+ if include_worktree_tasks {
+ spawner.spawn_worktree_only_tasks(s, &ctx);
+ }
+ spawner.spawn_optional_tasks(s, &ctx, skip);
+ });
+}
+
/// Collect worktree data progressively, sending results as each task completes.
///
/// Spawns parallel git operations (up to 10). Each task sends a TaskResult when it
@@ -652,15 +672,7 @@ pub fn collect_worktree_progressive(
item_url,
};
- let spawner = TaskSpawner::new(tx, expected_results.clone());
- let skip = &options.skip_tasks;
-
- std::thread::scope(|s| {
- // Core tasks (always run)
- spawner.spawn_core_tasks(s, &ctx);
- spawner.spawn_worktree_only_tasks(s, &ctx);
- spawner.spawn_optional_tasks(s, &ctx, skip);
- });
+ collect_progressive(ctx, true, options, tx, expected_results);
}
/// Collect branch data progressively, sending results as each task completes.
@@ -710,14 +722,7 @@ pub fn collect_branch_progressive(
item_url,
};
- let spawner = TaskSpawner::new(tx, expected_results.clone());
- let skip = &options.skip_tasks;
-
- std::thread::scope(|s| {
- // Core tasks (always run)
- spawner.spawn_core_tasks(s, &ctx);
- spawner.spawn_optional_tasks(s, &ctx, skip);
- });
+ collect_progressive(ctx, false, options, tx, expected_results);
}
// ============================================================================
diff --git a/src/commands/list/columns.rs b/src/commands/list/columns.rs
index 9bea9f4d1..7dc1c0f0e 100644
--- a/src/commands/list/columns.rs
+++ b/src/commands/list/columns.rs
@@ -18,6 +18,26 @@ pub enum ColumnKind {
Message,
}
+impl ColumnKind {
+ pub const fn header(self) -> &'static str {
+ match self {
+ ColumnKind::Gutter => "",
+ ColumnKind::Branch => "Branch",
+ ColumnKind::Status => "Status",
+ ColumnKind::WorkingDiff => "HEAD±",
+ ColumnKind::AheadBehind => "main↕",
+ ColumnKind::BranchDiff => "main…±",
+ ColumnKind::Path => "Path",
+ ColumnKind::Upstream => "Remote⇅",
+ ColumnKind::Url => "URL",
+ ColumnKind::Time => "Age",
+ ColumnKind::CiStatus => "CI",
+ ColumnKind::Commit => "Commit",
+ ColumnKind::Message => "Message",
+ }
+ }
+}
+
/// Differentiates between diff-style columns with plus/minus symbols and those with arrows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiffVariant {
@@ -32,96 +52,45 @@ pub enum DiffVariant {
#[derive(Clone, Copy, Debug)]
pub struct ColumnSpec {
pub kind: ColumnKind,
- pub header: &'static str,
pub base_priority: u8,
/// Task required for this column's data. If Some and task is skipped, column is hidden.
pub requires_task: Option<TaskKind>,
- pub display_index: u8,
}
impl ColumnSpec {
- pub const fn new(
- kind: ColumnKind,
- header: &'static str,
- base_priority: u8,
- requires_task: Option<TaskKind>,
- display_index: u8,
- ) -> Self {
+ pub const fn new(kind: ColumnKind, base_priority: u8, requires_task: Option<TaskKind>) -> Self {
Self {
kind,
- header,
base_priority,
requires_task,
- display_index,
}
}
}
/// Static registry of all possible columns in display order.
pub const COLUMN_SPECS: &[ColumnSpec] = &[
- ColumnSpec::new(ColumnKind::Gutter, super::layout::HEADER_GUTTER, 0, None, 0),
- ColumnSpec::new(ColumnKind::Branch, super::layout::HEADER_BRANCH, 1, None, 1),
- ColumnSpec::new(ColumnKind::Status, super::layout::HEADER_STATUS, 2, None, 2),
- ColumnSpec::new(
- ColumnKind::WorkingDiff,
- super::layout::HEADER_WORKING_DIFF,
- 3,
- None,
- 3,
- ),
- ColumnSpec::new(
- ColumnKind::AheadBehind,
- super::layout::HEADER_AHEAD_BEHIND,
- 4,
- None,
- 4,
- ),
- ColumnSpec::new(
- ColumnKind::BranchDiff,
- super::layout::HEADER_BRANCH_DIFF,
- 5,
- Some(TaskKind::BranchDiff),
- 5,
- ),
- ColumnSpec::new(ColumnKind::Path, super::layout::HEADER_PATH, 6, None, 6),
- ColumnSpec::new(
- ColumnKind::Upstream,
- super::layout::HEADER_UPSTREAM,
- 7,
- None,
- 7,
- ),
- ColumnSpec::new(
- ColumnKind::Url,
- super::layout::HEADER_URL,
- 8,
- Some(TaskKind::UrlStatus),
- 8,
- ),
- ColumnSpec::new(
- ColumnKind::CiStatus,
- super::layout::HEADER_CI,
- 9,
- Some(TaskKind::CiStatus),
- 9,
- ),
- ColumnSpec::new(
- ColumnKind::Commit,
- super::layout::HEADER_COMMIT,
- 10,
- None,
- 10,
- ),
- ColumnSpec::new(ColumnKind::Time, super::layout::HEADER_AGE, 11, None, 11),
- ColumnSpec::new(
- ColumnKind::Message,
- super::layout::HEADER_MESSAGE,
- 12,
- None,
- 12,
- ),
+ ColumnSpec::new(ColumnKind::Gutter, 0, None),
+ ColumnSpec::new(ColumnKind::Branch, 1, None),
+ ColumnSpec::new(ColumnKind::Status, 2, None),
+ ColumnSpec::new(ColumnKind::WorkingDiff, 3, None),
+ ColumnSpec::new(ColumnKind::AheadBehind, 4, None),
+ ColumnSpec::new(ColumnKind::BranchDiff, 5, Some(TaskKind::BranchDiff)),
+ ColumnSpec::new(ColumnKind::Path, 6, None),
+ ColumnSpec::new(ColumnKind::Upstream, 7, None),
+ ColumnSpec::new(ColumnKind::Url, 8, Some(TaskKind::UrlStatus)),
+ ColumnSpec::new(ColumnKind::CiStatus, 9, Some(TaskKind::CiStatus)),
+ ColumnSpec::new(ColumnKind::Commit, 10, None),
+ ColumnSpec::new(ColumnKind::Time, 11, None),
+ ColumnSpec::new(ColumnKind::Message, 12, None),
];
+pub fn column_display_index(kind: ColumnKind) -> usize {
+ COLUMN_SPECS
+ .iter()
+ .position(|spec| spec.kind == kind)
+ .unwrap_or(usize::MAX)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -146,14 +115,6 @@ mod tests {
ColumnKind::Message,
];
assert_eq!(kinds, expected, "column order should match display layout");
-
- // display_index should match position to keep layout lookups O(1)
- for (idx, spec) in COLUMN_SPECS.iter().enumerate() {
- assert_eq!(
- spec.display_index as usize, idx,
- "display_index must be contiguous"
- );
- }
}
#[test]
@@ -191,93 +152,21 @@ mod tests {
}
}
- #[test]
- fn test_column_kind_debug() {
- // Test Debug trait implementation
- assert_eq!(format!("{:?}", ColumnKind::Gutter), "Gutter");
- assert_eq!(format!("{:?}", ColumnKind::Branch), "Branch");
- assert_eq!(format!("{:?}", ColumnKind::Status), "Status");
- assert_eq!(format!("{:?}", ColumnKind::Message), "Message");
- }
-
- #[test]
- fn test_column_kind_copy() {
- let kind = ColumnKind::Branch;
- let copied1 = kind; // Copy trait
- let copied2 = kind;
- assert_eq!(kind, copied1);
- assert_eq!(kind, copied2);
- }
-
- #[test]
- fn test_column_kind_hash() {
- let mut set = HashSet::new();
- set.insert(ColumnKind::Branch);
- set.insert(ColumnKind::Path);
- assert!(set.contains(&ColumnKind::Branch));
- assert!(set.contains(&ColumnKind::Path));
- assert!(!set.contains(&ColumnKind::Message));
- }
-
- #[test]
- fn test_diff_variant_debug() {
- assert_eq!(format!("{:?}", DiffVariant::Signs), "Signs");
- assert_eq!(format!("{:?}", DiffVariant::Arrows), "Arrows");
- assert_eq!(
- format!("{:?}", DiffVariant::UpstreamArrows),
- "UpstreamArrows"
- );
- }
-
- #[test]
- fn test_diff_variant_copy() {
- let variant = DiffVariant::Signs;
- let copied1 = variant; // Copy trait
- let copied2 = variant;
- assert_eq!(variant, copied1);
- assert_eq!(variant, copied2);
- }
-
#[test]
fn test_column_spec_new() {
- let spec = ColumnSpec::new(ColumnKind::Branch, "Branch", 1, None, 1);
+ let spec = ColumnSpec::new(ColumnKind::Branch, 1, None);
assert_eq!(spec.kind, ColumnKind::Branch);
- assert_eq!(spec.header, "Branch");
assert_eq!(spec.base_priority, 1);
assert!(spec.requires_task.is_none());
- assert_eq!(spec.display_index, 1);
}
#[test]
fn test_column_spec_with_required_task() {
- let spec = ColumnSpec::new(
- ColumnKind::BranchDiff,
- "main…±",
- 5,
- Some(TaskKind::BranchDiff),
- 5,
- );
+ let spec = ColumnSpec::new(ColumnKind::BranchDiff, 5, Some(TaskKind::BranchDiff));
assert_eq!(spec.kind, ColumnKind::BranchDiff);
assert_eq!(spec.requires_task, Some(TaskKind::BranchDiff));
}
- #[test]
- fn test_column_spec_debug() {
- let spec = ColumnSpec::new(ColumnKind::Path, "Path", 6, None, 6);
- let debug_str = format!("{:?}", spec);
- assert!(debug_str.contains("ColumnSpec"));
- assert!(debug_str.contains("Path"));
- }
-
- #[test]
- fn test_column_spec_copy() {
- let spec = ColumnSpec::new(ColumnKind::Time, "Age", 10, None, 10);
- let copied = spec; // Copy trait - should work without clone
- assert_eq!(spec.kind, copied.kind);
- assert_eq!(spec.header, copied.header);
- assert_eq!(spec.base_priority, copied.base_priority);
- }
-
#[test]
fn test_column_specs_priorities_are_unique() {
// Each column should have a unique base_priority
@@ -293,12 +182,12 @@ mod tests {
#[test]
fn test_column_specs_headers_are_non_empty() {
// All columns except Gutter should have non-empty headers
- for spec in COLUMN_SPECS {
- if spec.kind != ColumnKind::Gutter {
+ for kind in COLUMN_SPECS.iter().map(|spec| spec.kind) {
+ if kind != ColumnKind::Gutter {
assert!(
- !spec.header.is_empty(),
+ !kind.header().is_empty(),
"{:?} should have a non-empty header",
- spec.kind
+ kind
);
}
}
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 0df9070d5..9eb9d3bc4 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -178,30 +178,13 @@ use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{ADDITION, DELETION};
use super::collect::TaskKind;
-use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec};
+use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, column_display_index};
// Re-export DiffVariant for external use (e.g., select command)
pub use super::columns::DiffVariant;
/// Width of short commit hash display (first 8 hex characters)
const COMMIT_HASH_WIDTH: usize = 8;
-
-/// Column header labels - single source of truth for all column headers.
-/// Both layout calculations and rendering use these constants.
-pub const HEADER_GUTTER: &str = ""; // No header for gutter (type indicator column)
-pub const HEADER_BRANCH: &str = "Branch";
-pub const HEADER_STATUS: &str = "Status";
-pub const HEADER_WORKING_DIFF: &str = "HEAD±";
-pub const HEADER_AHEAD_BEHIND: &str = "main↕";
-pub const HEADER_BRANCH_DIFF: &str = "main…±";
-pub const HEADER_PATH: &str = "Path";
-pub const HEADER_UPSTREAM: &str = "Remote⇅";
-pub const HEADER_URL: &str = "URL";
-pub const HEADER_AGE: &str = "Age";
-pub const HEADER_CI: &str = "CI";
-pub const HEADER_COMMIT: &str = "Commit";
-pub const HEADER_MESSAGE: &str = "Message";
-
/// Get terminal width for list rendering.
pub fn get_safe_list_width() -> usize {
get_terminal_width()
@@ -495,13 +478,13 @@ fn build_estimated_widths(
//
// Status column: Must match PositionMask::FULL width for consistent alignment
// PositionMask::FULL allocates: 1+1+1+1+1+1+2 = 8 chars (7 positions)
- let status_fixed = fit_header(HEADER_STATUS, 8);
- let working_diff_fixed = fit_header(HEADER_WORKING_DIFF, 9); // "+999 -999"
- let ahead_behind_fixed = fit_header(HEADER_AHEAD_BEHIND, 7); // "↑99 ↓99"
- let branch_diff_fixed = fit_header(HEADER_BRANCH_DIFF, 9); // "+999 -999"
- let upstream_fixed = fit_header(HEADER_UPSTREAM, 7); // "↑99 ↓99"
+ let status_fixed = fit_header(ColumnKind::Status.header(), 8);
+ let working_diff_fixed = fit_header(ColumnKind::WorkingDiff.header(), 9); // "+999 -999"
+ let ahead_behind_fixed = fit_header(ColumnKind::AheadBehind.header(), 7); // "↑99 ↓99"
+ let branch_diff_fixed = fit_header(ColumnKind::BranchDiff.header(), 9); // "+999 -999"
+ let upstream_fixed = fit_header(ColumnKind::Upstream.header(), 7); // "↑99 ↓99"
let age_estimate = 4; // "11mo" (short format)
- let ci_estimate = fit_header(HEADER_CI, 1); // Single indicator symbol
+ let ci_estimate = fit_header(ColumnKind::CiStatus.header(), 1); // Single indicator symbol
// Assume columns will have data (better to show and hide than to not show).
// This is a limitation of progressive mode - we can't know which columns have data
@@ -524,7 +507,7 @@ fn build_estimated_widths(
// URL width estimated from template + longest branch (or fallback)
// When url_width is 0 (no template), don't allocate any space for URL column
let url_estimate = if url_width > 0 {
- fit_header(HEADER_URL, url_width)
+ fit_header(ColumnKind::Url.header(), url_width)
} else {
0
};
@@ -692,8 +675,8 @@ fn allocate_columns_with_priority(
max_message_len = message_col.width;
}
- // Sort by display index to maintain correct visual order
- pending.sort_by_key(|col| col.spec.display_index);
+ // Sort by display order to maintain correct visual order
+ pending.sort_by_key(|col| column_display_index(col.spec.kind));
// Build final column layouts with positions
let gap = 2;
@@ -719,7 +702,7 @@ fn allocate_columns_with_priority(
columns.push(ColumnLayout {
kind: col.spec.kind,
- header: col.spec.header,
+ header: col.spec.kind.header(),
start,
width: col.width,
format: col.format,
@@ -795,7 +778,7 @@ pub fn calculate_layout_with_width(
.max_by_key(|b| b.width());
let max_branch = longest_branch.map(|b| b.width()).unwrap_or(0);
- let max_branch = fit_header(HEADER_BRANCH, max_branch);
+ let max_branch = fit_header(ColumnKind::Branch.header(), max_branch);
let path_data_width = items
.iter()
@@ -806,7 +789,7 @@ pub fn calculate_layout_with_width(
})
.max()
.unwrap_or(0);
- let max_path_width = fit_header(HEADER_PATH, path_data_width);
+ let max_path_width = fit_header(ColumnKind::Path.header(), path_data_width);
// Check if any worktree has a path that doesn't match the expected template.
// Path column is only useful when there's a mismatch; otherwise it's redundant with branch.
@@ -821,7 +804,7 @@ pub fn calculate_layout_with_width(
// Build pre-allocated width estimates (same as buffered mode)
let metadata = build_estimated_widths(max_branch, skip_tasks, has_path_mismatch, url_width);
- let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH);
+ let commit_width = fit_header(ColumnKind::Commit.header(), COMMIT_HASH_WIDTH);
allocate_columns_with_priority(
&metadata,
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 32da5d586..d6cd46cf9 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,5 +1,5 @@
use worktrunk::HookType;
-use worktrunk::config::{Command, ProjectConfig};
+use worktrunk::config::ProjectConfig;
use worktrunk::git::Repository;
use worktrunk::styling::info_message;
@@ -8,7 +8,7 @@ use super::command_executor::CommandContext;
use super::commit::CommitOptions;
use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, run_hook_with_filter};
-use super::project_config::collect_commands_for_hooks;
+use super::project_config::{HookCommand, collect_commands_for_hooks};
use super::repository_ext::RepositoryCliExt;
use super::worktree::{BranchDeletionMode, MergeOperations, RemoveResult, handle_push};
@@ -43,9 +43,9 @@ struct MergeCommandCollector<'a> {
}
/// Commands collected for batch approval with their project identifier
-/// - `Vec<Command>`: Commands with both template and (initial) expanded forms
+/// - `Vec<HookCommand>`: Commands with their hook types for approval display
/// - `String`: Project identifier for config lookup
-type CollectedCommands = (Vec<Command>, String);
+type CollectedCommands = (Vec<HookCommand>, String);
impl<'a> MergeCommandCollector<'a> {
/// Collect all commands that will be executed during merge
@@ -307,8 +307,8 @@ pub fn run_pre_merge_commands(
) -> anyhow::Result<()> {
run_hook_with_filter(
ctx,
- ctx.config.pre_merge.as_ref(),
- project_config.pre_merge.as_ref(),
+ ctx.config.hooks.pre_merge.as_ref(),
+ project_config.hooks.pre_merge.as_ref(),
HookType::PreMerge,
&[("target", target_branch)],
HookFailureStrategy::FailFast,
@@ -331,8 +331,10 @@ pub fn execute_post_merge_commands(
run_hook_with_filter(
ctx,
- ctx.config.post_merge.as_ref(),
- project_config.as_ref().and_then(|c| c.post_merge.as_ref()),
+ ctx.config.hooks.post_merge.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_merge.as_ref()),
HookType::PostMerge,
&[("target", target_branch)],
HookFailureStrategy::Warn,
@@ -354,8 +356,10 @@ pub fn execute_pre_remove_commands(
run_hook_with_filter(
ctx,
- ctx.config.pre_remove.as_ref(),
- project_config.as_ref().and_then(|c| c.pre_remove.as_ref()),
+ ctx.config.hooks.pre_remove.as_ref(),
+ project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_remove.as_ref()),
HookType::PreRemove,
&[],
HookFailureStrategy::FailFast,
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 12411cd34..d8eaaccff 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -1,24 +1,30 @@
use worktrunk::config::{Command, ProjectConfig};
use worktrunk::git::HookType;
+#[derive(Clone)]
+pub struct HookCommand {
+ pub hook_type: HookType,
+ pub command: Command,
+}
+
/// Collect commands for the given hook types, preserving order of the provided hooks.
pub fn collect_commands_for_hooks(
project_config: &ProjectConfig,
hooks: &[HookType],
-) -> Vec<Command> {
+) -> Vec<HookCommand> {
let mut commands = Vec::new();
for hook in hooks {
- let cfg = match hook {
- HookType::PostCreate => &project_config.post_create,
- HookType::PostStart => &project_config.post_start,
- HookType::PostSwitch => &project_config.post_switch,
- HookType::PreCommit => &project_config.pre_commit,
- HookType::PreMerge => &project_config.pre_merge,
- HookType::PostMerge => &project_config.post_merge,
- HookType::PreRemove => &project_config.pre_remove,
- };
- if let Some(config) = cfg {
- commands.extend(config.commands_with_phase(*hook));
+ if let Some(config) = project_config.hooks.get(*hook) {
+ commands.extend(
+ config
+ .commands()
+ .iter()
+ .cloned()
+ .map(|command| HookCommand {
+ hook_type: *hook,
+ command,
+ }),
+ );
}
}
commands
@@ -49,7 +55,7 @@ pre-merge = "cargo test"
let config = make_project_config_with_hooks();
let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
assert_eq!(commands.len(), 1);
- assert_eq!(commands[0].template, "npm install");
+ assert_eq!(commands[0].command.template, "npm install");
}
#[test]
@@ -58,8 +64,8 @@ pre-merge = "cargo test"
let commands =
collect_commands_for_hooks(&config, &[HookType::PostCreate, HookType::PreMerge]);
assert_eq!(commands.len(), 2);
- assert_eq!(commands[0].template, "npm install");
- assert_eq!(commands[1].template, "cargo test");
+ assert_eq!(commands[0].command.template, "npm install");
+ assert_eq!(commands[1].command.template, "cargo test");
}
#[test]
@@ -76,8 +82,8 @@ pre-merge = "cargo test"
let commands =
collect_commands_for_hooks(&config, &[HookType::PreMerge, HookType::PostCreate]);
assert_eq!(commands.len(), 2);
- assert_eq!(commands[0].template, "cargo test");
- assert_eq!(commands[1].template, "npm install");
+ assert_eq!(commands[0].command.template, "cargo test");
+ assert_eq!(commands[1].command.template, "npm install");
}
#[test]
@@ -107,8 +113,8 @@ build = "npm run build"
let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
assert_eq!(commands.len(), 2);
// Named commands preserve order from TOML
- assert_eq!(commands[0].name, Some("install".to_string()));
- assert_eq!(commands[1].name, Some("build".to_string()));
+ assert_eq!(commands[0].command.name, Some("install".to_string()));
+ assert_eq!(commands[1].command.name, Some("build".to_string()));
}
#[test]
@@ -116,6 +122,6 @@ build = "npm run build"
let config = make_project_config_with_hooks();
let commands = collect_commands_for_hooks(&config, &[HookType::PostCreate]);
assert_eq!(commands.len(), 1);
- assert_eq!(commands[0].phase, HookType::PostCreate);
+ assert_eq!(commands[0].hook_type, HookType::PostCreate);
}
}
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 67b8db6d2..aa8a3b9dd 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -52,7 +52,7 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
// Helper to get user hook config
macro_rules! user_hook {
($field:ident) => {
- ctx.config.$field.as_ref()
+ ctx.config.hooks.$field.as_ref()
};
}
@@ -75,7 +75,9 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
match hook_type {
HookType::PostCreate => {
let user_config = user_hook!(post_create);
- let project_config = project_config.as_ref().and_then(|c| c.post_create.as_ref());
+ let project_config = project_config
+ .as_ref()
+ .and_then(|c| c.hooks.post_create.as_ref());
require_hooks(user_config, project_config, hook_type)?;
run_hook_with_filter(
&ctx,
@@ -89,7 +91,9 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
}
HookType::PostStart => {
let user_config = user_hook!(post_start);
- let project_config = project_config.as_ref().and_then(|c| c.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)?;
run_hook_with_filter(
&ctx,
@@ -103,7 +107,9 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
}
HookType::PostSwitch => {
let user_config = user_hook!(post_switch);
- let project_config = project_config.as_ref().and_then(|c| c.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)?;
run_hook_with_filter(
&ctx,
@@ -117,7 +123,9 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->
}
HookType::PreCommit => {
let user_config = user_hook!(pre_commit);
- let project_config = project_config.as_ref().and_then(|c| c.pre_commit.as_ref());
+ let project_config = project_config
+ .as_ref()
+ .and_then(|c| c.hooks.pre_commit.as_ref());
require_hooks(user_config, project_config, hook_type)?;
// Pre-commit hook can optionally use target branch context
let target_branch = repo.default_branch().ok();
@@ -253,9 +261,9 @@ pub fn handle_squash(
let project_config = repo.load_project_config()?;
let has_project_pre_commit = project_config
.as_ref()
- .map(|c| c.pre_commit.is_some())
+ .map(|c| c.hooks.pre_commit.is_some())
.unwrap_or(false);
- let has_user_pre_commit = ctx.config.pre_commit.is_some();
+ let has_user_pre_commit = ctx.config.hooks.pre_commit.is_some();
let has_any_pre_commit = has_project_pre_commit || has_user_pre_commit;
if skip_pre_commit && has_any_pre_commit {
@@ -268,7 +276,7 @@ pub fn handle_squash(
let extra_vars = [("target", target_branch.as_str())];
// Run user pre-commit hooks first (unless skipped)
- if !skip_pre_commit && let Some(user_config) = &ctx.config.pre_commit {
+ if !skip_pre_commit && let Some(user_config) = &ctx.config.hooks.pre_commit {
use super::hooks::{HookFailureStrategy, HookSource};
pipeline
.run_sequential(
@@ -573,7 +581,7 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {
let commands_to_approve = if !show_all {
let unapproved: Vec<_> = commands
.into_iter()
- .filter(|cmd| !config.is_command_approved(project_id, &cmd.template))
+ .filter(|cmd| !config.is_command_approved(project_id, &cmd.command.template))
.collect();
if unapproved.is_empty() {
@@ -738,13 +746,13 @@ fn render_user_hooks(
// Collect all user hooks
let hooks = [
- (HookType::PostCreate, &config.post_create),
- (HookType::PostStart, &config.post_start),
- (HookType::PostSwitch, &config.post_switch),
- (HookType::PreCommit, &config.pre_commit),
- (HookType::PreMerge, &config.pre_merge),
- (HookType::PostMerge, &config.post_merge),
- (HookType::PreRemove, &config.pre_remove),
+ (HookType::PostCreate, &config.hooks.post_create),
+ (HookType::PostStart, &config.hooks.post_start),
+ (HookType::PostSwitch, &config.hooks.post_switch),
+ (HookType::PreCommit, &config.hooks.pre_commit),
+ (HookType::PreMerge, &config.hooks.pre_merge),
+ (HookType::PostMerge, &config.hooks.post_merge),
+ (HookType::PreRemove, &config.hooks.pre_remove),
];
let mut has_any = false;
@@ -798,13 +806,13 @@ fn render_project_hooks(
// Collect all project hooks
let hooks = [
- (HookType::PostCreate, &config.post_create),
- (HookType::PostStart, &config.post_start),
- (HookType::PostSwitch, &config.post_switch),
- (HookType::PreCommit, &config.pre_commit),
- (HookType::PreMerge, &config.pre_merge),
- (HookType::PostMerge, &config.post_merge),
- (HookType::PreRemove, &config.pre_remove),
+ (HookType::PostCreate, &config.hooks.post_create),
+ (HookType::PostStart, &config.hooks.post_start),
+ (HookType::PostSwitch, &config.hooks.post_switch),
+ (HookType::PreCommit, &config.hooks.pre_commit),
+ (HookType::PreMerge, &config.hooks.pre_merge),
+ (HookType::PostMerge, &config.hooks.post_merge),
+ (HookType::PreRemove, &config.hooks.pre_remove),
];
let mut has_any = false;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 9efeb8143..edd984459 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -834,7 +834,7 @@ impl<'a> CommandContext<'a> {
let pipeline = HookPipeline::new(*self);
// Run user hooks first (no approval required)
- if let Some(user_config) = &self.config.post_create {
+ if let Some(user_config) = &self.config.hooks.post_create {
pipeline.run_sequential(
user_config,
HookType::PostCreate,
@@ -851,7 +851,7 @@ impl<'a> CommandContext<'a> {
None => return Ok(()),
};
- let Some(post_create_config) = &project_config.post_create else {
+ let Some(post_create_config) = &project_config.hooks.post_create else {
return Ok(());
};
@@ -877,7 +877,7 @@ impl<'a> CommandContext<'a> {
let pipeline = HookPipeline::new(*self);
// Spawn user hooks first (no approval required)
- if let Some(user_config) = &self.config.post_start {
+ if let Some(user_config) = &self.config.hooks.post_start {
pipeline.spawn_background(
user_config,
HookType::PostStart,
@@ -893,7 +893,7 @@ impl<'a> CommandContext<'a> {
None => return Ok(()),
};
- let Some(post_start_config) = &project_config.post_start else {
+ let Some(post_start_config) = &project_config.hooks.post_start else {
return Ok(());
};
@@ -918,7 +918,7 @@ impl<'a> CommandContext<'a> {
let pipeline = HookPipeline::new(*self);
// Spawn user hooks first (no approval required)
- if let Some(user_config) = &self.config.post_switch {
+ if let Some(user_config) = &self.config.hooks.post_switch {
pipeline.spawn_background(
user_config,
HookType::PostSwitch,
@@ -934,7 +934,7 @@ impl<'a> CommandContext<'a> {
None => return Ok(()),
};
- let Some(post_switch_config) = &project_config.post_switch else {
+ let Some(post_switch_config) = &project_config.hooks.post_switch else {
return Ok(());
};
diff --git a/src/completion.rs b/src/completion.rs
index c169d0f62..04fb07db7 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -220,12 +220,12 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {
// Load user config and add user hook names
if let Ok(user_config) = WorktrunkConfig::load() {
let user_command_config = match hook_type {
- "post-create" => &user_config.post_create,
- "post-start" => &user_config.post_start,
- "pre-commit" => &user_config.pre_commit,
- "pre-merge" => &user_config.pre_merge,
- "post-merge" => &user_config.post_merge,
- "pre-remove" => &user_config.pre_remove,
+ "post-create" => &user_config.hooks.post_create,
+ "post-start" => &user_config.hooks.post_start,
+ "pre-commit" => &user_config.hooks.pre_commit,
+ "pre-merge" => &user_config.hooks.pre_merge,
+ "post-merge" => &user_config.hooks.post_merge,
+ "pre-remove" => &user_config.hooks.pre_remove,
_ => &None,
};
@@ -246,12 +246,12 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {
&& let Ok(Some(project_config)) = ProjectConfig::load(repo_root)
{
let project_command_config = match hook_type {
- "post-create" => &project_config.post_create,
- "post-start" => &project_config.post_start,
- "pre-commit" => &project_config.pre_commit,
- "pre-merge" => &project_config.pre_merge,
- "post-merge" => &project_config.post_merge,
- "pre-remove" => &project_config.pre_remove,
+ "post-create" => &project_config.hooks.post_create,
+ "post-start" => &project_config.hooks.post_start,
+ "pre-commit" => &project_config.hooks.pre_commit,
+ "pre-merge" => &project_config.hooks.pre_merge,
+ "post-merge" => &project_config.hooks.post_merge,
+ "pre-remove" => &project_config.hooks.pre_remove,
_ => &None,
};
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 260cea694..a43cc468c 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -3,13 +3,9 @@
//! Handles parsing and representation of commands that run during various phases
//! of worktree and merge operations.
-use crate::git::HookType;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
-/// Phase in which a command executes (alias to the canonical hook type)
-pub type CommandPhase = HookType;
-
/// Represents a command with its template and optionally expanded form
#[derive(Debug, Clone, PartialEq)]
pub struct Command {
@@ -19,33 +15,24 @@ pub struct Command {
pub template: String,
/// Expanded command with variables substituted (same as template if not expanded yet)
pub expanded: String,
- /// Phase in which this command executes
- pub phase: CommandPhase,
}
impl Command {
/// Create a new command from a template (not yet expanded)
- pub fn new(name: Option<String>, template: String, phase: CommandPhase) -> Self {
+ pub fn new(name: Option<String>, template: String) -> Self {
Self {
name,
expanded: template.clone(),
template,
- phase,
}
}
/// Create a command with both template and expanded forms
- pub fn with_expansion(
- name: Option<String>,
- template: String,
- expanded: String,
- phase: CommandPhase,
- ) -> Self {
+ pub fn with_expansion(name: Option<String>, template: String, expanded: String) -> Self {
Self {
name,
template,
expanded,
- phase,
}
}
}
@@ -72,17 +59,6 @@ impl CommandConfig {
pub fn commands(&self) -> &[Command] {
&self.commands
}
-
- /// Returns commands with the specified phase
- pub fn commands_with_phase(&self, phase: CommandPhase) -> Vec<Command> {
- self.commands
- .iter()
- .map(|cmd| Command {
- phase,
- ..cmd.clone()
- })
- .collect()
- }
}
// Custom deserialization to handle 2 TOML formats
@@ -102,14 +78,12 @@ impl<'de> Deserialize<'de> for CommandConfig {
let commands = match toml {
CommandConfigToml::Single(cmd) => {
// Phase will be set later when commands are collected
- vec![Command::new(None, cmd, CommandPhase::PostCreate)]
+ vec![Command::new(None, cmd)]
}
CommandConfigToml::Named(map) => {
// IndexMap preserves insertion order from TOML
map.into_iter()
- .map(|(name, template)| {
- Command::new(Some(name), template, CommandPhase::PostCreate)
- })
+ .map(|(name, template)| Command::new(Some(name), template))
.collect()
}
};
@@ -150,24 +124,18 @@ mod tests {
#[test]
fn test_command_new() {
- let cmd = Command::new(
- Some("build".to_string()),
- "cargo build".to_string(),
- HookType::PreMerge,
- );
+ let cmd = Command::new(Some("build".to_string()), "cargo build".to_string());
assert_eq!(cmd.name, Some("build".to_string()));
assert_eq!(cmd.template, "cargo build");
assert_eq!(cmd.expanded, "cargo build"); // Same as template when not expanded
- assert_eq!(cmd.phase, HookType::PreMerge);
}
#[test]
fn test_command_new_unnamed() {
- let cmd = Command::new(None, "npm install".to_string(), HookType::PostCreate);
+ let cmd = Command::new(None, "npm install".to_string());
assert_eq!(cmd.name, None);
assert_eq!(cmd.template, "npm install");
assert_eq!(cmd.expanded, "npm install");
- assert_eq!(cmd.phase, HookType::PostCreate);
}
#[test]
@@ -176,23 +144,10 @@ mod tests {
Some("test".to_string()),
"cargo test --package {{ repo }}".to_string(),
"cargo test --package myrepo".to_string(),
- HookType::PreMerge,
);
assert_eq!(cmd.name, Some("test".to_string()));
assert_eq!(cmd.template, "cargo test --package {{ repo }}");
assert_eq!(cmd.expanded, "cargo test --package myrepo");
- assert_eq!(cmd.phase, HookType::PreMerge);
- }
-
- #[test]
- fn test_command_clone() {
- let cmd = Command::new(
- Some("build".to_string()),
- "make".to_string(),
- HookType::PreMerge,
- );
- let cloned = cmd.clone();
- assert_eq!(cmd, cloned);
}
// ============================================================================
@@ -273,11 +228,7 @@ third = "echo 3"
let wrapper = Wrapper {
cmd: CommandConfig {
- commands: vec![Command::new(
- None,
- "npm install".to_string(),
- HookType::PostCreate,
- )],
+ commands: vec![Command::new(None, "npm install".to_string())],
},
};
@@ -296,16 +247,8 @@ third = "echo 3"
let wrapper = Wrapper {
cmd: CommandConfig {
commands: vec![
- Command::new(
- Some("build".to_string()),
- "cargo build".to_string(),
- HookType::PostCreate,
- ),
- Command::new(
- Some("test".to_string()),
- "cargo test".to_string(),
- HookType::PostCreate,
- ),
+ Command::new(Some("build".to_string()), "cargo build".to_string()),
+ Command::new(Some("test".to_string()), "cargo test".to_string()),
],
},
};
@@ -320,11 +263,7 @@ third = "echo 3"
#[test]
fn test_serialize_deserialize_roundtrip_single() {
let config = CommandConfig {
- commands: vec![Command::new(
- None,
- "echo hello".to_string(),
- HookType::PostCreate,
- )],
+ commands: vec![Command::new(None, "echo hello".to_string())],
};
#[derive(Serialize, Deserialize)]
@@ -344,16 +283,8 @@ third = "echo 3"
fn test_serialize_deserialize_roundtrip_named() {
let config = CommandConfig {
commands: vec![
- Command::new(
- Some("a".to_string()),
- "echo a".to_string(),
- HookType::PostCreate,
- ),
- Command::new(
- Some("b".to_string()),
- "echo b".to_string(),
- HookType::PostCreate,
- ),
+ Command::new(Some("a".to_string()), "echo a".to_string()),
+ Command::new(Some("b".to_string()), "echo b".to_string()),
],
};
@@ -377,8 +308,8 @@ third = "echo 3"
fn test_commands_returns_slice() {
let config = CommandConfig {
commands: vec![
- Command::new(None, "cmd1".to_string(), HookType::PostCreate),
- Command::new(None, "cmd2".to_string(), HookType::PostCreate),
+ Command::new(None, "cmd1".to_string()),
+ Command::new(None, "cmd2".to_string()),
],
};
@@ -388,40 +319,13 @@ third = "echo 3"
assert_eq!(cmds[1].template, "cmd2");
}
- #[test]
- fn test_commands_with_phase() {
- let config = CommandConfig {
- commands: vec![
- Command::new(
- Some("build".to_string()),
- "cargo build".to_string(),
- HookType::PostCreate,
- ),
- Command::new(
- Some("test".to_string()),
- "cargo test".to_string(),
- HookType::PostCreate,
- ),
- ],
- };
-
- let cmds = config.commands_with_phase(HookType::PreMerge);
-
- // All returned commands should have the new phase
- assert_eq!(cmds.len(), 2);
- assert!(cmds.iter().all(|c| c.phase == HookType::PreMerge));
- // But templates and names should be preserved
- assert_eq!(cmds[0].name, Some("build".to_string()));
- assert_eq!(cmds[0].template, "cargo build");
- }
-
#[test]
fn test_command_config_equality() {
let config1 = CommandConfig {
- commands: vec![Command::new(None, "test".to_string(), HookType::PostCreate)],
+ commands: vec![Command::new(None, "test".to_string())],
};
let config2 = CommandConfig {
- commands: vec![Command::new(None, "test".to_string(), HookType::PostCreate)],
+ commands: vec![Command::new(None, "test".to_string())],
};
assert_eq!(config1, config2);
}
diff --git a/src/config/hooks.rs b/src/config/hooks.rs
new file mode 100644
index 000000000..8251c3631
--- /dev/null
+++ b/src/config/hooks.rs
@@ -0,0 +1,75 @@
+use serde::{Deserialize, Serialize};
+
+use crate::git::HookType;
+
+use super::commands::CommandConfig;
+
+/// Shared hook configuration for user and project configs.
+#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
+pub struct HooksConfig {
+ /// Commands to execute after worktree creation (blocking)
+ #[serde(
+ default,
+ rename = "post-create",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_create: Option<CommandConfig>,
+
+ /// Commands to execute after worktree creation (background)
+ #[serde(
+ default,
+ rename = "post-start",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_start: Option<CommandConfig>,
+
+ /// Commands to execute after switching to a worktree (background)
+ #[serde(
+ default,
+ rename = "post-switch",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_switch: Option<CommandConfig>,
+
+ /// Commands to execute before committing during merge (blocking, fail-fast)
+ #[serde(
+ default,
+ rename = "pre-commit",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub pre_commit: Option<CommandConfig>,
+
+ /// Commands to execute before merging (blocking, fail-fast)
+ #[serde(default, rename = "pre-merge", skip_serializing_if = "Option::is_none")]
+ pub pre_merge: Option<CommandConfig>,
+
+ /// Commands to execute after successful merge (blocking, best-effort)
+ #[serde(
+ default,
+ rename = "post-merge",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub post_merge: Option<CommandConfig>,
+
+ /// Commands to execute before worktree removal (blocking, fail-fast)
+ #[serde(
+ default,
+ rename = "pre-remove",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub pre_remove: Option<CommandConfig>,
+}
+
+impl HooksConfig {
+ pub fn get(&self, hook: HookType) -> Option<&CommandConfig> {
+ match hook {
+ HookType::PostCreate => self.post_create.as_ref(),
+ HookType::PostStart => self.post_start.as_ref(),
+ HookType::PostSwitch => self.post_switch.as_ref(),
+ HookType::PreCommit => self.pre_commit.as_ref(),
+ HookType::PreMerge => self.pre_merge.as_ref(),
+ HookType::PostMerge => self.post_merge.as_ref(),
+ HookType::PreRemove => self.pre_remove.as_ref(),
+ }
+ }
+}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index f1a381533..c3879785e 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -17,14 +17,16 @@
mod commands;
mod expansion;
+mod hooks;
mod project;
#[cfg(test)]
mod test;
mod user;
// Re-export public types
-pub use commands::{Command, CommandConfig, CommandPhase};
+pub use commands::{Command, CommandConfig};
pub use expansion::{expand_template, sanitize_branch_name};
+pub use hooks::HooksConfig;
pub use project::{
ProjectConfig, ProjectListConfig, find_unknown_keys as find_unknown_project_keys,
};
@@ -147,23 +149,20 @@ mod tests {
#[test]
fn test_project_config_default() {
let config = ProjectConfig::default();
- assert!(config.post_create.is_none());
- assert!(config.post_start.is_none());
- assert!(config.pre_merge.is_none());
- assert!(config.post_merge.is_none());
+ assert!(config.hooks.post_create.is_none());
+ assert!(config.hooks.post_start.is_none());
+ assert!(config.hooks.pre_merge.is_none());
+ assert!(config.hooks.post_merge.is_none());
}
#[test]
fn test_command_config_single() {
let toml = r#"post-create = "npm install""#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.post_create.unwrap();
+ let cmd_config = config.hooks.post_create.unwrap();
let commands = cmd_config.commands();
assert_eq!(commands.len(), 1);
- assert_eq!(
- commands[0],
- Command::new(None, "npm install".to_string(), CommandPhase::PostCreate)
- );
+ assert_eq!(commands[0], Command::new(None, "npm install".to_string()));
}
#[test]
@@ -174,25 +173,17 @@ mod tests {
watch = "npm run watch"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.post_start.unwrap();
+ let cmd_config = config.hooks.post_start.unwrap();
let commands = cmd_config.commands();
assert_eq!(commands.len(), 2);
// Preserves TOML insertion order
assert_eq!(
commands[0],
- Command::new(
- Some("server".to_string()),
- "npm run dev".to_string(),
- CommandPhase::PostCreate
- )
+ Command::new(Some("server".to_string()), "npm run dev".to_string())
);
assert_eq!(
commands[1],
- Command::new(
- Some("watch".to_string()),
- "npm run watch".to_string(),
- CommandPhase::PostCreate
- )
+ Command::new(Some("watch".to_string()), "npm run watch".to_string())
);
}
@@ -206,7 +197,7 @@ mod tests {
clippy = "cargo clippy"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.pre_merge.unwrap();
+ let cmd_config = config.hooks.pre_merge.unwrap();
let commands = cmd_config.commands();
// Extract just the names for easier verification
@@ -236,7 +227,7 @@ task1 = "echo 'Task 1 running' > task1.txt"
task2 = "echo 'Task 2 running' > task2.txt"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.post_start.unwrap();
+ let cmd_config = config.hooks.post_start.unwrap();
let commands = cmd_config.commands();
assert_eq!(commands.len(), 2);
@@ -262,21 +253,18 @@ task2 = "echo 'Task 2 running' > task2.txt"
server = "npm run dev"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- assert!(config.post_create.is_some());
- assert!(config.post_start.is_some());
+ assert!(config.hooks.post_create.is_some());
+ assert!(config.hooks.post_start.is_some());
}
#[test]
fn test_pre_merge_command_single() {
let toml = r#"pre-merge = "cargo test""#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.pre_merge.unwrap();
+ let cmd_config = config.hooks.pre_merge.unwrap();
let commands = cmd_config.commands();
assert_eq!(commands.len(), 1);
- assert_eq!(
- commands[0],
- Command::new(None, "cargo test".to_string(), CommandPhase::PostCreate)
- );
+ assert_eq!(commands[0], Command::new(None, "cargo test".to_string()));
}
#[test]
@@ -288,7 +276,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
test = "cargo test"
"#;
let config: ProjectConfig = toml::from_str(toml).unwrap();
- let cmd_config = config.pre_merge.unwrap();
+ let cmd_config = config.hooks.pre_merge.unwrap();
let commands = cmd_config.commands();
assert_eq!(commands.len(), 3);
// Preserves TOML insertion order
@@ -296,25 +284,16 @@ task2 = "echo 'Task 2 running' > task2.txt"
commands[0],
Command::new(
Some("format".to_string()),
- "cargo fmt -- --check".to_string(),
- CommandPhase::PostCreate
+ "cargo fmt -- --check".to_string()
)
);
assert_eq!(
commands[1],
- Command::new(
- Some("lint".to_string()),
- "cargo clippy".to_string(),
- CommandPhase::PostCreate
- )
+ Command::new(Some("lint".to_string()), "cargo clippy".to_string())
);
assert_eq!(
commands[2],
- Command::new(
- Some("test".to_string()),
- "cargo test".to_string(),
- CommandPhase::PostCreate
- )
+ Command::new(Some("test".to_string()), "cargo test".to_string())
);
}
@@ -734,13 +713,16 @@ lint = "cargo clippy"
let config: WorktrunkConfig = toml::from_str(toml_str).unwrap();
// Check post-create
- let post_create = config.post_create.expect("post-create should be present");
+ let post_create = config
+ .hooks
+ .post_create
+ .expect("post-create should be present");
let commands = post_create.commands();
assert_eq!(commands.len(), 1);
assert_eq!(commands[0].name.as_deref(), Some("log"));
// Check pre-merge (multiple commands preserve order)
- let pre_merge = config.pre_merge.expect("pre-merge should be present");
+ let pre_merge = config.hooks.pre_merge.expect("pre-merge should be present");
let commands = pre_merge.commands();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].name.as_deref(), Some("test"));
@@ -755,7 +737,10 @@ post-create = "npm install"
"#;
let config: WorktrunkConfig = toml::from_str(toml_str).unwrap();
- let post_create = config.post_create.expect("post-create should be present");
+ let post_create = config
+ .hooks
+ .post_create
+ .expect("post-create should be present");
let commands = post_create.commands();
assert_eq!(commands.len(), 1);
assert!(commands[0].name.is_none()); // single command has no name
diff --git a/src/config/project.rs b/src/config/project.rs
index 55cc539c4..9f9ea6981 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -5,7 +5,7 @@
use config::ConfigError;
use serde::{Deserialize, Serialize};
-use super::commands::CommandConfig;
+use super::HooksConfig;
/// Project-level configuration for `wt list` output.
///
@@ -68,60 +68,9 @@ impl ProjectListConfig {
/// - `{{ branch | hash_port }}` - Hash string to deterministic port (10000-19999)
#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
pub struct ProjectConfig {
- /// Commands to execute sequentially before worktree is ready (blocking)
- /// Supports string (single command) or table (named, sequential)
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
- #[serde(default, rename = "post-create")]
- pub post_create: Option<CommandConfig>,
-
- /// Commands to execute in parallel as background processes (non-blocking)
- /// Supports string (single command) or table (named, parallel)
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
- #[serde(default, rename = "post-start")]
- pub post_start: Option<CommandConfig>,
-
- /// Commands to execute after switching to a worktree (non-blocking, background)
- /// Runs on every switch, including to existing worktrees and newly created ones
- /// Supports string (single command) or table (named, parallel)
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
- #[serde(default, rename = "post-switch")]
- pub post_switch: Option<CommandConfig>,
-
- /// Commands to execute before committing changes during merge (blocking, fail-fast validation)
- /// Supports string (single command) or table (named, sequential)
- /// All commands must exit with code 0 for commit to proceed
- /// Runs before any commit operation during `wt merge` (both squash and no-squash modes)
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
- #[serde(default, rename = "pre-commit")]
- pub pre_commit: Option<CommandConfig>,
-
- /// Commands to execute before merging (blocking, fail-fast validation)
- /// Supports string (single command) or table (named, sequential)
- /// All commands must exit with code 0 for merge to proceed
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
- #[serde(default, rename = "pre-merge")]
- pub pre_merge: Option<CommandConfig>,
-
- /// Commands to execute after successful merge in the main worktree (blocking)
- /// Supports string (single command) or table (named, sequential)
- /// Runs after push and cleanup complete
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`, `{{ target }}`
- #[serde(default, rename = "post-merge")]
- pub post_merge: Option<CommandConfig>,
-
- /// Commands to execute before a worktree is removed (blocking)
- /// Supports string (single command) or table (named, sequential)
- /// Runs in the worktree before removal; non-zero exit aborts removal
- ///
- /// Available template variables: `{{ repo }}`, `{{ branch }}`, `{{ worktree }}`, `{{ worktree_name }}`, `{{ repo_root }}`, `{{ default_branch }}`, `{{ commit }}`, `{{ short_commit }}`, `{{ remote }}`, `{{ upstream }}`
- #[serde(default, rename = "pre-remove")]
- pub pre_remove: Option<CommandConfig>,
+ /// Project hooks (same keys as user hooks, flattened at top level)
+ #[serde(flatten, default)]
+ pub hooks: HooksConfig,
/// Configuration for `wt list` output
#[serde(default)]
@@ -176,13 +125,13 @@ mod tests {
#[test]
fn test_project_config_default() {
let config = ProjectConfig::default();
- assert!(config.post_create.is_none());
- assert!(config.post_start.is_none());
- assert!(config.post_switch.is_none());
- assert!(config.pre_commit.is_none());
- assert!(config.pre_merge.is_none());
- assert!(config.post_merge.is_none());
- assert!(config.pre_remove.is_none());
+ assert!(config.hooks.post_create.is_none());
+ assert!(config.hooks.post_start.is_none());
+ assert!(config.hooks.post_switch.is_none());
+ assert!(config.hooks.pre_commit.is_none());
+ assert!(config.hooks.pre_merge.is_none());
+ assert!(config.hooks.post_merge.is_none());
+ assert!(config.hooks.pre_remove.is_none());
assert!(config.list.is_none());
}
@@ -194,15 +143,15 @@ mod tests {
fn test_deserialize_empty_config() {
let contents = "";
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.post_create.is_none());
- assert!(config.pre_merge.is_none());
+ assert!(config.hooks.post_create.is_none());
+ assert!(config.hooks.pre_merge.is_none());
}
#[test]
fn test_deserialize_post_create_string() {
let contents = r#"post-create = "npm install""#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.post_create.is_some());
+ assert!(config.hooks.post_create.is_some());
}
#[test]
@@ -213,35 +162,35 @@ build = "cargo build"
test = "cargo test"
"#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.post_start.is_some());
+ assert!(config.hooks.post_start.is_some());
}
#[test]
fn test_deserialize_pre_merge() {
let contents = r#"pre-merge = "cargo test""#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.pre_merge.is_some());
+ assert!(config.hooks.pre_merge.is_some());
}
#[test]
fn test_deserialize_post_merge() {
let contents = r#"post-merge = "git push origin main""#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.post_merge.is_some());
+ assert!(config.hooks.post_merge.is_some());
}
#[test]
fn test_deserialize_pre_remove() {
let contents = r#"pre-remove = "echo cleaning up""#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.pre_remove.is_some());
+ assert!(config.hooks.pre_remove.is_some());
}
#[test]
fn test_deserialize_pre_commit() {
let contents = r#"pre-commit = "cargo fmt --check""#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.pre_commit.is_some());
+ assert!(config.hooks.pre_commit.is_some());
}
#[test]
@@ -256,13 +205,13 @@ post-merge = "git push"
pre-remove = "echo bye"
"#;
let config: ProjectConfig = toml::from_str(contents).unwrap();
- assert!(config.post_create.is_some());
- assert!(config.post_start.is_some());
- assert!(config.post_switch.is_some());
- assert!(config.pre_commit.is_some());
- assert!(config.pre_merge.is_some());
- assert!(config.post_merge.is_some());
- assert!(config.pre_remove.is_some());
+ assert!(config.hooks.post_create.is_some());
+ assert!(config.hooks.post_start.is_some());
+ assert!(config.hooks.post_switch.is_some());
+ assert!(config.hooks.pre_commit.is_some());
+ assert!(config.hooks.pre_merge.is_some());
+ assert!(config.hooks.post_merge.is_some());
+ assert!(config.hooks.pre_remove.is_some());
}
// ============================================================================
diff --git a/src/config/user.rs b/src/config/user.rs
index 44ca5c512..544f61306 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -7,7 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize};
use std::path::PathBuf;
use std::sync::OnceLock;
-use super::commands::CommandConfig;
+use super::HooksConfig;
/// Deserialize a Vec<String> that can also accept a single String
/// This enables setting array config fields via environment variables
@@ -152,57 +152,8 @@ pub struct WorktrunkConfig {
// =========================================================================
// User-level hooks (same syntax as project hooks, run before project hooks)
// =========================================================================
- /// Commands to execute after worktree creation (blocking)
- #[serde(
- default,
- rename = "post-create",
- skip_serializing_if = "Option::is_none"
- )]
- pub post_create: Option<CommandConfig>,
-
- /// Commands to execute after worktree creation (background)
- #[serde(
- default,
- rename = "post-start",
- skip_serializing_if = "Option::is_none"
- )]
- pub post_start: Option<CommandConfig>,
-
- /// Commands to execute after switching to a worktree (background)
- #[serde(
- default,
- rename = "post-switch",
- skip_serializing_if = "Option::is_none"
- )]
- pub post_switch: Option<CommandConfig>,
-
- /// Commands to execute before committing during merge (blocking, fail-fast)
- #[serde(
- default,
- rename = "pre-commit",
- skip_serializing_if = "Option::is_none"
- )]
- pub pre_commit: Option<CommandConfig>,
-
- /// Commands to execute before merging (blocking, fail-fast)
- #[serde(default, rename = "pre-merge", skip_serializing_if = "Option::is_none")]
- pub pre_merge: Option<CommandConfig>,
-
- /// Commands to execute after successful merge (blocking, best-effort)
- #[serde(
- default,
- rename = "post-merge",
- skip_serializing_if = "Option::is_none"
- )]
- pub post_merge: Option<CommandConfig>,
-
- /// Commands to execute before worktree removal (blocking, fail-fast)
- #[serde(
- default,
- rename = "pre-remove",
- skip_serializing_if = "Option::is_none"
- )]
- pub pre_remove: Option<CommandConfig>,
+ #[serde(flatten, default)]
+ pub hooks: HooksConfig,
/// Captures unknown fields for validation warnings
#[serde(flatten, default, skip_serializing)]
@@ -348,13 +299,7 @@ impl Default for WorktrunkConfig {
list: None,
commit: None,
merge: None,
- post_create: None,
- post_start: None,
- post_switch: None,
- pre_commit: None,
- pre_merge: None,
- post_merge: None,
- pre_remove: None,
+ hooks: HooksConfig::default(),
unknown: std::collections::HashMap::new(),
}
}