Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: use CommandPhase for command approval and development
Maximilian Roos1d9a6bc49763
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 26645c2cf..c30707da2 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -19,7 +19,6 @@ pub fn approve_command_batch(project_id: &str,config: &WorktrunkConfig,force: bool,- context: &str,) -> Result<bool, GitError> {let needs_approval: Vec<&Command> = commands.iter()@@ -33,12 +32,23 @@ pub fn approve_command_batch(let approved = if force {true} else {- prompt_for_batch_approval(&needs_approval, project_id, context)?+ prompt_for_batch_approval(&needs_approval, project_id)?};if !approved {let dim = AnstyleStyle::new().dimmed();- println!("{INFO_EMOJI} {dim}{context} declined{dim:#}");+ // Derive phase from commands - if all same phase, show it; otherwise show generic message+ let phase_str = if commands.len() == 1 {+ commands[0].phase.to_string()+ } else {+ let first_phase = commands[0].phase;+ if commands.iter().all(|cmd| cmd.phase == first_phase) {+ first_phase.to_string()+ } else {+ "commands".to_string()+ }+ };+ println!("{INFO_EMOJI} {dim}{phase_str} declined{dim:#}");return Ok(false);}@@ -72,11 +82,7 @@ fn log_approval_warning(message: &str, error: impl std::fmt::Display) {println!("{WARNING_EMOJI} {WARNING}{message}: {error}{WARNING:#}");}-fn prompt_for_batch_approval(- commands: &[&Command],- project_id: &str,- context: &str,-) -> std::io::Result<bool> {+fn prompt_for_batch_approval(commands: &[&Command], project_id: &str) -> std::io::Result<bool> {use std::io::{self, Write};let project_name = project_id.split('/').next_back().unwrap_or(project_id);@@ -97,11 +103,12 @@ fn prompt_for_batch_approval(eprintln!();for cmd in commands {- // Format as: {context} {bold}{name}{bold:#}:- // context is provided by caller in lowercase (e.g., "post-create", "pre-merge")+ // Format as: {phase} {bold}{name}{bold:#}:+ // Phase comes from the command itself (e.g., "pre-commit", "pre-merge")+ let phase = cmd.phase.to_string();let label = match &cmd.name {- Some(name) => format!("{PROGRESS_EMOJI} {context} {bold}{name}{bold:#}:"),- None => format!("{PROGRESS_EMOJI} {context}:"),+ Some(name) => format!("{PROGRESS_EMOJI} {phase} {bold}{name}{bold:#}:"),+ None => format!("{PROGRESS_EMOJI} {phase}:"),};eprintln!("{label}");eprint!("{}", format_bash_with_gutter(&cmd.expanded, ""));diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex af708d4c8..9ba2ec5ab 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,6 +1,6 @@use std::collections::HashMap;use std::path::Path;-use worktrunk::config::{Command, CommandConfig, WorktrunkConfig, expand_template};+use worktrunk::config::{Command, CommandConfig, CommandPhase, WorktrunkConfig, expand_template};use worktrunk::git::{GitError, Repository};use super::command_approval::approve_command_batch;@@ -45,11 +45,10 @@ impl<'a> CommandContext<'a> {/// This is the canonical command expansion implementation./// Returns cloned commands with their expanded forms filled in.fn expand_commands(- command_config: &CommandConfig,+ commands: &[Command],ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],) -> Result<Vec<Command>, GitError> {- let commands = command_config.commands();if commands.is_empty() {return Ok(Vec::new());}@@ -87,6 +86,7 @@ fn expand_commands(cmd.name.clone(),cmd.template.clone(),expanded_str,+ cmd.phase,));}@@ -106,9 +106,9 @@ pub fn prepare_project_commands(ctx: &CommandContext<'_>,auto_trust: bool,extra_vars: &[(&str, &str)],- approval_context: &str,+ phase: CommandPhase,) -> Result<Vec<PreparedCommand>, GitError> {- let commands = command_config.commands();+ let commands = command_config.commands_with_phase(phase);if commands.is_empty() {return Ok(Vec::new());}@@ -116,17 +116,11 @@ pub fn prepare_project_commands(let project_id = ctx.repo.project_identifier()?;// Expand commands before approval for transparency- let expanded_commands = expand_commands(command_config, ctx, extra_vars)?;+ let expanded_commands = expand_commands(&commands, ctx, extra_vars)?;// Approve using expanded commands (which have both template and expanded forms)if !auto_trust- && !approve_command_batch(- &expanded_commands,- &project_id,- ctx.config,- ctx.force,- approval_context,- )?+ && !approve_command_batch(&expanded_commands, &project_id, ctx.config, ctx.force)?{return Err(GitError::CommandNotApproved);}diff --git a/src/commands/dev.rs b/src/commands/dev.rsindex 3ab796969..105b93df6 100644--- a/src/commands/dev.rs+++ b/src/commands/dev.rs@@ -384,7 +384,7 @@ pub fn handle_dev_rebase(target: Option<&str>) -> Result<bool, GitError> {/// Handle `wt dev ask-approval` command - test the approval prompt UIpub fn handle_dev_ask_approval(force: bool) -> Result<(), GitError> {use super::command_approval::approve_command_batch;- use worktrunk::config::{Command, WorktrunkConfig};+ use worktrunk::config::{Command, CommandPhase, WorktrunkConfig};// Create some test commands to show in the approval promptlet test_commands = vec![@@ -392,16 +392,19 @@ pub fn handle_dev_ask_approval(force: bool) -> Result<(), GitError> {Some("insta".to_string()),"NEXTEST_STATUS_LEVEL=fail cargo insta test".to_string(),"NEXTEST_STATUS_LEVEL=fail cargo insta test --test-runner nextest".to_string(),+ CommandPhase::PreMerge,),Command::with_expansion(Some("doc".to_string()),"RUSTDOCFLAGS='-Dwarnings' cargo doc --no-deps".to_string(),"RUSTDOCFLAGS='-Dwarnings' cargo doc --no-deps".to_string(),+ CommandPhase::PreMerge,),Command::with_expansion(None,"cargo install --path .".to_string(),"cargo install --path .".to_string(),+ CommandPhase::PostMerge,),];@@ -410,7 +413,7 @@ pub fn handle_dev_ask_approval(force: bool) -> Result<(), GitError> {let config = WorktrunkConfig::load().git_context("Failed to load config")?;// Call the approval prompt- let approved = approve_command_batch(&test_commands, &project_id, &config, force, "test")?;+ let approved = approve_command_batch(&test_commands, &project_id, &config, force)?;// Show resultif approved {diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex bcf10bd87..71001bcfc 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,5 +1,5 @@use worktrunk::HookType;-use worktrunk::config::{Command, ProjectConfig, WorktrunkConfig};+use worktrunk::config::{Command, CommandPhase, ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{AnstyleStyle, CYAN, CYAN_BOLD, ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, WARNING, WARNING_EMOJI,@@ -46,19 +46,19 @@ impl<'a> MergeCommandCollector<'a> {&& !self.squash_enabled&& let Some(pre_commit_config) = &project_config.pre_commit_command{- all_commands.extend(pre_commit_config.commands().to_vec());+ all_commands.extend(pre_commit_config.commands_with_phase(CommandPhase::PreCommit));}// Collect pre-merge commands (if not --no-verify)if !self.no_verify&& let Some(pre_merge_config) = &project_config.pre_merge_command{- all_commands.extend(pre_merge_config.commands().to_vec());+ all_commands.extend(pre_merge_config.commands_with_phase(CommandPhase::PreMerge));}// Collect post-merge commandsif let Some(post_merge_config) = &project_config.post_merge_command {- all_commands.extend(post_merge_config.commands().to_vec());+ all_commands.extend(post_merge_config.commands_with_phase(CommandPhase::PostMerge));}let project_id = self.repo.project_identifier()?;@@ -158,7 +158,7 @@ pub fn handle_merge(// Approve all commands in a single batch// Commands collected here are not yet expanded - expansion happens later in prepare_project_commands- approve_command_batch(&all_commands, &project_id, &config, force, "merge")?;+ approve_command_batch(&all_commands, &project_id, &config, force)?;// Handle uncommitted changes (skip if --no-commit) - track whether commit occurredlet committed = if !no_commit && repo.is_dirty()? {@@ -503,7 +503,7 @@ pub fn run_pre_merge_commands(&ctx,false,&[("target", target_branch)],- "pre-merge",+ CommandPhase::PreMerge,)?;for prepared in commands {let label = crate::commands::format_command_label("pre-merge", prepared.name.as_deref());@@ -566,7 +566,7 @@ pub fn execute_post_merge_commands(&ctx,false,&[("target", target_branch)],- "post-merge",+ CommandPhase::PostMerge,)?;if commands.is_empty() {@@ -629,8 +629,13 @@ pub fn run_pre_commit_commands(vec![]};- let commands =- prepare_project_commands(pre_commit_config, &ctx, false, &extra_vars, "pre-commit")?;+ let commands = prepare_project_commands(+ pre_commit_config,+ &ctx,+ false,+ &extra_vars,+ CommandPhase::PreCommit,+ )?;if commands.is_empty() {return Ok(());diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex e15053148..9edb97f39 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -101,7 +101,7 @@//! See also: DEMO.md for detailed architecture explanation.use std::path::PathBuf;-use worktrunk::config::{ProjectConfig, WorktrunkConfig};+use worktrunk::config::{CommandPhase, ProjectConfig, WorktrunkConfig};use worktrunk::git::{GitError, GitResultExt, Repository};use worktrunk::styling::{ADDITION, CYAN, CYAN_BOLD, DELETION, GREEN, GREEN_BOLD, SUCCESS_EMOJI, WARNING, WARNING_EMOJI,@@ -473,7 +473,13 @@ pub fn execute_post_create_commands(let repo_root = repo.worktree_base()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(post_create_config, &ctx, false, &[], "post-create")?;+ let commands = prepare_project_commands(+ post_create_config,+ &ctx,+ false,+ &[],+ CommandPhase::PostCreate,+ )?;if commands.is_empty() {return Ok(());@@ -522,7 +528,8 @@ pub fn spawn_post_start_commands(let repo_root = repo.worktree_base()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(post_start_config, &ctx, false, &[], "post-start")?;+ let commands =+ prepare_project_commands(post_start_config, &ctx, false, &[], CommandPhase::PostStart)?;if commands.is_empty() {return Ok(());@@ -578,7 +585,8 @@ pub fn execute_post_start_commands_sequential(let repo_root = repo.worktree_base()?;let ctx = CommandContext::new(repo, config, branch, worktree_path, &repo_root, force);- let commands = prepare_project_commands(post_start_config, &ctx, false, &[], "post-start")?;+ let commands =+ prepare_project_commands(post_start_config, &ctx, false, &[], CommandPhase::PostStart)?;if commands.is_empty() {return Ok(());diff --git a/src/config/mod.rs b/src/config/mod.rsindex 9eef0026c..d420d7532 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -200,6 +200,22 @@ pub struct ProjectConfig {pub post_merge_command: Option<CommandConfig>,}+/// Phase in which a command executes+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::AsRefStr)]+#[strum(serialize_all = "kebab-case")]+pub enum CommandPhase {+ /// After creating a worktree (blocking)+ PostCreate,+ /// After creating a worktree (background)+ PostStart,+ /// Before committing during merge (blocking, fail-fast)+ PreCommit,+ /// Before merging (blocking, fail-fast)+ PreMerge,+ /// After successful merge (blocking)+ PostMerge,+}+/// Represents a command with its template and optionally expanded form#[derive(Debug, Clone, PartialEq)]pub struct Command {@@ -209,24 +225,33 @@ 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) -> Self {+ pub fn new(name: Option<String>, template: String, phase: CommandPhase) -> 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) -> Self {+ pub fn with_expansion(+ name: Option<String>,+ template: String,+ expanded: String,+ phase: CommandPhase,+ ) -> Self {Self {name,template,expanded,+ phase,}}}@@ -254,6 +279,17 @@ 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 3 TOML formats@@ -272,15 +308,20 @@ impl<'de> Deserialize<'de> for CommandConfig {let toml = CommandConfigToml::deserialize(deserializer)?;let commands = match toml {- CommandConfigToml::Single(cmd) => vec![Command::new(None, cmd)],+ CommandConfigToml::Single(cmd) => {+ // Phase will be set later when commands are collected+ vec![Command::new(None, cmd, CommandPhase::PostCreate)]+ }CommandConfigToml::Multiple(cmds) => cmds.into_iter()- .map(|template| Command::new(None, template))+ .map(|template| Command::new(None, template, CommandPhase::PostCreate)).collect(),CommandConfigToml::Named(map) => {// IndexMap preserves insertion order from TOMLmap.into_iter()- .map(|(name, template)| Command::new(Some(name), template))+ .map(|(name, template)| {+ Command::new(Some(name), template, CommandPhase::PostCreate)+ }).collect()}};@@ -868,7 +909,10 @@ mod tests {let cmd_config = config.post_create_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 1);- assert_eq!(commands[0], Command::new(None, "npm install".to_string()));+ assert_eq!(+ commands[0],+ Command::new(None, "npm install".to_string(), CommandPhase::PostCreate)+ );}#[test]@@ -878,8 +922,14 @@ mod tests {let cmd_config = config.post_create_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 2);- assert_eq!(commands[0], Command::new(None, "npm install".to_string()));- assert_eq!(commands[1], Command::new(None, "npm test".to_string()));+ assert_eq!(+ commands[0],+ Command::new(None, "npm install".to_string(), CommandPhase::PostCreate)+ );+ assert_eq!(+ commands[1],+ Command::new(None, "npm test".to_string(), CommandPhase::PostCreate)+ );}#[test]@@ -896,11 +946,19 @@ mod tests {// Preserves TOML insertion orderassert_eq!(commands[0],- Command::new(Some("server".to_string()), "npm run dev".to_string())+ Command::new(+ Some("server".to_string()),+ "npm run dev".to_string(),+ CommandPhase::PostCreate+ ));assert_eq!(commands[1],- Command::new(Some("watch".to_string()), "npm run watch".to_string())+ Command::new(+ Some("watch".to_string()),+ "npm run watch".to_string(),+ CommandPhase::PostCreate+ ));}@@ -981,7 +1039,10 @@ task2 = "echo 'Task 2 running' > task2.txt"let cmd_config = config.pre_merge_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 1);- assert_eq!(commands[0], Command::new(None, "cargo test".to_string()));+ assert_eq!(+ commands[0],+ Command::new(None, "cargo test".to_string(), CommandPhase::PostCreate)+ );}#[test]@@ -993,9 +1054,16 @@ task2 = "echo 'Task 2 running' > task2.txt"assert_eq!(commands.len(), 2);assert_eq!(commands[0],- Command::new(None, "cargo fmt -- --check".to_string())+ Command::new(+ None,+ "cargo fmt -- --check".to_string(),+ CommandPhase::PostCreate+ )+ );+ assert_eq!(+ commands[1],+ Command::new(None, "cargo test".to_string(), CommandPhase::PostCreate));- assert_eq!(commands[1], Command::new(None, "cargo test".to_string()));}#[test]@@ -1015,16 +1083,25 @@ task2 = "echo 'Task 2 running' > task2.txt"commands[0],Command::new(Some("format".to_string()),- "cargo fmt -- --check".to_string()+ "cargo fmt -- --check".to_string(),+ CommandPhase::PostCreate));assert_eq!(commands[1],- Command::new(Some("lint".to_string()), "cargo clippy".to_string())+ Command::new(+ Some("lint".to_string()),+ "cargo clippy".to_string(),+ CommandPhase::PostCreate+ ));assert_eq!(commands[2],- Command::new(Some("test".to_string()), "cargo test".to_string())+ Command::new(+ Some("test".to_string()),+ "cargo test".to_string(),+ CommandPhase::PostCreate+ ));}