Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(for-each): abort loop on signal-derived child exit (#2174)
Maximilian Roos00c41895f27f
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 09d770267..8659c33fe 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -521,7 +521,9 @@ fn handle_command_error() -> anyhow::Result<()> {let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {match wt_err {- WorktrunkError::ChildProcessExited { message, code } => (message.clone(), Some(*code)),+ WorktrunkError::ChildProcessExited { message, code, .. } => {+ (message.clone(), Some(*code))+ }_ => (err.to_string(), None),}} else {@@ -695,6 +697,7 @@ mod tests {let err: anyhow::Error = WorktrunkError::ChildProcessExited {code: 42,message: "command failed".into(),+ signal: None,}.into();let cmd = make_cmd(Some("lint"));@@ -763,6 +766,7 @@ mod tests {let err: anyhow::Error = WorktrunkError::ChildProcessExited {code: 1,message: "exit 1".into(),+ signal: None,}.into();let cmd = make_cmd(None);@@ -796,6 +800,7 @@ mod tests {let err: anyhow::Error = WorktrunkError::ChildProcessExited {code: 1,message: "lint failed".into(),+ signal: None,}.into();let cmd = make_cmd(Some("lint"));diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex b6de2b963..4c5071fab 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -53,6 +53,10 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anylet mut failed: Vec<String> = Vec::new();let mut json_results: Vec<serde_json::Value> = Vec::new();+ // Set when a child dies from a signal (Ctrl-C / SIGTERM). We abort the+ // loop and propagate an equivalent exit code rather than visiting the+ // remaining worktrees — the user asked for the work to stop.+ let mut interrupted: Option<i32> = None;let total = worktrees.len();// Join args into a template string (will be expanded per-worktree)@@ -100,11 +104,15 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any}}Err(err) => {- let (exit_info, exit_code, error_msg, show_detail) =- if let Some(WorktrunkError::ChildProcessExited { code, message }) =- err.downcast_ref::<WorktrunkError>()+ let (signal, exit_info, exit_code, error_msg, show_detail) =+ if let Some(WorktrunkError::ChildProcessExited {+ code,+ message,+ signal,+ }) = err.downcast_ref::<WorktrunkError>(){(+ *signal,format!(" (exit code {code})"),serde_json::json!(code),message.clone(),@@ -113,6 +121,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any} else {let msg = err.to_string();(+ None," (spawn failed)".to_string(),serde_json::json!(null),msg,@@ -136,10 +145,27 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any"error": error_msg,}));}+ if let Some(sig) = signal {+ interrupted = Some(128 + sig);+ break;+ }}}}+ if let Some(exit_code) = interrupted {+ if json_mode {+ println!("{}", serde_json::to_string_pretty(&json_results)?);+ } else {+ eprintln!();+ eprintln!(+ "{}",+ warning_message("Interrupted — skipped remaining worktrees")+ );+ }+ return Err(WorktrunkError::AlreadyDisplayed { exit_code }.into());+ }+if json_mode {println!("{}", serde_json::to_string_pretty(&json_results)?);if failed.is_empty() {diff --git a/src/git/error.rs b/src/git/error.rsindex 2ef30e747..f9dbb25b8 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -935,8 +935,17 @@ impl std::fmt::Display for GitError {/// for cases that need exit code extraction or special handling.#[derive(Debug)]pub enum WorktrunkError {- /// Child process exited with non-zero code (preserves exit code for signals)- ChildProcessExited { code: i32, message: String },+ /// Child process exited with non-zero code (preserves exit code for signals).+ ///+ /// `signal` is `Some(sig)` when the process was terminated by a signal+ /// (on Unix), `None` for a normal non-zero exit. Callers that must treat+ /// interrupts differently from ordinary failures (e.g., aborting a loop+ /// on Ctrl-C) check `signal` rather than inferring from `code`.+ ChildProcessExited {+ code: i32,+ message: String,+ signal: Option<i32>,+ },/// Hook command failedHookCommandFailed {hook_type: HookType,@@ -1131,6 +1140,7 @@ mod tests {let err: anyhow::Error = WorktrunkError::ChildProcessExited {code: 42,message: "test".into(),+ signal: None,}.into();assert_eq!(exit_code(&err), Some(42));@@ -1209,6 +1219,7 @@ mod tests {let err: anyhow::Error = WorktrunkError::ChildProcessExited {code: 1,message: "test".into(),+ signal: None,}.into();assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));@@ -1241,6 +1252,7 @@ mod tests {let err = WorktrunkError::ChildProcessExited {code: 1,message: "Command failed".into(),+ signal: None,};assert_snapshot!(err.to_string(), @"[31m✗[39m [31mCommand failed[39m");diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 50e574349..4cd7459a1 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -361,6 +361,7 @@ fn collect_outcome(spawned: SpawnedChild, cmd: &ConcurrentCommand<'_>) -> anyhowErr(WorktrunkError::ChildProcessExited {code: 128 + sig,message: format!("terminated by signal {sig}"),+ signal: Some(sig),}.into())} else {@@ -368,6 +369,7 @@ fn collect_outcome(spawned: SpawnedChild, cmd: &ConcurrentCommand<'_>) -> anyhowErr(WorktrunkError::ChildProcessExited {code,message: format!("exit status: {code}"),+ signal: None,}.into())}diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 81976e0e6..a1f891c56 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -1185,6 +1185,7 @@ impl Cmd {return Err(WorktrunkError::ChildProcessExited {code: 128 + sig,message: format!("terminated by signal {}", sig),+ signal: Some(sig),}.into());}@@ -1201,6 +1202,7 @@ impl Cmd {return Err(WorktrunkError::ChildProcessExited {code: 128 + sig,message: format!("terminated by signal {}", sig),+ signal: Some(sig),}.into());}@@ -1211,6 +1213,7 @@ impl Cmd {return Err(WorktrunkError::ChildProcessExited {code,message: format!("exit status: {}", code),+ signal: None,}.into());}diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex cf3970147..9b99f9840 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -156,6 +156,66 @@ fn test_for_each_json_spawn_failure(repo: TestRepo) {}}+/// Signal-derived exit (Ctrl-C, SIGTERM) in a child must abort the loop+/// rather than continuing into the remaining worktrees. Simulated here with+/// a command that self-signals via SIGTERM — this drives the same+/// `ChildProcessExited { signal: Some(_), .. }` path as a real Ctrl-C against+/// the wt process. Sending SIGINT to the parent wt process from an integration+/// test is impractical (it would kill the test harness), so we cover the+/// signal-detection branch via an equivalent in-child signal.+#[rstest]+#[cfg(unix)]+fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {+ // The standard fixture already includes main + feature-{a,b,c} worktrees,+ // so we just need the command to abort on the first visit.++ // A marker file per visited worktree lets us assert that the loop stopped+ // after the first signal. for-each joins the post-`--` args with spaces+ // and runs the result through `sh -c`; we pass shell fragments that+ // touch a marker and then self-signal with SIGTERM.+ let marker_dir = tempfile::tempdir().expect("create marker tmpdir");+ let marker_path = marker_dir.path().to_string_lossy().to_string();++ let touch_cmd = format!("touch {marker_path}/$(basename \"$(pwd)\")");++ let output = repo+ .wt_command()+ .args([+ "step", "for-each", "--", &touch_cmd, "&&", "kill", "-TERM", "$$",+ ])+ .output()+ .expect("run wt step for-each");++ // Exit code: 128 + SIGTERM (15) = 143+ assert_eq!(+ output.status.code(),+ Some(143),+ "expected exit 143 (SIGTERM), got {:?}\nstderr: {}",+ output.status.code(),+ String::from_utf8_lossy(&output.stderr),+ );++ // Exactly one marker file should exist — the remaining worktrees must+ // not have been visited after the signal aborted the loop.+ let markers: Vec<_> = std::fs::read_dir(marker_dir.path())+ .expect("read marker dir")+ .filter_map(Result::ok)+ .collect();+ assert_eq!(+ markers.len(),+ 1,+ "expected exactly one worktree visited before abort, got {}: stderr={}",+ markers.len(),+ String::from_utf8_lossy(&output.stderr),+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("Interrupted"),+ "expected 'Interrupted' message in stderr, got: {stderr}"+ );+}+#[rstest]fn test_for_each_skips_prunable_worktrees(mut repo: TestRepo) {let worktree_path = repo.add_worktree("feature");