Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Add more `post-start` command integration tests
Maximilian Roos2646d7b70d7b
diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 9961e1e5c..2c7617a4f 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -400,3 +400,34 @@ pub fn make_snapshot_cmd(.current_dir(cwd.unwrap_or(repo.root_path()));cmd}++/// Resolve the actual git directory path from a worktree path+///+/// In worktrees, `.git` is a file containing `gitdir: /path/to/git/dir`,+/// not a directory. This helper reads that file and returns the actual+/// git directory path.+///+/// # Arguments+/// * `worktree_path` - Path to the worktree root+///+/// # Returns+/// The resolved git directory path+pub fn resolve_git_dir(worktree_path: &Path) -> PathBuf {+ let git_path = worktree_path.join(".git");++ if git_path.is_file() {+ // Read the gitdir path from the file+ let content = std::fs::read_to_string(&git_path).expect("Failed to read .git file");++ // Format is "gitdir: /path/to/git/dir"+ let gitdir_path = content+ .trim()+ .strip_prefix("gitdir: ")+ .expect("Invalid .git file format");++ PathBuf::from(gitdir_path)+ } else {+ // Not a worktree, .git is already a directory+ git_path+ }+}diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rsindex b2b8039c4..2996de373 100644--- a/tests/integration_tests/post_start_commands.rs+++ b/tests/integration_tests/post_start_commands.rs@@ -1,4 +1,4 @@-use crate::common::{TestRepo, make_snapshot_cmd, setup_snapshot_settings};+use crate::common::{TestRepo, make_snapshot_cmd, resolve_git_dir, setup_snapshot_settings};use insta_cmd::assert_cmd_snapshot;use std::fs;use std::path::Path;@@ -6,6 +6,18 @@ use std::thread;use std::time::Duration;use tempfile::TempDir;+// Sleep duration constants for background command tests+// These allow time for background processes to complete and write output files++/// Short wait for fast commands (simple echo statements)+const SLEEP_FAST_COMMAND: Duration = Duration::from_millis(500);++/// Standard wait for background commands with sleep/processing+const SLEEP_BACKGROUND_COMMAND: Duration = Duration::from_secs(1);++/// Extended wait for commands that need extra time (e.g., in e2e shell tests)+const SLEEP_EXTENDED: Duration = Duration::from_secs(2);+/// Helper to create snapshot with normalized paths and SHAs/// If temp_home is provided, sets HOME environment variable to that pathfn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str], temp_home: Option<&Path>) {@@ -350,25 +362,12 @@ command = "sleep 1 && echo 'Background task done' > background.txt"// Verify log file was createdlet 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 git_dir = resolve_git_dir(&worktree_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));+ // Wait for the background command to complete+ thread::sleep(SLEEP_EXTENDED);// Verify the background command actually ranlet output_file = worktree_path.join("background.txt");@@ -427,7 +426,7 @@ command = "echo 'Task 2 running' > task2.txt");// Wait for background commands- thread::sleep(Duration::from_secs(1));+ thread::sleep(SLEEP_BACKGROUND_COMMAND);// Verify both tasks ranlet worktree_path = repo.root_path().parent().unwrap().join("main.feature");@@ -492,7 +491,7 @@ command = "sleep 0.5 && echo 'Server running' > server.txt");// Wait for background command- thread::sleep(Duration::from_secs(1));+ thread::sleep(SLEEP_BACKGROUND_COMMAND);// Server file should exist after background task completesassert!(@@ -520,3 +519,371 @@ fn test_invalid_toml() {// Should continue without executing commands, showing warningsnapshot_switch("invalid_toml", &repo, &["--create", "feature"], None);}++// ============================================================================+// Additional Coverage Tests+// ============================================================================++#[test]+fn test_post_start_log_file_captures_output() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create command that writes to both stdout and stderr+ 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 = "echo 'stdout output' && echo 'stderr output' >&2""#,+ )+ .expect("Failed to write config");++ repo.commit("Add command with stdout/stderr");++ // 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 = "echo 'stdout output' && echo 'stderr output' >&2"+"#,+ )+ .expect("Failed to write user config");++ snapshot_switch(+ "post_start_log_captures_output",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),+ );++ // Give background command time to complete+ thread::sleep(SLEEP_FAST_COMMAND);++ // Find and read the log file+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");+ let git_dir = resolve_git_dir(&worktree_path);+ let log_dir = git_dir.join("wt-logs");+ assert!(log_dir.exists(), "Log directory should exist");++ // Find the log file+ let log_files: Vec<_> = fs::read_dir(&log_dir)+ .expect("Failed to read log dir")+ .filter_map(|e| e.ok())+ .map(|e| e.path())+ .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("log"))+ .collect();++ assert_eq!(+ log_files.len(),+ 1,+ "Should have exactly one log file, found: {:?}",+ log_files+ );++ let log_contents = fs::read_to_string(&log_files[0]).expect("Failed to read log file");++ // Verify both stdout and stderr were captured+ assert!(+ log_contents.contains("stdout output"),+ "Log should contain stdout, got: {}",+ log_contents+ );+ assert!(+ log_contents.contains("stderr output"),+ "Log should contain stderr, got: {}",+ log_contents+ );+}++#[test]+fn test_post_start_invalid_command_handling() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create command with syntax error (missing quote)+ 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 = "echo 'unclosed quote""#,+ )+ .expect("Failed to write config");++ repo.commit("Add invalid 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 = "echo 'unclosed quote"+"#,+ )+ .expect("Failed to write user config");++ // wt should still complete successfully even if background command has errors+ snapshot_switch(+ "post_start_invalid_command",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),+ );++ // Verify worktree was created despite command error+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");+ assert!(+ worktree_path.exists(),+ "Worktree should be created even if post-start command fails"+ );+}++#[test]+fn test_post_start_multiple_commands_separate_logs() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create multiple background commands with distinct output+ 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 'TASK1_OUTPUT'"+task2 = "echo 'TASK2_OUTPUT'"+task3 = "echo 'TASK3_OUTPUT'"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add three background commands");++ // 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 'TASK1_OUTPUT'"++[[approved-commands]]+project = "main"+command = "echo 'TASK2_OUTPUT'"++[[approved-commands]]+project = "main"+command = "echo 'TASK3_OUTPUT'"+"#,+ )+ .expect("Failed to write user config");++ snapshot_switch(+ "post_start_separate_logs",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),+ );++ // Give background commands time to complete+ thread::sleep(SLEEP_FAST_COMMAND);++ // Verify we have 3 separate log files+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");+ let git_dir = resolve_git_dir(&worktree_path);+ let log_dir = git_dir.join("wt-logs");+ let log_files: Vec<_> = fs::read_dir(&log_dir)+ .expect("Failed to read log dir")+ .filter_map(|e| e.ok())+ .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("log"))+ .collect();++ assert_eq!(+ log_files.len(),+ 3,+ "Should have 3 separate log files, found: {}",+ log_files.len()+ );++ // Read all log files and verify no cross-contamination+ let mut found_outputs = vec![false, false, false];+ for entry in log_files {+ let contents = fs::read_to_string(entry.path()).expect("Failed to read log file");+ let count_task1 = contents.matches("TASK1_OUTPUT").count();+ let count_task2 = contents.matches("TASK2_OUTPUT").count();+ let count_task3 = contents.matches("TASK3_OUTPUT").count();++ // Each log should contain exactly one task's output+ let total_outputs = count_task1 + count_task2 + count_task3;+ assert_eq!(+ total_outputs,+ 1,+ "Each log should contain exactly one task's output, found {} in {:?}",+ total_outputs,+ entry.path()+ );++ if count_task1 == 1 {+ found_outputs[0] = true;+ }+ if count_task2 == 1 {+ found_outputs[1] = true;+ }+ if count_task3 == 1 {+ found_outputs[2] = true;+ }+ }++ assert!(+ found_outputs.iter().all(|&x| x),+ "Should find output from all three tasks, found: {:?}",+ found_outputs+ );+}++#[test]+fn test_execute_flag_with_post_start_commands() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create post-start 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 = "echo 'Background task' > 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 = "echo 'Background task' > background.txt"+"#,+ )+ .expect("Failed to write user config");++ // Use --execute flag along with post-start command+ snapshot_switch(+ "execute_with_post_start",+ &repo,+ &[+ "--create",+ "feature",+ "--execute",+ "echo 'Execute flag' > execute.txt",+ ],+ Some(temp_home.path()),+ );++ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");++ // Execute flag file should exist immediately (synchronous)+ assert!(+ worktree_path.join("execute.txt").exists(),+ "Execute command should run synchronously"+ );++ // Wait for background command+ thread::sleep(SLEEP_FAST_COMMAND);++ // Background file should also exist+ assert!(+ worktree_path.join("background.txt").exists(),+ "Post-start command should also run"+ );+}++#[test]+fn test_post_start_complex_shell_commands() {+ let temp_home = TempDir::new().unwrap();+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create command with pipes and redirects+ 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 = "echo 'line1\nline2\nline3' | grep line2 > filtered.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add complex shell 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 = "echo 'line1\nline2\nline3' | grep line2 > filtered.txt"+"#,+ )+ .expect("Failed to write user config");++ snapshot_switch(+ "post_start_complex_shell",+ &repo,+ &["--create", "feature"],+ Some(temp_home.path()),+ );++ // Wait for background command+ thread::sleep(SLEEP_FAST_COMMAND);++ // Verify the piped command worked correctly+ let worktree_path = repo.root_path().parent().unwrap().join("main.feature");+ let filtered_file = worktree_path.join("filtered.txt");+ assert!(+ filtered_file.exists(),+ "Complex shell command should create output file"+ );++ let contents = fs::read_to_string(&filtered_file).expect("Failed to read filtered.txt");+ assert!(+ contents.contains("line2"),+ "Should contain filtered output, got: {}",+ contents+ );+ assert!(+ !contents.contains("line1") && !contents.contains("line3"),+ "Should only contain line2, got: {}",+ contents+ );+}diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap b/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snapnew file mode 100644index 000000000..e35f0ac7a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__execute_with_post_start.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/post_start_commands.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ - "--execute"+ - "echo 'Execute flag' > execute.txt"+ 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/.tmppAp6Di+ 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+++----- stderr -----+π [36mStarting (background): echo 'Background task' > background.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_complex_shell.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_complex_shell.snapnew file mode 100644index 000000000..6eb25a0b1--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_complex_shell.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/.tmp4ONp21+ 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 'line1+line2+line3' | grep line2 > filtered.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_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_command.snapnew file mode 100644index 000000000..0bddb8cf9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_invalid_command.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/.tmpAUf5hw+ 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 'unclosed quote[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_log_captures_output.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_log_captures_output.snapnew file mode 100644index 000000000..26ab355f4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_log_captures_output.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/.tmpJec4ml+ 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 'stdout output' && echo 'stderr output' >&2[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_separate_logs.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_separate_logs.snapnew file mode 100644index 000000000..087940738--- /dev/null+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_separate_logs.snap@@ -0,0 +1,35 @@+---+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/.tmpwYI79g+ 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 'TASK1_OUTPUT'[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0m+π [36mStarting (background): echo 'TASK2_OUTPUT'[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0m+π [36mStarting (background): echo 'TASK3_OUTPUT'[0m+ [2mβ Logs: .git/wt-logs/post-start-[NAME]-[TIMESTAMP].log[0m