Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: Improve external command output interleaving
Maximilian Roos182844cec777
diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex cc54f9e6a..95b2274a5 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -121,23 +121,58 @@ pub fn execute_command_in_worktree(worktree_path: &std::path::Path,command: &str,) -> Result<(), GitError> {+ use std::io::{BufRead, BufReader, Write};use std::process::{Command, Stdio};+ use worktrunk::styling::println;- // Redirect child's stdout to parent's stderr so all bytes go to a single FD.- // This prevents terminal reordering between stdout and stderr writes.- // Brace group ensures the redirection applies to the whole command (pipes, &&, etc.)- // TODO: Support Windows with appropriate redirect syntax for cmd.exe: ( command ) 1>&2- let wrapped = format!("{{ {}; }} 1>&2", command);+ // Flush stdout before executing command to ensure all our messages appear+ // before the child process output+ super::flush()?;- let status = Command::new("sh")+ // Spawn the command, capturing stdout and stderr so we can write them in order+ let mut child = Command::new("sh").arg("-c")- .arg(&wrapped)+ .arg(command).current_dir(worktree_path)- .stdout(Stdio::inherit())- .stderr(Stdio::inherit())- .status()+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn().git_context("Failed to execute command")?;+ // Read and immediately write output line-by-line to maintain interleaving+ // Both child stdout and stderr go to our stdout (not stderr as before)+ // This ensures all output goes to the same FD and appears in order+ let stdout = child.stdout.take().unwrap();+ let stderr = child.stderr.take().unwrap();++ // Use threads to read both streams concurrently+ let stdout_thread = std::thread::spawn(move || {+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if let Ok(line) = line {+ println!("{}", line);+ let _ = worktrunk::styling::stdout().flush();+ }+ }+ });++ let stderr_thread = std::thread::spawn(move || {+ let reader = BufReader::new(stderr);+ for line in reader.lines() {+ if let Ok(line) = line {+ println!("{}", line);+ let _ = worktrunk::styling::stdout().flush();+ }+ }+ });++ // Wait for output threads to complete+ let _ = stdout_thread.join();+ let _ = stderr_thread.join();++ // Wait for command to complete+ let status = child.wait().git_context("Failed to wait for command")?;+if !status.success() {return Err(GitError::CommandFailed(format!("Command failed with exit code: {}",@@ -145,6 +180,9 @@ pub fn execute_command_in_worktree()));}+ // Flush to ensure all output appears before we continue+ super::flush()?;+// Terminate output (adds NUL in directive mode, no-op in interactive)super::terminate_output()?;diff --git a/src/output/interactive.rs b/src/output/interactive.rsindex bca9ded66..7aeec5436 100644--- a/src/output/interactive.rs+++ b/src/output/interactive.rs@@ -2,7 +2,7 @@use std::io::{self, Write};use std::path::Path;-use worktrunk::styling::{GREEN, SUCCESS_EMOJI, println};+use worktrunk::styling::{GREEN, SUCCESS_EMOJI, println, stdout, stderr};/// Interactive output mode for human users///@@ -20,19 +20,20 @@ impl InteractiveOutput {pub fn success(&mut self, message: String) -> io::Result<()> {println!("{SUCCESS_EMOJI} {GREEN}{message}{GREEN:#}");+ stdout().flush()?;Ok(())}pub fn progress(&mut self, message: String) -> io::Result<()> {println!("{message}");- io::stdout().flush()?;+ stdout().flush()?;Ok(())}pub fn hint(&mut self, message: String) -> io::Result<()> {// Hints are suggestions for interactive users (like "run wt configure-shell")println!("{message}");- io::stdout().flush()?;+ stdout().flush()?;Ok(())}@@ -77,8 +78,8 @@ impl InteractiveOutput {}pub fn flush(&mut self) -> io::Result<()> {- io::stdout().flush()?;- io::stderr().flush()?;+ stdout().flush()?;+ stderr().flush()?;Ok(())}diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.new b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.newnew file mode 100644index 000000000..d0363daf9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_combined_output.snap.new@@ -0,0 +1,29 @@+---+source: tests/integration_tests/merge.rs+assertion_line: 1147+expression: output+---+Exit code: 0+π [36mValidating merge...[0m+π [36mRunning pre-merge command [1m[36mfirst[0m:[0m+[40m [0m echo 'STDOUT-FROM-FIRST' && echo 'STDERR-FROM-FIRST' >&2++STDOUT-FROM-FIRST+STDERR-FROM-FIRST+π [36mRunning pre-merge command [1m[36msecond[0m:[0m+[40m [0m echo 'STDOUT-FROM-SECOND' && echo 'STDERR-FROM-SECOND' >&2++STDERR-FROM-SECOND+STDOUT-FROM-SECOND+π [36mRebasing onto [1m[36mmain[0m...[0m+π [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m++* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add feature file++ feature.txt | 1 [32m+[m+ 1 file changed, 1 insertion(+)++β [32mPushed to [1m[32mmain[0m (1 commit, 1 file, [32m+1[0m) [0m+π [36mCleaning up worktree...[0m++β [32mReturned to primary at [REPO][0mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snapindex 378320055..1ec8c1928 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmprfH3Ln/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpdnEI0Y/test-config.toml---success: trueexit_code: 0@@ -26,10 +26,26 @@ exit_code: 0[40m [0m [PROJECT_ROOT]/tests/fixtures/mixed-output.sh[40m [0m check1 3+[check1] stderr line 1+[check1] stderr line 2+[check1] stderr line 3+[check1] stderr complete+[check1] stdout line 1+[check1] stdout line 2+[check1] stdout line 3+[check1] stdout completeπ [36mRunning pre-merge command [1m[36mcheck2[0m:[0m[40m [0m [PROJECT_ROOT]/tests/fixtures/mixed-output.sh[40m [0m check2 3+[check2] stdout line 1+[check2] stderr line 1+[check2] stdout line 2+[check2] stderr line 2+[check2] stdout line 3+[check2] stderr line 3+[check2] stdout complete+[check2] stderr completeπ [36mRebasing onto [1m[36mmain[0m...[0mπ [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m@@ -44,19 +60,3 @@ exit_code: 0β [32mReturned to primary at [REPO][0m----- stderr ------[check1] stdout line 1-[check1] stderr line 1-[check1] stdout line 2-[check1] stderr line 2-[check1] stdout line 3-[check1] stderr line 3-[check1] stdout complete-[check1] stderr complete-[check2] stdout line 1-[check2] stderr line 1-[check2] stdout line 2-[check2] stderr line 2-[check2] stdout line 3-[check2] stderr line 3-[check2] stdout complete-[check2] stderr completediff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.new b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.newnew file mode 100644index 000000000..6c370b124--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap.new@@ -0,0 +1,63 @@+---+source: tests/integration_tests/merge.rs+assertion_line: 12+info:+ program: wt+ args:+ - merge+ - main+ - "--force"+ 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: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpR8G6Ki/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mValidating merge...[0m+π [36mRunning pre-merge command [1m[36mcheck1[0m:[0m+[40m [0m [PROJECT_ROOT]/tests/fixtures/mixed-output.sh+[40m [0m check1 3++[check1] stdout line 1+[check1] stderr line 1+[check1] stdout line 2+[check1] stderr line 2+[check1] stdout line 3+[check1] stderr line 3+[check1] stdout complete+[check1] stderr complete+π [36mRunning pre-merge command [1m[36mcheck2[0m:[0m+[40m [0m [PROJECT_ROOT]/tests/fixtures/mixed-output.sh+[40m [0m check2 3++[check2] stderr line 1+[check2] stderr line 2+[check2] stderr line 3+[check2] stderr complete+[check2] stdout line 1+[check2] stdout line 2+[check2] stdout line 3+[check2] stdout complete+π [36mRebasing onto [1m[36mmain[0m...[0m+π [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m++* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add feature file++ feature.txt | 1 [32m+[m+ 1 file changed, 1 insertion(+)++β [32mPushed to [1m[32mmain[0m (1 commit, 1 file, [32m+1[0m) [0m+π [36mCleaning up worktree...[0m++β [32mReturned to primary at [REPO][0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snapindex b2877cd7d..11ec85271 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpsmacvw/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWgEEAu/test-config.toml---success: trueexit_code: 0@@ -24,13 +24,13 @@ exit_code: 0π [36mExecuting (post-create):[0m[40m [0m echo 'First'+Firstπ [36mExecuting (post-create):[0m[40m [0m echo 'Second'+Secondβ [32mCreated new worktree for [1mfeature[0m at [REPO].feature[0mTo enable automatic cd, run: wt configure-shell----- stderr ------First-Seconddiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snapindex ce03d0b02..2a55cef42 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpggIPgR/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp55Mjxv/test-config.toml---success: trueexit_code: 0@@ -24,13 +24,13 @@ exit_code: 0π [36mExecuting (post-create):[0m[40m [0m echo 'Installing deps'+Installing depsπ [36mExecuting (post-create):[0m[40m [0m echo 'Running setup'+Running setupβ [32mCreated new worktree for [1mfeature[0m at [REPO].feature[0mTo enable automatic cd, run: wt configure-shell----- stderr ------Installing deps-Running setupdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snapindex c412b050f..4a12399e0 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpZMSoxL/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp8A1ot3/test-config.toml---success: trueexit_code: 0@@ -24,9 +24,9 @@ exit_code: 0π [36mExecuting (post-create):[0m[40m [0m echo 'Setup complete'+Setup completeβ [32mCreated new worktree for [1mfeature[0m at [REPO].feature[0mTo enable automatic cd, run: wt configure-shell----- stderr ------Setup complete