Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Preserve JSON results and diagnostics on command failure (#4574)

Maximilian Roosf117827bd01e
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 0f5d5b58a..c242dbacf 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -9,7 +9,6 @@ use std::path::{Path, PathBuf};
use anyhow::Context;
use color_print::cformat;
-use serde::{Serialize, de::DeserializeOwned};
use worktrunk::config::{
ConfigError, ConfigFileKind, ConfigParseError, LoadError, ProjectConfig, UserConfig,
require_config_path, system_config_path,
@@ -22,7 +21,7 @@ use worktrunk::shell::{
};
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
- FormattedMessage, error_message, format_bash_with_gutter, format_heading, format_toml,
+ FormattedMessage, eprint, error_message, format_bash_with_gutter, format_heading, format_toml,
format_with_gutter, hint_message, info_message, warning_message,
};
@@ -144,17 +143,18 @@ pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()
Ok(())
}
-/// JSON retains the report on invalid input and signals failure by exit code.
+/// JSON retains the report on invalid input, with diagnostics on stderr and a failing exit code.
fn handle_config_show_json() -> anyhow::Result<()> {
let repo = Repository::current().ok();
let (merged_user_config, user_warnings) = UserConfig::load_with_warnings();
+ let mut diagnostics = String::new();
let mut invalid = user_warnings
.iter()
.any(|warning| matches!(warning, LoadError::Validation(_)));
let user_path = require_config_path()?;
let user_exists = user_path.exists();
let user_config = if user_exists {
- match read_user_config(&user_path) {
+ match read_user_config(&user_path, ConfigFileKind::User, &mut diagnostics) {
Some(_) => Some(serde_json::to_value(merged_user_config)?),
None => {
invalid = true;
@@ -165,53 +165,56 @@ fn handle_config_show_json() -> anyhow::Result<()> {
None
};
- let (project_path, project_exists, project_config, project_identifier) =
- if let Some(repo) = repo.as_ref() {
- let on_disk = repo.project_config_path()?;
- let object_store = match &on_disk {
- Some(path) if path.exists() => None,
- _ => repo.default_branch_project_config_content(),
- };
- let object_store_exists = object_store.is_some();
- let (path, config) = match &on_disk {
- Some(path) if path.exists() => {
- let config = read_json_config::<ProjectConfig>(path)?;
- (on_disk.clone(), config)
- }
- _ => match object_store {
- Some((contents, spec)) => {
- let config = parse_json_config::<ProjectConfig>(&contents)?;
- (Some(spec), config)
- }
- None => (on_disk.clone(), None),
- },
- };
- if (on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists)
- && config.is_none()
- {
- invalid = true;
+ let (project_path, project_exists, project_config, project_identifier) = if let Some(repo) =
+ repo.as_ref()
+ {
+ let on_disk = repo.project_config_path()?;
+ let object_store = match &on_disk {
+ Some(path) if path.exists() => None,
+ _ => repo.default_branch_project_config_content(),
+ };
+ let object_store_exists = object_store.is_some();
+ let (path, config) = match &on_disk {
+ Some(path) if path.exists() => {
+ let config = read_config_contents(path, ConfigFileKind::Project, &mut diagnostics)
+ .map(|contents| parse_project_config_json(&contents, path, &mut diagnostics))
+ .transpose()?
+ .flatten();
+ (on_disk.clone(), config)
}
- let identifier = repo.project_identifier().ok().map(|id| id.to_string());
- let exists = on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists;
- (path, exists, config, identifier)
- } else {
- (None, false, None, None)
+ _ => match object_store {
+ Some((contents, spec)) => {
+ let config = parse_project_config_json(&contents, &spec, &mut diagnostics)?;
+ (Some(spec), config)
+ }
+ None => (on_disk.clone(), None),
+ },
};
+ if (on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists)
+ && config.is_none()
+ {
+ invalid = true;
+ }
+ let identifier = repo.project_identifier().ok().map(|id| id.to_string());
+ let exists = on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists;
+ (path, exists, config, identifier)
+ } else {
+ (None, false, None, None)
+ };
let system_path = system_config_path();
let system_exists = system_path.as_ref().is_some_and(|p| p.exists());
let system_invalid = if let Some(path) = system_path.as_deref().filter(|_| system_exists) {
- match std::fs::read_to_string(path) {
- Ok(contents) => parse_user_config(&contents, path, ConfigFileKind::System).is_err(),
- Err(_) => true,
- }
+ read_user_config(path, ConfigFileKind::System, &mut diagnostics).is_none()
} else {
false
};
- let approvals_invalid = matches!(
- approvals_diagnostic(repo.as_ref()),
- ApprovalsDiagnostic::Invalid(_)
- );
+ invalid |= system_invalid;
+ if let ApprovalsDiagnostic::Invalid(error) = approvals_diagnostic(repo.as_ref()) {
+ render_config_error(&mut diagnostics, error, "Invalid approvals");
+ invalid = true;
+ }
+ invalid |= render_column_selection(&mut diagnostics, repo.as_ref())?;
let output = serde_json::json!({
"user": {
@@ -233,12 +236,8 @@ fn handle_config_show_json() -> anyhow::Result<()> {
"exists": system_exists,
},
});
- invalid |= system_invalid
- || approvals_invalid
- || repo
- .as_ref()
- .is_some_and(|repo| validate_column_selection(repo).is_err());
print_json(&output)?;
+ eprint!("{diagnostics}");
if invalid {
return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());
@@ -247,19 +246,43 @@ fn handle_config_show_json() -> anyhow::Result<()> {
Ok(())
}
-fn read_json_config<C>(path: &Path) -> anyhow::Result<Option<serde_json::Value>>
-where
- C: DeserializeOwned + Serialize,
-{
- let Ok(contents) = std::fs::read_to_string(path) else {
- return Ok(None);
- };
- parse_json_config::<C>(&contents)
+fn read_config_contents(
+ path: &Path,
+ kind: ConfigFileKind,
+ diagnostics: &mut String,
+) -> Option<String> {
+ match std::fs::read_to_string(path) {
+ Ok(contents) => Some(contents),
+ Err(error) => {
+ let source = format!("{} @ {}", kind.label(), format_path_for_display(path));
+ let _ = writeln!(diagnostics, "{}", format_heading(&source, None));
+ render_config_read_error(diagnostics, &error);
+ None
+ }
+ }
}
-fn read_user_config(path: &Path) -> Option<UserConfig> {
- let contents = std::fs::read_to_string(path).ok()?;
- parse_user_config(&contents, path, ConfigFileKind::User).ok()
+fn read_user_config(
+ path: &Path,
+ kind: ConfigFileKind,
+ diagnostics: &mut String,
+) -> Option<UserConfig> {
+ let contents = read_config_contents(path, kind, diagnostics)?;
+ match parse_user_config(&contents, path, kind) {
+ Ok(config) => Some(config),
+ // Startup's user-config preload already reports parser failures for
+ // both file layers, including outside a repository.
+ Err(ConfigError::Parse(_)) => None,
+ Err(error) => {
+ let fallback = format!(
+ "{} @ {} is invalid",
+ kind.label(),
+ format_path_for_display(path)
+ );
+ render_config_error(diagnostics, error, &fallback);
+ None
+ }
+ }
}
fn parse_user_config(
@@ -274,15 +297,23 @@ fn parse_user_config(
Ok(config)
}
-fn parse_json_config<C>(contents: &str) -> anyhow::Result<Option<serde_json::Value>>
-where
- C: DeserializeOwned + Serialize,
-{
+fn parse_project_config_json(
+ contents: &str,
+ path: &Path,
+ diagnostics: &mut String,
+) -> anyhow::Result<Option<serde_json::Value>> {
let migrated = worktrunk::config::migrate_content(contents);
- toml::from_str::<C>(&migrated)
- .ok()
- .map(|config| serde_json::to_value(config).map_err(Into::into))
- .transpose()
+ match toml::from_str::<ProjectConfig>(&migrated) {
+ Ok(config) => Ok(Some(serde_json::to_value(config)?)),
+ Err(error) => {
+ render_config_error(
+ diagnostics,
+ ConfigError::Parse(ConfigParseError::new(ConfigFileKind::Project, path, error)),
+ "Invalid project config",
+ );
+ Ok(None)
+ }
+ }
}
// ==================== Helper Functions ====================
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 8a6b77c09..36651fc09 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -43,7 +43,8 @@ use crate::output::print_json;
/// Run a command in each worktree sequentially.
///
/// Executes the given argv directly in every worktree, streaming output in
-/// real-time. Continues on errors and reports a summary at the end.
+/// real-time. Preparation and child failures belong to each worktree; later
+/// worktrees still run. Interruptions stop the loop and retain visited results.
///
/// All template variables from hooks are available; values are substituted
/// into argv elements without shell escaping. Context JSON is provided on stdin.
@@ -73,25 +74,25 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
progress_message(format!("Running in {display_name}..."))
);
- // Build full hook context for this worktree
- // Pass wt.branch directly (not the display string) so a detached
- // worktree maps to None and leaves `{{ branch }}` unset
- let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);
- let context_map = build_hook_context(&ctx, &[], VarScope::All)?;
-
- // Expand each argv element through the template engine without
- // shell-escaping — values are interpolated directly into the argv
- // element a program receives, not through `sh -c`.
- let expanded: Vec<String> = args
- .iter()
- .map(|arg| {
- context_map.expand(arg, ShellEscapeMode::Literal, &repo, "for-each argument")
- })
- .collect::<Result<_, _>>()?;
-
- let context_json = context_map.to_json();
-
- match run_argv(&wt.path, expanded, &context_json) {
+ let result = (|| {
+ // Pass the branch, not its display name: a detached worktree
+ // leaves `{{ branch }}` unset.
+ let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);
+ let context_map = build_hook_context(&ctx, &[], VarScope::All)?;
+
+ // Expand argv literally: the program receives each element
+ // directly, without shell parsing.
+ let expanded: Vec<String> = args
+ .iter()
+ .map(|arg| {
+ context_map.expand(arg, ShellEscapeMode::Literal, &repo, "for-each argument")
+ })
+ .collect::<Result<_, _>>()?;
+
+ run_argv(&wt.path, expanded, &context_map.to_json())
+ })();
+
+ match result {
Ok(()) => {
if json_mode {
json_results.push(serde_json::json!({
@@ -120,12 +121,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
} else {
let detail = err.display_message();
let styled = err.render_diagnostic().unwrap_or_else(|| detail.clone());
- (
- " (spawn failed)".to_string(),
- serde_json::json!(null),
- Some(styled),
- detail,
- )
+ (String::new(), serde_json::json!(null), Some(styled), detail)
};
eprintln!(
"{}",
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index f9ef49d2c..a8b7a5195 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -2,7 +2,8 @@
//! dispatch each removal to the output handler.
//!
//! Target failures are reported independently; later targets still run and
-//! the batch exits unsuccessfully. An interrupt cancels the batch immediately.
+//! the batch exits unsuccessfully. An interrupt cancels the batch immediately,
+//! retaining completed removals in the JSON report.
use crate::commands::command_executor::ForegroundStdin;
@@ -512,6 +513,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
};
let mut failed = !plans.errors.is_empty();
let mut json_items = Vec::new();
+ let mut interrupted = None;
for result in all_plans() {
match run(result) {
Ok(fate) => {
@@ -521,7 +523,8 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
}
Err(e) => {
if let Some(signal) = e.interrupt_signal() {
- return Err(WorktrunkError::Interrupted { signal, hint: None }.into());
+ interrupted = Some(signal);
+ break;
}
crate::print_command_error(&e);
failed = true;
@@ -532,6 +535,9 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
if json_mode {
print_json(&json_items)?;
}
+ if let Some(signal) = interrupted {
+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());
+ }
// Fire-and-forget repo-wide internal cleanup (stale trash +
// orphaned fsmonitor daemons) — runs after primary output so
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 57dcda35c..4de4d61eb 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -7336,6 +7336,9 @@ fn test_config_show_rejects_semantically_invalid_user_config(
assert_eq!(output.status.code(), Some(1));
if args.contains(&"--format=json") {
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("User config @"), "{stderr}");
+ assert!(stderr.contains("worktree-path cannot be empty"), "{stderr}");
} else {
let stdout = String::from_utf8_lossy(&output.stdout);
let user_section = stdout
@@ -7373,6 +7376,9 @@ fn test_config_show_rejects_semantically_invalid_system_config(
assert_eq!(output.status.code(), Some(1));
if args.contains(&"--format=json") {
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("System config @"), "{stderr}");
+ assert!(stderr.contains("worktree-path cannot be empty"), "{stderr}");
return;
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -7428,13 +7434,12 @@ fn test_config_show_json_rejects_invalid_custom_column(repo: TestRepo, temp_home
let output = cmd.output().unwrap();
assert_eq!(output.status.code(), Some(1));
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
- assert!(output.stderr.is_empty());
+ insta::assert_snapshot!(String::from_utf8_lossy(&output.stderr).ansi_strip(), @"✗ Invalid [list.custom-columns.ticket] width: must be at least 1");
}
#[rstest]
fn test_config_show_json_rejects_invalid_system_config(repo: TestRepo, temp_home: TempDir) {
- let system_config_dir = tempfile::tempdir().unwrap();
- let system_config_path = system_config_dir.path().join("config.toml");
+ let system_config_path = repo.root_path().join("system-config.toml");
fs::write(&system_config_path, "invalid = [toml\n").unwrap();
let global_config_dir = temp_home.path().join(".config").join("worktrunk");
fs::create_dir_all(&global_config_dir).unwrap();
@@ -7456,6 +7461,22 @@ fn test_config_show_json_rejects_invalid_system_config(repo: TestRepo, temp_home
json["user"]["config"].is_object(),
"a broken system source must not erase valid user config"
);
+ let mut settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ crate::common::add_path_placeholder_filter(
+ &mut settings,
+ r"_REPO_/system-config\.toml",
+ "[SYSTEM_CONFIG]",
+ );
+ settings.bind(|| {
+ insta::assert_snapshot!(String::from_utf8_lossy(&output.stderr).ansi_strip(), @"
+ ▲ System config @ [SYSTEM_CONFIG] failed to parse, skipping
+ TOML parse error at line 1, column 16
+ |
+ 1 | invalid = [toml
+ | ^
+ unclosed array, expected `]`
+ ");
+ });
}
#[rstest]
@@ -7474,6 +7495,9 @@ fn test_config_show_json_rejects_unreadable_system_config(repo: TestRepo, temp_h
assert_eq!(output.status.code(), Some(1));
let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
assert_eq!(json["system"]["exists"], true);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("System config @"), "{stderr}");
+ assert!(stderr.contains("Cannot read config"), "{stderr}");
}
#[rstest]
@@ -7488,6 +7512,16 @@ fn test_config_show_json_rejects_invalid_approvals_file(repo: TestRepo) {
assert_eq!(output.status.code(), Some(1));
serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
+ setup_snapshot_settings(&repo).bind(|| {
+ insta::assert_snapshot!(String::from_utf8_lossy(&output.stderr).ansi_strip(), @"
+ ✗ Approvals @ [TEST_APPROVALS] failed to parse
+ TOML parse error at line 1, column 5
+ |
+ 1 | not valid TOML [[[
+ | ^
+ key with no value, expected `=`
+ ");
+ });
}
#[rstest]
@@ -7504,6 +7538,16 @@ fn test_config_show_json_rejects_invalid_user_config(repo: TestRepo) {
let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
assert_eq!(json["user"]["exists"], true);
assert!(json["user"]["config"].is_null());
+ setup_snapshot_settings(&repo).bind(|| {
+ insta::assert_snapshot!(String::from_utf8_lossy(&output.stderr).ansi_strip(), @"
+ ▲ User config @ [TEST_CONFIG] failed to parse, skipping
+ TOML parse error at line 1, column 16
+ |
+ 1 | invalid = [toml
+ | ^
+ unclosed array, expected `]`
+ ");
+ });
}
#[rstest]
@@ -7520,6 +7564,9 @@ fn test_config_show_json_rejects_unreadable_user_config(repo: TestRepo) {
let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
assert_eq!(json["user"]["exists"], true);
assert!(json["user"]["config"].is_null());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("User config @"), "{stderr}");
+ assert!(stderr.contains("Cannot read config"), "{stderr}");
}
#[rstest]
@@ -7536,6 +7583,16 @@ fn test_config_show_json_rejects_invalid_project_config(repo: TestRepo) {
let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
assert_eq!(json["project"]["exists"], true);
assert!(json["project"]["config"].is_null());
+ setup_snapshot_settings(&repo).bind(|| {
+ insta::assert_snapshot!(String::from_utf8_lossy(&output.stderr).ansi_strip(), @"
+ ✗ Project config @ _REPO_/.config/wt.toml failed to parse
+ TOML parse error at line 1, column 16
+ |
+ 1 | invalid = [toml
+ | ^
+ unclosed array, expected `]`
+ ");
+ });
}
#[rstest]
@@ -7553,6 +7610,9 @@ fn test_config_show_json_rejects_unreadable_project_config(repo: TestRepo) {
let json = serde_json::from_slice::<serde_json::Value>(&output.stdout).unwrap();
assert_eq!(json["project"]["exists"], true);
assert!(json["project"]["config"].is_null());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains("Project config @"), "{stderr}");
+ assert!(stderr.contains("Cannot read config"), "{stderr}");
}
#[rstest]
diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rs
index df94d86a8..2f2d64749 100644
--- a/tests/integration_tests/for_each.rs
+++ b/tests/integration_tests/for_each.rs
@@ -108,9 +108,8 @@ fn test_for_each_detached_branch_variable(mut repo: TestRepo) {
/// literal `HEAD` — a string git resolves as a ref, so the command ran against
/// the wrong thing instead of saying so.
#[rstest]
-fn test_for_each_detached_branch_variable_unguarded(mut repo: TestRepo) {
- repo.add_worktree("detached-test");
- repo.detach_head_in_worktree("detached-test");
+fn test_for_each_detached_branch_variable_unguarded(repo: TestRepo) {
+ repo.detach_head_in_worktree("feature-b");
assert_cmd_snapshot!(make_snapshot_cmd(
&repo,
@@ -120,6 +119,57 @@ fn test_for_each_detached_branch_variable_unguarded(mut repo: TestRepo) {
));
}
+/// Preparation failures belong to one worktree: retain earlier results and
+/// continue to the next worktree, just as for a child command failure.
+#[rstest]
+fn test_for_each_json_retains_results_after_template_failure(repo: TestRepo) {
+ repo.detach_head_in_worktree("feature-b");
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "for-each",
+ "--format=json",
+ "--",
+ "echo",
+ "{{ branch }}",
+ ])
+ .output()
+ .unwrap();
+
+ assert_eq!(output.status.code(), Some(1));
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ insta::assert_snapshot!(serde_json::to_string_pretty(&json).unwrap(), @r#"
+ [
+ {
+ "branch": "main",
+ "path": "_REPO_",
+ "exit_code": 0,
+ "success": true
+ },
+ {
+ "branch": "feature-a",
+ "path": "_REPO_.feature-a",
+ "exit_code": 0,
+ "success": true
+ },
+ {
+ "branch": null,
+ "path": "_REPO_.feature-b",
+ "exit_code": null,
+ "success": false,
+ "error": "Failed to expand for-each argument: undefined variable branch @ line 1"
+ },
+ {
+ "branch": "feature-c",
+ "path": "_REPO_.feature-c",
+ "exit_code": 0,
+ "success": true
+ }
+ ]
+ "#);
+}
+
#[rstest]
fn test_for_each_spawn_fails(mut repo: TestRepo) {
repo.add_worktree("feature");
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 35c91e868..b18118e9d 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1298,8 +1298,8 @@ fn test_remove_continues_after_execution_failures(
});
}
-/// Cancellation stops the batch before its next worktree. The hook signals
-/// its own shell, exercising child signal identity without signaling cargo.
+/// Cancellation retains completed removals in JSON and stops the batch before
+/// its next worktree. The hook signals its own shell, never the test process.
#[cfg(unix)]
#[rstest]
#[case::sigint("INT", 130)]
@@ -1309,14 +1309,23 @@ fn test_remove_interrupt_stops_batch(
#[case] signal: &str,
#[case] exit_code: i32,
) {
- let hook = format!("kill -{signal} $$");
+ let hook = format!("if [ '{{{{ branch }}}}' = interrupted ]; then kill -{signal} $$; fi");
repo.write_project_config(&format!("pre-remove = {hook:?}"));
repo.commit("Add interrupting pre-remove hook");
+ let completed = repo.add_worktree("completed");
let interrupted = repo.add_worktree("interrupted");
let later = repo.add_worktree("later");
let output = repo
.wt_command()
- .args(["remove", "interrupted", "later", "--foreground", "--yes"])
+ .args([
+ "remove",
+ "completed",
+ "interrupted",
+ "later",
+ "--foreground",
+ "--yes",
+ "--format=json",
+ ])
.output()
.unwrap();
assert_eq!(
@@ -1327,8 +1336,17 @@ fn test_remove_interrupt_stops_batch(
);
assert!(
interrupted.exists() && later.exists(),
- "interrupt must stop all removals"
+ "interrupt must stop the current and later removals"
);
+ assert!(
+ !completed.exists(),
+ "the earlier removal must have completed"
+ );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let items = json.as_array().unwrap();
+ assert_eq!(items.len(), 1, "{json}");
+ assert_eq!(items[0]["branch"], "completed");
+ assert_eq!(items[0]["path"], completed.to_string_lossy().as_ref());
}
/// Ctrl-C stops the batch even when the hook catches it and exits with an
@@ -1457,10 +1475,8 @@ exec {real_git} "$@"
Some(exit_code),
"stderr:\n{stderr}"
);
- assert!(
- output.stdout.is_empty(),
- "a canceled batch must not publish success JSON"
- );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json, serde_json::json!([]), "no removal completed: {json}");
}
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
index 248571bf1..0de98d722 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
@@ -64,7 +64,15 @@ exit_code: 1
----- stderr -----
◎ Running in main...
Branch: main
-◎ Running in _REPO_.detached-test (detached)...
-✗ Failed to expand for-each argument: undefined variable branch @ line 1
-  Branch: {{ branch }}
-↳ Available variables: commit, cwd, default_branch, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, worktree_name, worktree_path
+◎ Running in feature-a...
+Branch: feature-a
+◎ Running in _REPO_.feature-b (detached)...
+✗ Failed in _REPO_.feature-b (detached)
+  ✗ Failed to expand for-each argument: undefined variable branch @ line 1
+    Branch: {{ branch }}
+  ↳ Available variables: commit, cwd, default_branch, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, worktree_name, worktree_path
+◎ Running in feature-c...
+Branch: feature-c
+
+▲ 1 of 4 worktrees failed
+  _REPO_.feature-b (detached)
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap
index f8590f2ec..748d23396 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_spawn_fails.snap
@@ -63,19 +63,19 @@ exit_code: 1
----- stderr -----
◎ Running in main...
-✗ Failed in main (spawn failed)
+✗ Failed in main
  Failed to execute nonexistent-command-12345 @ ~/repo: [SPAWN_FAIL]
◎ Running in feature...
-✗ Failed in feature (spawn failed)
+✗ Failed in feature
  Failed to execute nonexistent-command-12345 @ ~/repo.feature: [SPAWN_FAIL]
◎ Running in feature-a...
-✗ Failed in feature-a (spawn failed)
+✗ Failed in feature-a
  Failed to execute nonexistent-command-12345 @ ~/repo.feature-a: [SPAWN_FAIL]
◎ Running in feature-b...
-✗ Failed in feature-b (spawn failed)
+✗ Failed in feature-b
  Failed to execute nonexistent-command-12345 @ ~/repo.feature-b: [SPAWN_FAIL]
◎ Running in feature-c...
-✗ Failed in feature-c (spawn failed)
+✗ Failed in feature-c
  Failed to execute nonexistent-command-12345 @ ~/repo.feature-c: [SPAWN_FAIL]
▲ 5 of 5 worktrees failed