Skip to content

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

fix(output): don't panic when a --format=json consumer closes the pipe (#3746)

Maximilian Roos860fa02ecff9
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
index fc81bc6a5..1c40bb664 100644
--- a/src/commands/CLAUDE.md
+++ b/src/commands/CLAUDE.md
@@ -85,6 +85,8 @@ wt --source -C /path/to/repo switch
3. Add an `after_long_help` attribute — it is the source of truth for `docs/content/{command}.md`.
4. Run `cargo test --test integration test_docs_are_in_sync`. Editing help text also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept --test integration -- test_help` (or run the pre-merge hook, which does both).
+A `--format=json` mode prints its answer to stdout through anstream's `println!`, which drops a `BrokenPipe` write error where std's panics. `crate::output::print_json` is that printer for every surface but `wt switch --format=json`, which emits its single result as one compact line.
+
## Branch Argument Conventions
Every branch-name argument carries a completer (shell completion) and the
diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rs
index 9526d2774..9ffcdc78c 100644
--- a/src/commands/config/approvals.rs
+++ b/src/commands/config/approvals.rs
@@ -23,6 +23,7 @@ use crate::commands::command_approval::approve_command_batch;
use crate::commands::project_config::{
ApprovableCommand, collect_commands_for_aliases, collect_commands_for_hooks,
};
+use crate::output::print_json;
/// Every approvable command a project config declares: hooks in lifecycle
/// order, then aliases (alphabetical), then any commit-message guidance.
@@ -119,7 +120,7 @@ pub fn list_approvals(format: SwitchFormat) -> anyhow::Result<()> {
} else {
"approved"
};
- return crate::commands::list::print_json(&JsonApprovals {
+ return print_json(&JsonApprovals {
state,
commands: json_commands,
stale,
diff --git a/src/commands/config/hints.rs b/src/commands/config/hints.rs
index abdeedf17..2d473584e 100644
--- a/src/commands/config/hints.rs
+++ b/src/commands/config/hints.rs
@@ -7,6 +7,7 @@ use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message, println, success_message};
use crate::cli::SwitchFormat;
+use crate::output::print_json;
/// Handle the hints get command (list shown hints)
pub fn handle_hints_get(format: SwitchFormat) -> anyhow::Result<()> {
@@ -14,7 +15,7 @@ pub fn handle_hints_get(format: SwitchFormat) -> anyhow::Result<()> {
let hints = repo.list_shown_hints();
if format == SwitchFormat::Json {
- println!("{}", serde_json::to_string_pretty(&hints)?);
+ print_json(&hints)?;
} else if hints.is_empty() {
eprintln!("{}", info_message("No hints have been shown"));
} else {
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 3fe0df55c..558921074 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -30,6 +30,7 @@ use crate::commands::list::ci_status::CiToolsStatus;
use crate::help_pager::show_help_in_pager;
use crate::llm::test_commit_generation;
use crate::output;
+use crate::output::print_json;
/// Handle the config show command
pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()> {
@@ -157,7 +158,7 @@ fn handle_config_show_json() -> anyhow::Result<()> {
"exists": system_exists,
},
});
- worktrunk::styling::println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
Ok(())
}
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 6642a770b..93235f01b 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -84,6 +84,7 @@ use worktrunk::styling::{
};
use crate::cli::{OutputFormat, SwitchFormat};
+use crate::output::print_json;
use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};
use worktrunk::utils::epoch_now;
@@ -634,7 +635,7 @@ pub fn handle_logs_list(format: SwitchFormat) -> anyhow::Result<()> {
"hook_output": hook_output,
"diagnostic": diagnostic,
});
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
return Ok(());
}
@@ -689,7 +690,7 @@ pub fn handle_logs_profile(file: Option<PathBuf>, format: SwitchFormat) -> anyho
let profile = worktrunk::trace::Profile::from_entries(&entries);
if format == SwitchFormat::Json {
- println!("{}", serde_json::to_string_pretty(&profile)?);
+ print_json(&profile)?;
} else {
show_help_in_pager(&profile.render_text(&source), true);
}
@@ -746,7 +747,7 @@ pub fn handle_state_get(
}
None => serde_json::json!(null),
};
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
} else {
match repo.branch_marker(&branch_name) {
Some(marker) => println!("{marker}"),
@@ -811,7 +812,7 @@ pub fn handle_state_get(
ci_provider_override.as_deref(),
)
});
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
} else {
let ci_status = pr_status
.map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {
@@ -1300,7 +1301,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
"trash": trash,
});
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
Ok(())
}
@@ -1479,7 +1480,7 @@ fn handle_cache_get_json(repo: &Repository) -> anyhow::Result<()> {
"hints": repo.list_shown_hints(),
});
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
Ok(())
}
@@ -1690,7 +1691,7 @@ pub fn handle_vars_list(branch: Option<String>, format: SwitchFormat) -> anyhow:
.into_iter()
.map(|(k, v)| (k, serde_json::Value::String(v)))
.collect();
- println!("{}", serde_json::to_string_pretty(&obj)?);
+ print_json(&obj)?;
} else if entries.is_empty() {
eprintln!(
"{}",
diff --git a/src/commands/eval.rs b/src/commands/eval.rs
index 5981b84c5..8df9003e2 100644
--- a/src/commands/eval.rs
+++ b/src/commands/eval.rs
@@ -11,6 +11,7 @@ use worktrunk::styling::{eprintln, format_with_gutter, info_message, println, ve
use crate::cli::SwitchFormat;
use crate::commands::command_executor::{CommandContext, build_hook_context};
+use crate::output::print_json;
/// Template name reported in errors, the `-v` expansion view, and JSON output.
const EVAL_NAME: &str = "eval";
@@ -63,7 +64,7 @@ pub fn step_eval(template: &str, format: SwitchFormat) -> anyhow::Result<()> {
"template": template,
"result": result,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
}
}
Ok(())
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 052296a35..003433a92 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -37,6 +37,7 @@ use worktrunk::styling::{
use crate::commands::command_executor::{CommandContext, build_hook_context};
use crate::commands::worktree_display_name;
+use crate::output::print_json;
/// Run a command in each worktree sequentially.
///
@@ -150,7 +151,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
if let Some(signal) = interrupted {
if json_mode {
- println!("{}", serde_json::to_string_pretty(&json_results)?);
+ print_json(&json_results)?;
} else {
eprintln!();
eprintln!(
@@ -162,7 +163,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
}
if json_mode {
- println!("{}", serde_json::to_string_pretty(&json_results)?);
+ print_json(&json_results)?;
if failed.is_empty() {
return Ok(());
} else {
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 8763e49f7..593b7a10a 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -20,6 +20,8 @@ use worktrunk::styling::{
info_message, println, warning_message,
};
+use crate::output::print_json;
+
use super::command_approval::approve_hooks_filtered;
use super::command_executor::{
CommandContext, FailureStrategy, PreparedStep, prepare_steps, render_template_preview,
@@ -475,7 +477,7 @@ fn emit_hook_show_json(
}
}
- println!("{}", serde_json::to_string_pretty(&entries)?);
+ print_json(&entries)?;
Ok(())
}
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 0b51ba24c..c9b283c57 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -133,12 +133,13 @@ pub(crate) mod render;
// Layout is calculated in collect/mod.rs
use anstyle::Style;
-use anyhow::Context;
use model::{BranchScope, ItemKind, ListData, ListItem};
use progressive::RenderTarget;
use worktrunk::git::Repository;
use worktrunk::styling::INFO_SYMBOL;
+use crate::output::print_json;
+
// Re-export for statusline and other consumers
pub use collect::{CollectOptions, build_worktree_item, populate_item};
pub use model::StatuslineSegment;
@@ -192,13 +193,6 @@ pub fn handle_list(
Ok(())
}
-/// Serialize a JSON answer to stdout (pretty, one trailing newline).
-pub(crate) fn print_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {
- let json = serde_json::to_string_pretty(value).context("Failed to serialize to JSON")?;
- println!("{}", json);
- Ok(())
-}
-
/// Resolve `[list] json-schema` (per-project resolved config) to 1 or 2.
///
/// Unset defaults to schema 1 and nags once per process; an out-of-range
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index e96890878..d0cf5346c 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -7,6 +7,8 @@ use worktrunk::config::{MergeConfig, UserConfig};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message};
+use crate::output::print_json;
+
use super::command_approval::approve_commit_template_append;
use super::command_executor::FailureStrategy;
use super::commit::{CommitOptions, HookGate};
@@ -462,7 +464,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
"rebased": rebased,
"removed": removed,
});
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
}
Ok(())
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index e7570f446..ff1023077 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -124,6 +124,8 @@ use worktrunk::git::{ErrorExt, Repository, current_or_recover};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{eprintln, error_message, hint_message, info_message, warning_message};
+use crate::output::print_json;
+
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::hooks::HookAnnouncer;
use super::list::collect;
@@ -2088,7 +2090,7 @@ pub fn handle_picker(
"rows": rows,
"entries": orchestrator.cache_entries_json(),
});
- println!("{}", serde_json::to_string_pretty(&dump)?);
+ print_json(&dump)?;
}
return Ok(());
}
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index d5cc858c1..abdfc39c3 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -11,7 +11,7 @@ use worktrunk::git::{BranchDeletionMode, ErrorExt, Repository, ResolvedWorktree}
use worktrunk::styling::{eprintln, info_message};
use crate::cli::{RemoveArgs, SwitchFormat};
-use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};
+use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output, print_json};
use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::hooks::HookAnnouncer;
@@ -365,7 +365,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
announcer.flush()?;
if json_mode {
let json = serde_json::json!([result.to_json(fate)]);
- println!("{}", serde_json::to_string_pretty(&json)?);
+ print_json(&json)?;
}
// Fire-and-forget repo-wide internal cleanup (stale trash +
// orphaned fsmonitor daemons) — runs after primary output so
@@ -447,7 +447,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
.zip(fates)
.map(|(removal, fate)| removal.to_json(fate))
.collect();
- println!("{}", serde_json::to_string_pretty(&json_items)?);
+ print_json(&json_items)?;
}
// Fire-and-forget repo-wide internal cleanup (stale trash +
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 4c225c69a..ecc32d4ed 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -31,6 +31,7 @@ use worktrunk::styling::{
use super::list::{self, CollectOptions, StatuslineSegment, json_output};
use crate::cli::StatuslineFormat;
+use crate::output::print_json;
/// Claude Code context parsed from stdin JSON
struct ClaudeCodeContext {
@@ -932,10 +933,9 @@ fn run_json() -> Result<()> {
// report, and resolving it here could reach the network on a
// fresh clone — this path runs on every prompt redraw.
let envelope = list::json_v2::envelope_with_items(&repo, None, collected, vec![]);
- list::print_json(&envelope)
+ print_json(&envelope)
} else {
- println!("[]");
- Ok(())
+ print_json(&serde_json::json!([]))
}
};
@@ -982,7 +982,7 @@ fn run_json() -> Result<()> {
);
let envelope =
list::json_v2::envelope_with_items(&repo, default_branch, collected, vec![json_item]);
- list::print_json(&envelope)
+ print_json(&envelope)
} else {
let repo_metadata = repo.repo_info();
let json_item = json_output::JsonItem::from_list_item(
@@ -992,7 +992,7 @@ fn run_json() -> Result<()> {
ci_provider_override.as_deref(),
&[],
);
- list::print_json(&[json_item])
+ print_json(&[json_item])
}
}
diff --git a/src/commands/step/copy_ignored.rs b/src/commands/step/copy_ignored.rs
index 419dcf133..440d5b821 100644
--- a/src/commands/step/copy_ignored.rs
+++ b/src/commands/step/copy_ignored.rs
@@ -13,6 +13,8 @@ use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, println, success_message, verbosity,
};
+use crate::output::print_json;
+
use super::shared::{list_and_filter_ignored_entries, resolve_copy_ignored_config};
/// Handle `wt step copy-ignored` command
@@ -76,7 +78,7 @@ pub fn step_copy_ignored(
"files": 0,
"bytes": 0,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
} else {
eprintln!(
"{}",
@@ -108,7 +110,7 @@ pub fn step_copy_ignored(
"files": 0,
"bytes": 0,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
} else {
eprintln!(
"{}",
@@ -144,7 +146,7 @@ pub fn step_copy_ignored(
"files": 0,
"bytes": 0,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
} else {
eprintln!("{}", info_message("No matching files to copy"));
}
@@ -174,7 +176,7 @@ pub fn step_copy_ignored(
"to": dest_path,
"entries": entries,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
return Ok(());
}
let items: Vec<String> = entries_to_copy
@@ -286,7 +288,7 @@ pub fn step_copy_ignored(
"files": copied_count,
"bytes": copied_bytes,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
} else {
// Show summary
let file_word = if copied_count == 1 { "file" } else { "files" };
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 8575eda39..270e3c440 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -40,6 +40,8 @@ use worktrunk::styling::{
};
use worktrunk::trace::Span;
+use crate::output::print_json;
+
use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};
use super::super::hooks::HookAnnouncer;
use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};
@@ -799,7 +801,7 @@ fn render_dry_run(
})
})
.collect();
- println!("{}", serde_json::to_string_pretty(&items)?);
+ print_json(&items)?;
return Ok(());
}
@@ -1374,7 +1376,7 @@ pub fn step_prune(
})
})
.collect();
- println!("{}", serde_json::to_string_pretty(&items)?);
+ print_json(&items)?;
} else if removed.is_empty() {
if skipped_young.is_empty() && skipped_approval.is_empty() {
eprintln!("{}", info_message("No merged worktrees to remove"));
diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rs
index 9ff8f7faa..132c81eb7 100644
--- a/src/commands/step/relocate.rs
+++ b/src/commands/step/relocate.rs
@@ -6,7 +6,8 @@ use std::path::PathBuf;
use worktrunk::config::UserConfig;
use worktrunk::git::Repository;
-use worktrunk::styling::println;
+
+use crate::output::print_json;
/// Move worktrees to their expected paths based on the `worktree-path` template.
///
@@ -188,6 +189,6 @@ fn print_relocate_json(
"reason": s.reason,
})).collect::<Vec<_>>(),
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
Ok(())
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 7f55a8b67..1d6edec06 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -27,8 +27,8 @@ use worktrunk::shell_exec::{
ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,
};
use worktrunk::styling::{
- eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,
- warning_message,
+ eprintln, format_with_gutter, hint_message, info_message, println, progress_message,
+ suggest_command, warning_message,
};
use super::resolve::{compute_worktree_path, offer_bare_repo_worktree_path_fix};
@@ -1315,6 +1315,11 @@ impl SwitchJsonOutput {
/// Emit the structured `--format=json` result to stdout when requested.
///
+/// One compact line rather than [`crate::output::print_json`]'s pretty form —
+/// a switch reports a single result, and a line is what a shell loop reads.
+/// The `println!` is anstream's for the same reason `print_json` uses it: a
+/// consumer that stops reading must not panic the command.
+///
/// A no-op for `SwitchFormat::Text`.
fn emit_switch_json(
format: SwitchFormat,
diff --git a/src/main.rs b/src/main.rs
index a94ae8360..4ebdbfdd2 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -35,6 +35,8 @@ pub(crate) use invocation::{
pub(crate) use crate::cli::{OutputFormat, StatuslineFormat};
+use crate::output::print_json;
+
use commands::commit::HookGate;
use commands::handle_picker;
use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
@@ -215,7 +217,7 @@ fn handle_step_command(
"message": outcome.message,
"stage_mode": outcome.stage_mode,
});
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
}
Ok(())
}
@@ -273,7 +275,7 @@ fn handle_step_command(
"outcome": "no_net_changes",
}),
};
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
} else {
match result {
SquashResult::Squashed { .. } | SquashResult::NoNetChanges => {}
@@ -327,7 +329,7 @@ fn handle_step_command(
if let PushOutcome::MergeCommit { merge_sha } = outcome {
payload["merge_sha"] = serde_json::Value::String(merge_sha);
}
- println!("{}", serde_json::to_string_pretty(&payload)?);
+ print_json(&payload)?;
}
Ok(())
}
@@ -347,7 +349,7 @@ fn handle_step_command(
"outcome": "up_to_date",
}),
};
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
} else if let RebaseResult::UpToDate(branch) = &result {
eprintln!(
"{}",
@@ -399,7 +401,7 @@ fn handle_step_command(
"branch": branch,
}),
};
- println!("{}", serde_json::to_string_pretty(&output)?);
+ print_json(&output)?;
} else if let commands::PromoteResult::AlreadyInMain(branch) = &result {
eprintln!(
"{}",
diff --git a/src/output/json.rs b/src/output/json.rs
new file mode 100644
index 000000000..8593f7bcf
--- /dev/null
+++ b/src/output/json.rs
@@ -0,0 +1,15 @@
+//! Machine-readable output for commands with a `--format=json` mode.
+
+use anyhow::Context;
+use worktrunk::styling::println;
+
+/// Serialize a JSON answer to stdout (pretty, one trailing newline).
+///
+/// Prints through anstream's `println!`, which drops a `BrokenPipe` write
+/// error where std's panics — a consumer that stops reading (`wt … | head`)
+/// must not fail the command.
+pub(crate) fn print_json<T: serde::Serialize>(value: &T) -> anyhow::Result<()> {
+ let json = serde_json::to_string_pretty(value).context("Failed to serialize to JSON")?;
+ println!("{}", json);
+ Ok(())
+}
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 084ce73ae..41617b974 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -3,8 +3,9 @@
//! # Architecture
//!
//! For regular output, use `eprintln!`/`println!` directly (from `worktrunk::styling`
-//! for color support). This module handles shell integration directives (cd, exec)
-//! that need to be communicated to the parent shell.
+//! for color support); [`print_json`] serializes a `--format=json` answer to stdout.
+//! This module handles shell integration directives (cd, exec) that need to be
+//! communicated to the parent shell.
//!
//! ## Usage
//!
@@ -32,6 +33,7 @@ pub(crate) mod commit_generation;
pub(crate) mod concurrent;
mod global;
pub(crate) mod handlers;
+mod json;
pub(crate) mod prompt;
pub(crate) mod shell_integration;
@@ -55,3 +57,5 @@ pub(crate) use shell_integration::{
};
// Re-export commit generation functions
pub(crate) use commit_generation::prompt_commit_generation;
+// Re-export the JSON answer printer
+pub(crate) use json::print_json;
diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rs
index 9508cee38..11d42043d 100644
--- a/tests/integration_tests/for_each.rs
+++ b/tests/integration_tests/for_each.rs
@@ -252,6 +252,46 @@ fn test_for_each_aborts_on_signal_exit(repo: TestRepo) {
);
}
+/// An interrupted `--format=json` run still owes its consumer the results it
+/// collected before the signal: the machine-readable answer is emitted on the
+/// abort path too, not just on the completing one. Same in-child SIGTERM as
+/// the test above, for the same reason.
+#[rstest]
+#[cfg(unix)]
+fn test_for_each_json_emitted_on_signal_abort(repo: TestRepo) {
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "for-each",
+ "--format=json",
+ "--",
+ "sh",
+ "-c",
+ "kill -TERM $$",
+ ])
+ .output()
+ .expect("run wt step for-each");
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(
+ output.status.code(),
+ Some(143),
+ "expected exit 143 (SIGTERM), got {:?}\nstderr: {stderr}",
+ output.status.code(),
+ );
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let json: serde_json::Value = serde_json::from_str(&stdout)
+ .unwrap_or_else(|e| panic!("interrupted run must still emit JSON: {e}\nstdout: {stdout}"));
+ let items = json.as_array().expect("results are an array");
+ assert_eq!(
+ items.len(),
+ 1,
+ "only the worktree visited before the signal is reported:\n{stdout}"
+ );
+}
+
/// for-each relocates the user's command into each worktree, so inherited
/// git-discovery vars (`GIT_DIR`/`GIT_WORK_TREE`) must be scrubbed — git
/// resolves them before walking up from the cwd, so a forwarded value would
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index 82ae5ad6e..5547338e9 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -31,16 +31,12 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"statusline.rs",
// Table and summary output for wt list
"list/collect/mod.rs",
- // JSON output for wt list --format=json
- "list/mod.rs",
// State data output (branch names, previous worktree, etc.)
"config/state.rs",
// Hint list output
"config/hints.rs",
// Alias introspection output (show / dry-run), intended to be pipeable
"config/alias.rs",
- // Alias --help hint output (conventional `--help` destination)
- "alias.rs",
// Template evaluation output for scripting
"eval.rs",
// LLM prompt output for wt step commit --show-prompt and squash --show-prompt
@@ -50,27 +46,15 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"step/copy_ignored.rs",
// wt step prune dry-run plan (human preview + --format=json)
"step/prune.rs",
- // JSON output for wt step relocate --format=json
- "step/relocate.rs",
// wt step relocate dry-run human preview (show_dry_run_preview)
"relocate.rs",
// wt config shell install/uninstall --dry-run preview (the interactive
// `?` re-preview still goes to stderr)
"configure_shell.rs",
- // Dry-run cache inventory dump (WORKTRUNK_PICKER_DRY_RUN)
- "picker/mod.rs",
// JSON output for wt switch --format=json
"worktree/switch.rs",
- // JSON output for wt config show --format=json
- "config/show.rs",
// Migrated TOML output for wt config update --print (pipeable)
"config/update.rs",
- // JSON output for wt step for-each --format=json
- "for_each.rs",
- // JSON output for wt merge --format=json
- "merge.rs",
- // JSON output for wt remove --format=json
- "remove.rs",
// Hook listing for wt hook show (paged), and the wt hook --dry-run preview
"hook_commands.rs",
];
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index ecc085a6d..f1720e9e2 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -3750,6 +3750,41 @@ cleanup = "flyctl scale count 0"
// --format=json
// ============================================================================
+/// Removing the current worktree by omitting the branch takes a separate
+/// single-worktree path from the named removals above, with its own
+/// `--format=json` emission. The shape must match: one array, one item.
+///
+/// Removal stays backgrounded: `wt` runs with the doomed worktree as its cwd,
+/// and Windows refuses to delete a directory a live process is sitting in, so
+/// `--foreground` would make this a Windows-only failure. The JSON is emitted
+/// either way — the execution mode picks who deletes, not who reports.
+#[rstest]
+fn test_remove_json_current_worktree_no_args(mut repo: TestRepo) {
+ use crate::common::wait_for_worktree_removed;
+
+ repo.commit("initial");
+ let feature_wt = repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--format=json", "--yes"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+ assert!(output.status.success(), "remove should succeed:\n{stderr}");
+
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+ let items = json.as_array().unwrap();
+ assert_eq!(items.len(), 1, "one worktree removed, one item:\n{stderr}");
+ assert_eq!(items[0]["branch"], "feature");
+
+ wait_for_worktree_removed(&feature_wt);
+}
+
#[rstest]
fn test_remove_json(mut repo: TestRepo) {
repo.commit("initial");