Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Add `post-create` and `post-start` commands
Maximilian Roos946937c39954
diff --git a/Cargo.lock b/Cargo.lockindex c7a96a50d..5d2b8e3a5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11,6 +11,15 @@ dependencies = ["memchr",]+[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]+[[package]]name = "anes"version = "0.1.6"@@ -196,12 +205,35 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"+[[package]]+name = "cc"+version = "1.2.41"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac9fe6cdbb24b6ade63616c0a0688e45bb56732262c158df3c0c4bea4ca47cb7"+dependencies = [+ "find-msvc-tools",+ "shlex",+]+[[package]]name = "cfg-if"version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"+[[package]]+name = "chrono"+version = "0.4.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"+dependencies = [+ "iana-time-zone",+ "js-sys",+ "num-traits",+ "wasm-bindgen",+ "windows-link",+]+[[package]]name = "ciborium"version = "0.2.2"@@ -345,6 +377,12 @@ dependencies = ["unicode-segmentation",]+[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -609,6 +647,12 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"+[[package]]+name = "find-msvc-tools"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127"+[[package]]name = "fnv"version = "1.0.7"@@ -750,6 +794,30 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "iana-time-zone"+version = "0.1.64"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]+[[package]]name = "ident_case"version = "1.0.1"@@ -1334,6 +1402,18 @@ dependencies = ["digest",]+[[package]]+name = "shell-escape"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f"++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]name = "similar"version = "2.7.0"@@ -1713,12 +1793,65 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"+[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]+[[package]]name = "windows-sys"version = "0.59.0"@@ -1898,6 +2031,7 @@ dependencies = ["anstyle","askama","assert_cmd",+ "chrono","clap","clap_complete","config",@@ -1910,6 +2044,7 @@ dependencies = ["rstest","serde","serde_json",+ "shell-escape","tempfile","terminal_size","toml",diff --git a/Cargo.toml b/Cargo.tomlindex 01339369e..bd6c56212 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -20,6 +20,7 @@ path = "src/main.rs"anstream = "0.6"anstyle = "1.0"askama = { version = "0.14", default-features = false, features = ["derive", "std"] }+chrono = "0.4"clap = { version = "4.5", features = ["derive"] }clap_complete = "4.5"config = "0.15"@@ -27,6 +28,7 @@ directories = "6.0"rayon = "1.11"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"+shell-escape = "0.1"terminal_size = "0.4"toml = "0.9"unicode-width = "0.2"diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex a7c0623af..eb1a6c146 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -3,6 +3,7 @@ pub mod configure_shell;pub mod init;pub mod list;pub mod merge;+pub mod process;pub mod worktree;pub use completion::{handle_complete, handle_completion};diff --git a/src/commands/process.rs b/src/commands/process.rsnew file mode 100644index 000000000..1cec3a52f--- /dev/null+++ b/src/commands/process.rs@@ -0,0 +1,123 @@+use std::fs;+use std::path::Path;+use std::process::{Command, Stdio};+use worktrunk::git::GitError;++/// Spawn a detached background process with output redirected to a log file+///+/// The process will be fully detached from the parent:+/// - On Unix: uses double-fork with setsid to create a daemon+/// - On Windows: uses CREATE_NEW_PROCESS_GROUP to detach from console+///+/// # Arguments+/// * `worktree_path` - Working directory for the command+/// * `command` - Shell command to execute+/// * `name` - Name identifier for the process (used in log filename)+///+/// # Returns+/// Path to the log file where output is being written+pub fn spawn_detached(+ worktree_path: &Path,+ command: &str,+ name: &str,+) -> Result<std::path::PathBuf, GitError> {+ // Resolve the actual .git directory path+ // In a worktree, .git is a file pointing to the real git directory+ let git_path = worktree_path.join(".git");+ let git_dir = if git_path.is_file() {+ // Read the gitdir path from the file+ let content = fs::read_to_string(&git_path)+ .map_err(|e| GitError::CommandFailed(format!("Failed to read .git file: {}", e)))?;+ // Format is "gitdir: /path/to/git/dir"+ let gitdir_path = content+ .trim()+ .strip_prefix("gitdir: ")+ .ok_or_else(|| GitError::CommandFailed("Invalid .git file format".to_string()))?;+ Path::new(gitdir_path).to_path_buf()+ } else {+ git_path+ };++ // Create log directory in the git directory+ let log_dir = git_dir.join("wt-logs");+ fs::create_dir_all(&log_dir)+ .map_err(|e| GitError::CommandFailed(format!("Failed to create log directory: {}", e)))?;++ // Generate log filename with timestamp+ let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S");+ let log_path = log_dir.join(format!("post-start-{}-{}.log", name, timestamp));++ // Create log file+ let log_file = fs::File::create(&log_path)+ .map_err(|e| GitError::CommandFailed(format!("Failed to create log file: {}", e)))?;++ #[cfg(unix)]+ {+ spawn_detached_unix(worktree_path, command, log_file)?;+ }++ #[cfg(windows)]+ {+ spawn_detached_windows(worktree_path, command, log_file)?;+ }++ Ok(log_path)+}++#[cfg(unix)]+fn spawn_detached_unix(+ worktree_path: &Path,+ command: &str,+ log_file: fs::File,+) -> Result<(), GitError> {+ // Detachment using nohup and background execution (&):+ // - nohup makes the process immune to SIGHUP (continues after parent exits)+ // - sh -c allows complex shell commands with pipes, redirects, etc.+ // - & backgrounds the process immediately+ // - Parent process doesn't wait, allowing immediate return+ // - Output redirected to log file for debugging+ Command::new("sh")+ .arg("-c")+ .arg(format!(+ "nohup sh -c {} &",+ shell_escape::escape(command.into())+ ))+ .current_dir(worktree_path)+ .stdin(Stdio::null())+ .stdout(Stdio::from(log_file.try_clone().map_err(|e| {+ GitError::CommandFailed(format!("Failed to clone log file handle: {}", e))+ })?))+ .stderr(Stdio::from(log_file))+ .spawn()+ .map_err(|e| GitError::CommandFailed(format!("Failed to spawn detached process: {}", e)))?;++ Ok(())+}++#[cfg(windows)]+fn spawn_detached_windows(+ worktree_path: &Path,+ command: &str,+ log_file: fs::File,+) -> Result<(), GitError> {+ use std::os::windows::process::CommandExt;++ // CREATE_NEW_PROCESS_GROUP: Creates new process group (0x00000200)+ // DETACHED_PROCESS: Creates process without console (0x00000008)+ const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200;+ const DETACHED_PROCESS: u32 = 0x00000008;++ Command::new("cmd")+ .args(["/C", command])+ .current_dir(worktree_path)+ .stdin(Stdio::null())+ .stdout(Stdio::from(log_file.try_clone().map_err(|e| {+ GitError::CommandFailed(format!("Failed to clone log file handle: {}", e))+ })?))+ .stderr(Stdio::from(log_file))+ .creation_flags(CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS)+ .spawn()+ .map_err(|e| GitError::CommandFailed(format!("Failed to spawn detached process: {}", e)))?;++ Ok(())+}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 4d99e4639..0bd4fab1e 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -109,6 +109,7 @@ use worktrunk::styling::{AnstyleStyle, ERROR, ERROR_EMOJI, HINT, HINT_EMOJI, WARNING, WARNING_EMOJI, eprintln, println,};+use crate::commands::process::spawn_detached;use crate::output::execute_command_in_worktree;/// Result of a worktree switch operation@@ -217,8 +218,11 @@ pub fn handle_switch(.canonicalize().unwrap_or_else(|_| worktree_path.clone());- // Execute post-start commands from project config- execute_post_start_commands(&canonical_path, &repo, config, branch, repo_name, force)?;+ // Execute post-create commands (sequential, blocking)+ execute_post_create_commands(&canonical_path, &repo, config, branch, repo_name, force)?;++ // Spawn post-start commands (parallel, background)+ spawn_post_start_commands(&canonical_path, &repo, config, branch, repo_name, force)?;Ok(SwitchResult::CreatedWorktree {path: canonical_path,@@ -378,21 +382,12 @@ fn prompt_for_approval(command: &str, project_id: &str) -> io::Result<bool> {Ok(response == "y" || response == "yes")}-/// Execute post-start commands from project config-fn execute_post_start_commands(- worktree_path: &std::path::Path,- repo: &Repository,- config: &WorktrunkConfig,- branch: &str,- repo_name: &str,- force: bool,-) -> Result<(), GitError> {- // Load project config+/// Helper to load project config with error handling+fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {let repo_root = repo.repo_root()?;let config_path = repo_root.join(".config").join("wt.toml");- let project_config = match ProjectConfig::load(&repo_root) {- Ok(Some(cfg)) => cfg,- Ok(None) => return Ok(()), // No project config+ match ProjectConfig::load(&repo_root) {+ Ok(cfg) => Ok(cfg),Err(e) => {eprintln!("{WARNING_EMOJI} {WARNING}Failed to load project config from {}{WARNING:#}",@@ -400,80 +395,148 @@ fn execute_post_start_commands();eprintln!("{HINT_EMOJI} {HINT}Error details: {e}{HINT:#}");eprintln!(- "{HINT_EMOJI} {HINT}Skipping post-start commands. Check TOML syntax if file exists.{HINT:#}"+ "{HINT_EMOJI} {HINT}Skipping commands. Check TOML syntax if file exists.{HINT:#}");- return Ok(());+ Ok(None)+ }+ }+}++/// Convert CommandConfig to a vector of (name, command) pairs+fn command_config_to_vec(config: &worktrunk::config::CommandConfig) -> Vec<(String, String)> {+ use worktrunk::config::CommandConfig;+ match config {+ CommandConfig::Single(cmd) => vec![("default".to_string(), cmd.clone())],+ CommandConfig::Multiple(cmds) => cmds+ .iter()+ .enumerate()+ .map(|(i, cmd)| (format!("cmd-{}", i), cmd.clone()))+ .collect(),+ CommandConfig::Named(map) => {+ let mut pairs: Vec<_> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();+ // Sort by name for deterministic iteration order+ pairs.sort_by(|a, b| a.0.cmp(&b.0));+ pairs}+ }+}++/// Execute post-create commands sequentially (blocking)+fn execute_post_create_commands(+ worktree_path: &std::path::Path,+ repo: &Repository,+ config: &WorktrunkConfig,+ branch: &str,+ repo_name: &str,+ force: bool,+) -> Result<(), GitError> {+ let project_config = match load_project_config(repo)? {+ Some(cfg) => cfg,+ None => return Ok(()),};- if project_config.post_start_commands.is_empty() {+ let Some(post_create_config) = &project_config.post_create_command else {+ return Ok(());+ };++ let commands = command_config_to_vec(post_create_config);+ if commands.is_empty() {return Ok(());}- // Get project identifierlet project_id = repo.project_identifier()?;+ let repo_root = repo.repo_root()?;- // Execute each command- for command in &project_config.post_start_commands {- // Check if command is already approved or if force flag is set- let approved = if force || config.is_command_approved(&project_id, command) {- true- } else {- // Prompt for approval- match prompt_for_approval(command, &project_id) {- Ok(true) => {- // Reload config and save approval- match WorktrunkConfig::load() {- Ok(mut fresh_config) => {- if let Err(e) =- fresh_config.approve_command(project_id.clone(), command.clone())- {- eprintln!(- "{WARNING_EMOJI} {WARNING}Failed to save command approval: {e}{WARNING:#}"- );- eprintln!("You will be prompted again next time.");- }- }- Err(e) => {- eprintln!(- "{WARNING_EMOJI} {WARNING}Failed to reload config for saving approval: {e}{WARNING:#}"- );- eprintln!("You will be prompted again next time.");- }- }- true- }- Ok(false) => {- let dim = AnstyleStyle::new().dimmed();- eprintln!("{dim}Skipping command: {command}{dim:#}");- false- }- Err(e) => {- eprintln!("{WARNING_EMOJI} {WARNING}Failed to read user input: {e}{WARNING:#}");- false- }- }- };+ // Execute each command sequentially+ for (name, command) in commands {+ if !check_and_approve_command(&project_id, &command, config, force)? {+ let dim = AnstyleStyle::new().dimmed();+ eprintln!("{dim}Skipping command: {command}{dim:#}");+ continue;+ }++ let expanded_command =+ expand_command_template(&command, repo_name, branch, worktree_path, &repo_root);- if approved {- // Expand template variables in the command- let expanded_command =- expand_command_template(command, repo_name, branch, worktree_path, &repo_root);-- use anstyle::{AnsiColor, Color};- use std::io::Write;- let cyan = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));- eprintln!("π {cyan}Executing: {expanded_command}{cyan:#}");- // Flush stderr to ensure message is displayed before command execution- let _ = std::io::stderr().flush();- if let Err(e) = execute_command_in_worktree(worktree_path, &expanded_command) {- eprintln!("{WARNING_EMOJI} {WARNING}Command failed: {e}{WARNING:#}");- // Continue with other commands even if one fails+ use anstyle::{AnsiColor, Color};+ use std::io::Write;+ let cyan = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));+ eprintln!("π {cyan}Executing (post-create): {expanded_command}{cyan:#}");+ let _ = std::io::stderr().flush();++ if let Err(e) = execute_command_in_worktree(worktree_path, &expanded_command) {+ eprintln!("{WARNING_EMOJI} {WARNING}Command '{name}' failed: {e}{WARNING:#}");+ // Continue with other commands even if one fails+ }+ }++ use std::io::Write;+ let _ = std::io::stdout().flush();+ let _ = std::io::stderr().flush();++ Ok(())+}++/// Spawn post-start commands in parallel as background processes (non-blocking)+fn spawn_post_start_commands(+ worktree_path: &std::path::Path,+ repo: &Repository,+ config: &WorktrunkConfig,+ branch: &str,+ repo_name: &str,+ force: bool,+) -> Result<(), GitError> {+ let project_config = match load_project_config(repo)? {+ Some(cfg) => cfg,+ None => return Ok(()),+ };++ let Some(post_start_config) = &project_config.post_start_command else {+ return Ok(());+ };++ let commands = command_config_to_vec(post_start_config);+ if commands.is_empty() {+ return Ok(());+ }++ let project_id = repo.project_identifier()?;+ let repo_root = repo.repo_root()?;++ // Spawn each command as a detached background process+ for (name, command) in commands {+ if !check_and_approve_command(&project_id, &command, config, force)? {+ let dim = AnstyleStyle::new().dimmed();+ eprintln!("{dim}Skipping command: {command}{dim:#}");+ continue;+ }++ let expanded_command =+ expand_command_template(&command, repo_name, branch, worktree_path, &repo_root);++ use anstyle::{AnsiColor, Color};+ use std::io::Write;+ let cyan = AnstyleStyle::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)));+ eprintln!("π {cyan}Starting (background): {expanded_command}{cyan:#}");+ let _ = std::io::stderr().flush();++ match spawn_detached(worktree_path, &expanded_command, &name) {+ Ok(log_path) => {+ let dim = AnstyleStyle::new().dimmed();+ // Show relative path from worktree/.git/wt-logs/+ let display_path = if let Some(filename) = log_path.file_name() {+ format!(".git/wt-logs/{}", filename.to_string_lossy())+ } else {+ log_path.display().to_string()+ };+ eprintln!(" {dim}β Logs: {}{dim:#}", display_path);+ }+ Err(e) => {+ eprintln!("{WARNING_EMOJI} {WARNING}Failed to spawn '{name}': {e}{WARNING:#}");}}}- // Flush all output before returning to ensure proper display orderuse std::io::Write;let _ = std::io::stdout().flush();let _ = std::io::stderr().flush();@@ -481,6 +544,48 @@ fn execute_post_start_commands(Ok(())}+/// Check if command is approved and prompt if needed+fn check_and_approve_command(+ project_id: &str,+ command: &str,+ config: &WorktrunkConfig,+ force: bool,+) -> Result<bool, GitError> {+ if force || config.is_command_approved(project_id, command) {+ return Ok(true);+ }++ match prompt_for_approval(command, project_id) {+ Ok(true) => {+ // Reload config and save approval+ match WorktrunkConfig::load() {+ Ok(mut fresh_config) => {+ if let Err(e) =+ fresh_config.approve_command(project_id.to_string(), command.to_string())+ {+ eprintln!(+ "{WARNING_EMOJI} {WARNING}Failed to save command approval: {e}{WARNING:#}"+ );+ eprintln!("You will be prompted again next time.");+ }+ }+ Err(e) => {+ eprintln!(+ "{WARNING_EMOJI} {WARNING}Failed to reload config for saving approval: {e}{WARNING:#}"+ );+ eprintln!("You will be prompted again next time.");+ }+ }+ Ok(true)+ }+ Ok(false) => Ok(false),+ Err(e) => {+ eprintln!("{WARNING_EMOJI} {WARNING}Failed to read user input: {e}{WARNING:#}");+ Ok(false)+ }+ }+}+pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), GitError> {use anstyle::{AnsiColor, Color};diff --git a/src/config.rs b/src/config.rsindex 184d8117c..7c1a7c01a 100644--- a/src/config.rs+++ b/src/config.rs@@ -65,9 +65,27 @@ pub struct LlmConfig {/// Project-specific configuration (stored in .config/wt.toml within the project)#[derive(Debug, Serialize, Deserialize, Clone, Default)]pub struct ProjectConfig {- /// Commands to execute after creating a new worktree- #[serde(default, rename = "post-start-commands")]- pub post_start_commands: Vec<String>,+ /// Commands to execute sequentially before worktree is ready (blocking)+ /// Supports string (single command), array (sequential), or table (named, sequential)+ #[serde(default, rename = "post-create-command")]+ pub post_create_command: Option<CommandConfig>,++ /// Commands to execute in parallel as background processes (non-blocking)+ /// Supports string (single), array (parallel), or table (named, parallel)+ #[serde(default, rename = "post-start-command")]+ pub post_start_command: Option<CommandConfig>,+}++/// Configuration for commands - supports multiple formats+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum CommandConfig {+ /// Single command as a string+ Single(String),+ /// Multiple commands as an array+ Multiple(Vec<String>),+ /// Named commands as a table (map)+ Named(std::collections::HashMap<String, String>),}/// Approved command for automatic execution@@ -395,29 +413,63 @@ mod tests {#[test]fn test_project_config_default() {let config = ProjectConfig::default();- assert!(config.post_start_commands.is_empty());+ assert!(config.post_create_command.is_none());+ assert!(config.post_start_command.is_none());}#[test]- fn test_project_config_serialization() {- let config = ProjectConfig {- post_start_commands: vec!["npm install".to_string(), "npm test".to_string()],- };- let toml = toml::to_string(&config).unwrap();- assert!(toml.contains("post-start-commands"));- assert!(toml.contains("npm install"));- assert!(toml.contains("npm test"));+ fn test_command_config_single() {+ let toml = r#"post-create-command = "npm install""#;+ let config: ProjectConfig = toml::from_str(toml).unwrap();+ assert!(matches!(+ config.post_create_command,+ Some(CommandConfig::Single(_))+ ));}#[test]- fn test_project_config_deserialization() {+ fn test_command_config_multiple() {+ let toml = r#"post-create-command = ["npm install", "npm test"]"#;+ let config: ProjectConfig = toml::from_str(toml).unwrap();+ match config.post_create_command {+ Some(CommandConfig::Multiple(cmds)) => {+ assert_eq!(cmds.len(), 2);+ assert_eq!(cmds[0], "npm install");+ assert_eq!(cmds[1], "npm test");+ }+ _ => panic!("Expected Multiple variant"),+ }+ }++ #[test]+ fn test_command_config_named() {let toml = r#"- post-start-commands = ["npm install", "npm test"]+ [post-start-command]+ server = "npm run dev"+ watch = "npm run watch"+ "#;+ let config: ProjectConfig = toml::from_str(toml).unwrap();+ match config.post_start_command {+ Some(CommandConfig::Named(cmds)) => {+ assert_eq!(cmds.len(), 2);+ assert_eq!(cmds.get("server"), Some(&"npm run dev".to_string()));+ assert_eq!(cmds.get("watch"), Some(&"npm run watch".to_string()));+ }+ _ => panic!("Expected Named variant"),+ }+ }++ #[test]+ fn test_project_config_both_commands() {+ let toml = r#"+ post-create-command = ["npm install"]++ [post-start-command]+ server = "npm run dev""#;let config: ProjectConfig = toml::from_str(toml).unwrap();- assert_eq!(config.post_start_commands.len(), 2);- assert_eq!(config.post_start_commands[0], "npm install");- assert_eq!(config.post_start_commands[1], "npm test");+ assert!(config.post_create_command.is_some());+ assert!(config.post_start_command.is_some());}#[test]diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex adb8ec62e..9961e1e5c 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -373,6 +373,13 @@ pub fn setup_snapshot_settings(repo: &TestRepo) -> insta::Settings {settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA]");settings.add_filter(r"\\", "/");+ // Normalize timestamps in log filenames (format: YYYYMMDD-HHMMSS)+ // The SHA filter runs first, so we match: post-start-NAME-[SHA]-HHMMSS.log+ settings.add_filter(+ r"post-start-[^-]+-\[SHA\]-\d{6}\.log",+ "post-start-[NAME]-[TIMESTAMP].log",+ );+settings}diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rsnew file mode 100644index 000000000..208d87ee8--- /dev/null+++ b/tests/integration_tests/e2e_shell_post_start.rs@@ -0,0 +1,518 @@+use crate::common::TestRepo;+use insta_cmd::get_cargo_bin;+use rstest::rstest;+use std::fs;+use std::process::Command;+use std::thread;+use std::time::Duration;+use tempfile::TempDir;++/// Map shell display names to actual binary names+fn get_shell_binary(shell: &str) -> &str {+ match shell {+ "nushell" => "nu",+ "powershell" => "pwsh",+ "oil" => "osh",+ _ => shell,+ }+}++/// Helper to check if a shell is available on the system+fn is_shell_available(shell: &str) -> bool {+ let binary = get_shell_binary(shell);+ Command::new("which")+ .arg(binary)+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++/// Execute a shell script in the given shell and return stdout+/// Optionally set a custom HOME directory+fn execute_shell_script_with_home(+ repo: &TestRepo,+ shell: &str,+ script: &str,+ home: Option<&std::path::Path>,+) -> String {+ let binary = get_shell_binary(shell);+ let mut cmd = Command::new(binary);+ repo.clean_cli_env(&mut cmd);++ // Set HOME if provided+ if let Some(home_path) = home {+ cmd.env("HOME", home_path);+ }++ // Additional shell-specific isolation to prevent user config interference+ cmd.env_remove("BASH_ENV");+ cmd.env_remove("ENV"); // for sh/dash+ cmd.env_remove("ZDOTDIR"); // for zsh+ cmd.env_remove("XONSHRC"); // for xonsh+ cmd.env_remove("XDG_CONFIG_HOME"); // for elvish and others++ // Prevent loading user config files+ match shell {+ "fish" => {+ cmd.arg("--no-config");+ }+ "powershell" | "pwsh" => {+ cmd.arg("-NoProfile");+ }+ "xonsh" => {+ cmd.arg("--no-rc");+ }+ "nushell" | "nu" => {+ cmd.arg("--no-config-file");+ }+ _ => {}+ }++ let output = cmd+ .arg("-c")+ .arg(script)+ .current_dir(repo.root_path())+ .output()+ .unwrap_or_else(|e| panic!("Failed to execute {} script: {}", shell, e));++ if !output.status.success() {+ panic!(+ "Shell script failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ String::from_utf8(output.stdout).expect("Invalid UTF-8 in output")+}++/// Generate shell integration code for the given shell+fn generate_init_code(repo: &TestRepo, shell: &str) -> String {+ let mut cmd = Command::new(get_cargo_bin("wt"));+ repo.clean_cli_env(&mut cmd);++ let output = cmd+ .args(["init", shell])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to generate init code");++ if !output.status.success() {+ panic!(+ "Failed to generate init code:\nstderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }++ String::from_utf8(output.stdout).expect("Invalid UTF-8 in init code")+}++/// Generate shell-specific PATH export syntax+fn path_export_syntax(shell: &str, bin_path: &str) -> String {+ match shell {+ "fish" => format!(r#"set -x PATH {} $PATH"#, bin_path),+ "nushell" => format!(r#"$env.PATH = ($env.PATH | prepend "{}")"#, bin_path),+ "powershell" => format!(r#"$env:PATH = "{}:$env:PATH""#, bin_path),+ "elvish" => format!(r#"set E:PATH = {}:$E:PATH"#, bin_path),+ "xonsh" => format!(r#"$PATH.insert(0, "{}")"#, bin_path),+ _ => format!(r#"export PATH="{}:$PATH""#, bin_path), // bash, zsh, oil+ }+}++/// Test that post-start background commands work with shell integration+#[rstest]+// Tier 1: Shells available in standard Ubuntu repos+#[case("bash")]+#[case("fish")]+#[case("zsh")]+// Tier 2: Shells requiring extra setup+#[cfg_attr(feature = "tier-2-integration-tests", case("elvish"))]+#[cfg_attr(feature = "tier-2-integration-tests", case("nushell"))]+#[cfg_attr(feature = "tier-2-integration-tests", case("oil"))]+#[cfg_attr(feature = "tier-2-integration-tests", case("xonsh"))]+fn test_e2e_post_start_background_command(#[case] shell: &str) {+ if !is_shell_available(shell) {+ eprintln!("Skipping test: {} not available", shell);+ return;+ }++ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with background command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-start-command = "sleep 0.5 && echo 'Background task done' > bg_marker.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add post-start config");++ // Pre-approve the command+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "sleep 0.5 && echo 'Background task done' > bg_marker.txt"+"#,+ )+ .expect("Failed to write user config");++ let init_code = generate_init_code(&repo, shell);+ let bin_path = get_cargo_bin("wt")+ .parent()+ .unwrap()+ .to_string_lossy()+ .to_string();++ let script = format!(+ r#"+ {}+ {}+ wt switch --create bg-feature+ echo "Switched to worktree"+ pwd+ "#,+ path_export_syntax(shell, &bin_path),+ init_code+ );++ let output = execute_shell_script_with_home(&repo, shell, &script, Some(temp_home.path()));++ // Verify that:+ // 1. The switch command completed (shell returned)+ // 2. We're in the new worktree+ assert!(+ output.contains("Switched to worktree") && output.contains("bg-feature"),+ "Expected to see switch completion and be in bg-feature worktree, got: {}",+ output+ );++ // Wait for background command to complete+ thread::sleep(Duration::from_secs(2));++ // Verify background command actually ran+ let worktree_path = repo.root_path().parent().unwrap().join("main.bg-feature");++ // First check if log file was created (proves process was spawned)+ let git_dir = worktree_path.join(".git");+ let actual_git_dir = if git_dir.is_file() {+ let content = fs::read_to_string(&git_dir).expect("Failed to read .git file");+ let gitdir_path = content+ .trim()+ .strip_prefix("gitdir: ")+ .expect("Invalid .git format");+ std::path::PathBuf::from(gitdir_path)+ } else {+ git_dir+ };++ let log_dir = actual_git_dir.join("wt-logs");+ assert!(+ log_dir.exists(),+ "Log directory should exist at {}",+ log_dir.display()+ );++ // Check for log files+ let log_files: Vec<_> = fs::read_dir(&log_dir)+ .expect("Failed to read log dir")+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().to_string())+ .collect();++ assert!(+ !log_files.is_empty(),+ "Should have log files in {}, found: {:?}",+ log_dir.display(),+ log_files+ );++ let marker_file = worktree_path.join("bg_marker.txt");+ assert!(+ marker_file.exists(),+ "Background command should have created bg_marker.txt in {} (logs: {:?})",+ worktree_path.display(),+ log_files+ );++ let content = fs::read_to_string(&marker_file).expect("Failed to read marker file");+ assert!(+ content.contains("Background task done"),+ "Expected background task output, got: {}",+ content+ );+}++/// Test that multiple post-start commands run in parallel with shell integration+#[test]+fn test_bash_post_start_multiple_parallel_commands() {+ if !is_shell_available("bash") {+ eprintln!("Skipping test: bash not available");+ return;+ }++ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with multiple background commands+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"[post-start-command]+task1 = "sleep 0.5 && echo 'Task 1' > task1.txt"+task2 = "sleep 0.5 && echo 'Task 2' > task2.txt"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add multiple post-start commands");++ // Pre-approve commands+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "sleep 0.5 && echo 'Task 1' > task1.txt"++[[approved-commands]]+project = "main"+command = "sleep 0.5 && echo 'Task 2' > task2.txt"+"#,+ )+ .expect("Failed to write user config");++ let init_code = generate_init_code(&repo, "bash");+ let bin_path = get_cargo_bin("wt")+ .parent()+ .unwrap()+ .to_string_lossy()+ .to_string();++ let script = format!(+ r#"+ export PATH="{}:$PATH"+ {}+ wt switch --create parallel-test+ echo "Returned from wt"+ "#,+ bin_path, init_code+ );++ let output = execute_shell_script_with_home(&repo, "bash", &script, Some(temp_home.path()));++ // Verify shell returned immediately (didn't wait for background tasks)+ assert!(+ output.contains("Returned from wt"),+ "Expected immediate return from wt, got: {}",+ output+ );++ // Wait for background commands to complete+ thread::sleep(Duration::from_secs(1));++ // Verify both background commands ran+ let worktree_path = repo+ .root_path()+ .parent()+ .unwrap()+ .join("main.parallel-test");+ assert!(+ worktree_path.join("task1.txt").exists(),+ "Task 1 should have completed"+ );+ assert!(+ worktree_path.join("task2.txt").exists(),+ "Task 2 should have completed"+ );+}++/// Test that post-create commands block before shell returns+#[test]+fn test_bash_post_create_blocks() {+ if !is_shell_available("bash") {+ eprintln!("Skipping test: bash not available");+ return;+ }++ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with blocking command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = "echo 'Setup done' > setup.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add post-create command");++ // Pre-approve command+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "echo 'Setup done' > setup.txt"+"#,+ )+ .expect("Failed to write user config");++ let init_code = generate_init_code(&repo, "bash");+ let bin_path = get_cargo_bin("wt")+ .parent()+ .unwrap()+ .to_string_lossy()+ .to_string();++ let worktree_path = repo+ .root_path()+ .parent()+ .unwrap()+ .join("main.blocking-test");+ let script = format!(+ r#"+ export PATH="{}:$PATH"+ {}+ wt switch --create blocking-test+ pwd+ "#,+ bin_path, init_code+ );++ let output = execute_shell_script_with_home(&repo, "bash", &script, Some(temp_home.path()));++ // Verify we switched to the worktree+ assert!(+ output.contains("blocking-test"),+ "Expected to be in blocking-test worktree, got: {}",+ output+ );++ // Verify that post-create command completed before wt returned (blocking behavior)+ // The file should exist immediately after wt exits+ let setup_file = worktree_path.join("setup.txt");+ assert!(+ setup_file.exists(),+ "Setup file should exist immediately after wt returns (post-create is blocking)"+ );++ let content = fs::read_to_string(&setup_file).expect("Failed to read setup file");+ assert!(+ content.contains("Setup done"),+ "Expected setup output, got: {}",+ content+ );+}++/// Test fish shell specifically with background tasks+#[test]+fn test_fish_post_start_background() {+ if !is_shell_available("fish") {+ eprintln!("Skipping test: fish not available");+ return;+ }++ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with background command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"[post-start-command]+fish_bg = "sleep 0.5 && echo 'Fish background done' > fish_bg.txt"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add fish background command");++ // Pre-approve command+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "sleep 0.5 && echo 'Fish background done' > fish_bg.txt"+"#,+ )+ .expect("Failed to write user config");++ let init_code = generate_init_code(&repo, "fish");+ let bin_path = get_cargo_bin("wt")+ .parent()+ .unwrap()+ .to_string_lossy()+ .to_string();++ let script = format!(+ r#"+ set -x PATH {} $PATH+ {}+ wt switch --create fish-bg-test+ echo "Fish shell returned"+ pwd+ "#,+ bin_path, init_code+ );++ let output = execute_shell_script_with_home(&repo, "fish", &script, Some(temp_home.path()));++ // Verify fish shell returned immediately+ assert!(+ output.contains("Fish shell returned") && output.contains("fish-bg-test"),+ "Expected fish shell to return immediately, got: {}",+ output+ );++ // Wait for background command+ thread::sleep(Duration::from_secs(1));++ // Verify background command ran+ let worktree_path = repo.root_path().parent().unwrap().join("main.fish-bg-test");+ let marker_file = worktree_path.join("fish_bg.txt");+ assert!(+ marker_file.exists(),+ "Fish background command should have created fish_bg.txt"+ );++ let content = fs::read_to_string(&marker_file).expect("Failed to read marker file");+ assert!(+ content.contains("Fish background done"),+ "Expected fish background output, got: {}",+ content+ );+}diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 40687930d..a46bb6179 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -6,6 +6,7 @@ pub mod configure_shell;pub mod default_branch;pub mod directives;pub mod e2e_shell;+pub mod e2e_shell_post_start;pub mod init;pub mod list;pub mod merge;diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex 0a90688b9..b2b8039c4 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -2,6 +2,8 @@ use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings};use insta_cmd::assert_cmd_snapshot;use std::fs;use std::path::Path;+use std::thread;+use std::time::Duration;use tempfile::TempDir;/// Helper to create snapshot with normalized paths and SHAs@@ -17,36 +19,18 @@ fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str], temp_home: O});}-#[test]-fn test_post_start_commands_no_config() {- let repo = TestRepo::new();- repo.commit("Initial commit");-- // Switch without project config should work normally- snapshot_switch(- "post_start_no_config",- &repo,- &["--create", "feature"],- None,- );-}+// ============================================================================+// Post-Create Command Tests (sequential, blocking)+// ============================================================================#[test]-fn test_post_start_commands_empty_array() {+fn test_post_create_no_config() {let repo = TestRepo::new();repo.commit("Initial commit");- // Create empty project config- let config_dir = repo.root_path().join(".config");- fs::create_dir_all(&config_dir).expect("Failed to create .config dir");- fs::write(config_dir.join("wt.toml"), "post-start-commands = []\n")- .expect("Failed to write config");-- repo.commit("Add empty config");-- // Should work without prompting+ // Switch without project config should work normallysnapshot_switch(- "post_start_empty_array",+ "post_create_no_config",&repo,&["--create", "feature"],None,@@ -54,17 +38,17 @@ fn test_post_start_commands_empty_array() {}#[test]-fn test_post_start_commands_with_approval() {+fn test_post_create_single_command() {let temp_home = TempDir::new().unwrap();let repo = TestRepo::new();repo.commit("Initial commit");- // Create project config with a simple command+ // Create project config with a single command (string format)let config_dir = repo.root_path().join(".config");fs::create_dir_all(&config_dir).expect("Failed to create .config dir");fs::write(config_dir.join("wt.toml"),- r#"post-start-commands = ["echo 'Setup complete'"]"#,+ r#"post-create-command = "echo 'Setup complete'""#,).expect("Failed to write config");@@ -88,7 +72,7 @@ command = "echo 'Setup complete'"// Command should execute without promptingsnapshot_switch(- "post_start_with_approval",+ "post_create_single_command",&repo,&["--create", "feature"],Some(temp_home.path()),@@ -96,48 +80,72 @@ command = "echo 'Setup complete'"}#[test]-fn test_post_start_commands_invalid_toml() {+fn test_post_create_multiple_commands_array() {+ let temp_home = TempDir::new().unwrap();let repo = TestRepo::new();repo.commit("Initial commit");- // Create invalid TOML+ // Create project config with multiple commands (array format)let config_dir = repo.root_path().join(".config");fs::create_dir_all(&config_dir).expect("Failed to create .config dir");fs::write(config_dir.join("wt.toml"),- "post-start-commands = [invalid syntax\n",+ r#"post-create-command = ["echo 'First'", "echo 'Second'"]"#,).expect("Failed to write config");- repo.commit("Add invalid config");+ repo.commit("Add config with multiple commands");- // Should continue without executing commands, showing warning+ // Pre-approve both commands in temp HOME+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "echo 'First'"++[[approved-commands]]+project = "main"+command = "echo 'Second'"+"#,+ )+ .expect("Failed to write user config");++ // Both commands should execute sequentiallysnapshot_switch(- "post_start_invalid_toml",+ "post_create_multiple_commands_array",&repo,&["--create", "feature"],- None,+ Some(temp_home.path()),);}#[test]-fn test_post_start_commands_failing_command() {+fn test_post_create_named_commands() {let temp_home = TempDir::new().unwrap();let repo = TestRepo::new();repo.commit("Initial commit");- // Create project config with a command that will fail+ // Create project config with named commands (table format)let config_dir = repo.root_path().join(".config");fs::create_dir_all(&config_dir).expect("Failed to create .config dir");fs::write(config_dir.join("wt.toml"),- r#"post-start-commands = ["exit 1"]"#,+ r#"[post-create-command]+install = "echo 'Installing deps'"+setup = "echo 'Running setup'"+"#,).expect("Failed to write config");- repo.commit("Add config with failing command");+ repo.commit("Add config with named commands");- // Pre-approve the command in temp HOME+ // Pre-approve both commands in temp HOMElet user_config_dir = temp_home.path().join("Library/Application Support/worktrunk");@@ -148,14 +156,18 @@ fn test_post_start_commands_failing_command() {[[approved-commands]]project = "main"-command = "exit 1"+command = "echo 'Installing deps'"++[[approved-commands]]+project = "main"+command = "echo 'Running setup'""#,).expect("Failed to write user config");- // Should show warning but continue (worktree should still be created)+ // Commands should execute sequentiallysnapshot_switch(- "post_start_failing_command",+ "post_create_named_commands",&repo,&["--create", "feature"],Some(temp_home.path()),@@ -163,23 +175,23 @@ command = "exit 1"}#[test]-fn test_post_start_commands_multiple_commands() {+fn test_post_create_failing_command() {let temp_home = TempDir::new().unwrap();let repo = TestRepo::new();repo.commit("Initial commit");- // Create project config with multiple commands+ // Create project config with a command that will faillet config_dir = repo.root_path().join(".config");fs::create_dir_all(&config_dir).expect("Failed to create .config dir");fs::write(config_dir.join("wt.toml"),- r#"post-start-commands = ["echo 'First'", "echo 'Second'"]"#,+ r#"post-create-command = "exit 1""#,).expect("Failed to write config");- repo.commit("Add config with multiple commands");+ repo.commit("Add config with failing command");- // Pre-approve both commands in temp HOME+ // Pre-approve the command in temp HOMElet user_config_dir = temp_home.path().join("Library/Application Support/worktrunk");@@ -190,18 +202,14 @@ fn test_post_start_commands_multiple_commands() {[[approved-commands]]project = "main"-command = "echo 'First'"--[[approved-commands]]-project = "main"-command = "echo 'Second'"+command = "exit 1""#,).expect("Failed to write user config");- // Both commands should execute+ // Should show warning but continue (worktree should still be created)snapshot_switch(- "post_start_multiple_commands",+ "post_create_failing_command",&repo,&["--create", "feature"],Some(temp_home.path()),@@ -209,7 +217,7 @@ command = "echo 'Second'"}#[test]-fn test_post_start_commands_template_expansion() {+fn test_post_create_template_expansion() {let temp_home = TempDir::new().unwrap();let repo = TestRepo::new();repo.commit("Initial commit");@@ -219,7 +227,7 @@ fn test_post_start_commands_template_expansion() {fs::create_dir_all(&config_dir).expect("Failed to create .config dir");fs::write(config_dir.join("wt.toml"),- r#"post-start-commands = [+ r#"post-create-command = ["echo 'Repo: {repo}' > info.txt","echo 'Branch: {branch}' >> info.txt","echo 'Worktree: {worktree}' >> info.txt",@@ -261,14 +269,13 @@ command = "echo 'Root: {repo_root}' >> info.txt"// Commands should execute with expanded templatessnapshot_switch(- "post_start_template_expansion",+ "post_create_template_expansion",&repo,&["--create", "feature/test"],Some(temp_home.path()),);// Verify template expansion actually worked by checking the output file- // The worktree path should be ../main.feature-test (slashes replaced with dashes)let worktree_path = repo.root_path().parent()@@ -283,7 +290,7 @@ command = "echo 'Root: {repo_root}' >> info.txt"let contents = fs::read_to_string(&info_file).expect("Failed to read info.txt");- // Verify that template variables were actually expanded, not left as literals+ // Verify that template variables were actually expandedassert!(contents.contains(&format!("Repo: {}", repo_name)),"Should contain expanded repo name, got: {}",@@ -294,38 +301,222 @@ command = "echo 'Root: {repo_root}' >> info.txt""Should contain expanded branch name (sanitized), got: {}",contents);- assert!(- contents.contains(&format!(- "Worktree: {}",- worktree_path.canonicalize().unwrap().display()- )),- "Should contain expanded worktree path, got: {}",- contents+}++// ============================================================================+// Post-Start Command Tests (parallel, background)+// ============================================================================++#[test]+fn test_post_start_single_background_command() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with a background command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-start-command = "sleep 1 && echo 'Background task done' > background.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add background command");++ // Pre-approve the command+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "sleep 1 && echo 'Background task done' > background.txt"+"#,+ )+ .expect("Failed to write user config");++ // Command should spawn in background (wt exits immediately)+ snapshot_switch(+ "post_start_single_background",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),);++ // Verify log file was created+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");++ // In a worktree, .git is a file pointing to the real git directory+ let git_path = worktree_path.join(".git");+ let git_dir = if git_path.is_file() {+ let content = fs::read_to_string(&git_path).expect("Failed to read .git file");+ let gitdir_path = content+ .trim()+ .strip_prefix("gitdir: ")+ .expect("Invalid .git format");+ std::path::PathBuf::from(gitdir_path)+ } else {+ git_path+ };++ let log_dir = git_dir.join("wt-logs");+ assert!(log_dir.exists(), "Log directory should be created");++ // Wait a bit for the background command to complete+ thread::sleep(Duration::from_secs(2));++ // Verify the background command actually ran+ let output_file = worktree_path.join("background.txt");assert!(- contents.contains(&format!(- "Root: {}",- repo.root_path().canonicalize().unwrap().display()- )),- "Should contain expanded repo root path, got: {}",- contents+ output_file.exists(),+ "Background command should have created output file");+}- // Make sure they're NOT the literal template strings- assert!(- !contents.contains("{repo}"),- "Should not contain literal {{repo}} placeholder"+#[test]+fn test_post_start_multiple_background_commands() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with multiple background commands (table format)+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"[post-start-command]+task1 = "echo 'Task 1 running' > task1.txt"+task2 = "echo 'Task 2 running' > task2.txt"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add multiple background commands");++ // Pre-approve both commands+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "echo 'Task 1 running' > task1.txt"++[[approved-commands]]+project = "main"+command = "echo 'Task 2 running' > task2.txt"+"#,+ )+ .expect("Failed to write user config");++ // Commands should spawn in parallel+ snapshot_switch(+ "post_start_multiple_background",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),);- assert!(- !contents.contains("{branch}"),- "Should not contain literal {{branch}} placeholder"++ // Wait for background commands+ thread::sleep(Duration::from_secs(1));++ // Verify both tasks ran+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");+ assert!(worktree_path.join("task1.txt").exists());+ assert!(worktree_path.join("task2.txt").exists());+}++#[test]+fn test_both_post_create_and_post_start() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with both command types+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-create-command = "echo 'Setup done' > setup.txt"++[post-start-command]+server = "sleep 0.5 && echo 'Server running' > server.txt"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add both command types");++ // Pre-approve all commands+ let user_config_dir = temp_home+ .path()+ .join("Library/Application Support/worktrunk");+ fs::create_dir_all(&user_config_dir).expect("Failed to create user config dir");+ fs::write(+ user_config_dir.join("config.toml"),+ r#"worktree-path = "../{repo}.{branch}"++[[approved-commands]]+project = "main"+command = "echo 'Setup done' > setup.txt"++[[approved-commands]]+project = "main"+command = "sleep 0.5 && echo 'Server running' > server.txt"+"#,+ )+ .expect("Failed to write user config");++ // Post-create should run first (blocking), then post-start (background)+ snapshot_switch(+ "both_create_and_start",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),);++ // Setup file should exist immediately (post-create is blocking)+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");assert!(- !contents.contains("{worktree}"),- "Should not contain literal {{worktree}} placeholder"+ worktree_path.join("setup.txt").exists(),+ "Post-create command should have completed before wt exits");++ // Wait for background command+ thread::sleep(Duration::from_secs(1));++ // Server file should exist after background task completesassert!(- !contents.contains("{repo_root}"),- "Should not contain literal {{repo_root}} placeholder"+ worktree_path.join("server.txt").exists(),+ "Post-start background command should complete");}++#[test]+fn test_invalid_toml() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create invalid TOML+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");+ fs::write(+ config_dir.join("wt.toml"),+ "post-create-command = [invalid syntax\n",+ )+ .expect("Failed to write config");++ repo.commit("Add invalid config");++ // Should continue without executing commands, showing warning+ snapshot_switch("invalid_toml", &repo, &["--create", "feature"], None);+}diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__both_create_and_start.snap b/tests/snapshots/integration__integration_tests__post_start_commands__both_create_and_start.snapnew file mode 100644index 000000000..21d48b8c4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__both_create_and_start.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2NgX3P+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mCreated new worktree for [1m[32mfeature[0m[0m+ [2mPath: [REPO].feature[0m++To enable automatic cd, run: wt configure-shell++----- stderr -----+π [36mExecuting (post-create): echo 'Setup done' > setup.txt[0m+π [36mStarting (background): sleep 0.5 && echo 'Server running' > server.txt[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snapsimilarity index 65%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snapindex 64c63a665..2832c956e 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_toml.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap@@ -29,8 +29,16 @@ To enable automatic cd, run: wt configure-shellπ‘ [33mFailed to load project config from [REPO]/.config/wt.toml[0mπ‘ [2mError details: TOML parse error at line 1, column 39|-1 | post-start-commands = [invalid syntax+1 | post-create-command = [invalid syntax| ^unclosed array, expected `]`in .config/wt.toml[0m-π‘ [2mSkipping post-start commands. Check TOML syntax if file exists.[0m+π‘ [2mSkipping commands. Check TOML syntax if file exists.[0m+π‘ [33mFailed to load project config from [REPO]/.config/wt.toml[0m+π‘ [2mError details: TOML parse error at line 1, column 39+ |+1 | post-create-command = [invalid syntax+ | ^+unclosed array, expected `]`+ in .config/wt.toml[0m+π‘ [2mSkipping commands. Check TOML syntax if file exists.[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_failing_command.snapsimilarity index 75%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_failing_command.snapindex dd5a97417..ceb25038b 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_failing_command.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_failing_command.snap@@ -13,7 +13,7 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpQmUBXp+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpN6uBLsLANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1704067200"@@ -27,5 +27,5 @@ exit_code: 0To enable automatic cd, run: wt configure-shell----- stderr ------π [36mExecuting: exit 1[0m-π‘ [33mCommand failed: Command 'exit 1' failed with exit code 1[0m+π [36mExecuting (post-create): exit 1[0m+π‘ [33mCommand 'default' failed: Command 'exit 1' failed with exit code 1[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snapsimilarity index 78%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snapindex 69e12c973..af85df91b 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_commands.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap@@ -13,7 +13,7 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp7JwUkM+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdXUI1SLANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1704067200"@@ -29,5 +29,5 @@ SecondTo enable automatic cd, run: wt configure-shell----- stderr ------π [36mExecuting: echo 'First'[0m-π [36mExecuting: echo 'Second'[0m+π [36mExecuting (post-create): echo 'First'[0m+π [36mExecuting (post-create): echo 'Second'[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snapsimilarity index 73%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snapindex 8c438a5fb..c6207519e 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_no_config.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap@@ -13,6 +13,7 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdoot33LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1704067200"@@ -20,9 +21,13 @@ info:success: trueexit_code: 0----- stdout -----+Installing deps+Running setupβ [32mCreated new worktree for [1m[32mfeature[0m[0m[2mPath: [REPO].feature[0mTo enable automatic cd, run: wt configure-shell----- stderr -----+π [36mExecuting (post-create): echo 'Installing deps'[0m+π [36mExecuting (post-create): echo 'Running setup'[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_no_config.snapsimilarity index 100%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_empty_array.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_no_config.snapdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snapsimilarity index 82%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snapindex 021b64365..82118296e 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_with_approval.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap@@ -13,7 +13,7 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpF0Nd0x+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpK8piSeLANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1704067200"@@ -28,4 +28,4 @@ Setup completeTo enable automatic cd, run: wt configure-shell----- stderr ------π [36mExecuting: echo 'Setup complete'[0m+π [36mExecuting (post-create): echo 'Setup complete'[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snapsimilarity index 62%rename from tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snaprename to tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snapindex baecf9bab..b7da2214c 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_template_expansion.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap@@ -13,7 +13,7 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxHBIw9+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpB5F27pLANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1704067200"@@ -27,7 +27,7 @@ exit_code: 0To enable automatic cd, run: wt configure-shell----- stderr ------π [36mExecuting: echo 'Repo: main' > info.txt[0m-π [36mExecuting: echo 'Branch: feature-test' >> info.txt[0m-π [36mExecuting: echo 'Worktree: [REPO].feature-test' >> info.txt[0m-π [36mExecuting: echo 'Root: [REPO]' >> info.txt[0m+π [36mExecuting (post-create): echo 'Repo: main' > info.txt[0m+π [36mExecuting (post-create): echo 'Branch: feature-test' >> info.txt[0m+π [36mExecuting (post-create): echo 'Worktree: [REPO].feature-test' >> info.txt[0m+π [36mExecuting (post-create): echo 'Root: [REPO]' >> info.txt[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_background.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_background.snapnew file mode 100644index 000000000..0040d16e5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_multiple_background.snap@@ -0,0 +1,33 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdjrX9R+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mCreated new worktree for [1m[32mfeature[0m[0m+ [2mPath: [REPO].feature[0m++To enable automatic cd, run: wt configure-shell++----- stderr -----+π [36mStarting (background): echo 'Task 1 running' > task1.txt[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0m+π [36mStarting (background): echo 'Task 2 running' > task2.txt[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_single_background.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_single_background.snapnew file mode 100644index 000000000..ed160967f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_single_background.snap@@ -0,0 +1,31 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpevdKIc+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mCreated new worktree for [1m[32mfeature[0m[0m+ [2mPath: [REPO].feature[0m++To enable automatic cd, run: wt configure-shell++----- stderr -----+π [36mStarting (background): sleep 1 && echo 'Background task done' > background.txt[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0m