Skip to content

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

fix: return one complete JSON result for switch (#4345)

Maximilian Roos93beb0670d90
diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.md
index a492b34a2..5250d9c69 100644
--- a/docs/src/content/docs/switch.md
+++ b/docs/src/content/docs/switch.md
@@ -289,8 +289,12 @@ Automation:
--format <FORMAT>
Output format
- JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code
- WorktreeCreate hooks).
+ JSON prints one structured result to stdout once the switch, including any --execute
+ command, completes. Once arguments are accepted, failures print an object with an error
+ string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A
+ worktree created before a later failure remains in place. Canceling the interactive picker
+ produces no result. Background hooks run independently of the result. Designed for tool
+ integration (e.g., Claude Code WorktreeCreate hooks).
[default: text]
[possible values: text, json]
diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.md
index fe2a4519f..28b4fc041 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md
@@ -259,8 +259,12 @@ Automation:
--format <FORMAT>
Output format
- JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code
- WorktreeCreate hooks).
+ JSON prints one structured result to stdout once the switch, including any --execute
+ command, completes. Once arguments are accepted, failures print an object with an error
+ string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A
+ worktree created before a later failure remains in place. Canceling the interactive picker
+ produces no result. Background hooks run independently of the result. Designed for tool
+ integration (e.g., Claude Code WorktreeCreate hooks).
[default: text]
[possible values: text, json]
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index fe2a4519f..28b4fc041 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -259,8 +259,12 @@ Automation:
--format <FORMAT>
Output format
- JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code
- WorktreeCreate hooks).
+ JSON prints one structured result to stdout once the switch, including any --execute
+ command, completes. Once arguments are accepted, failures print an object with an error
+ string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A
+ worktree created before a later failure remains in place. Canceling the interactive picker
+ produces no result. Background hooks run independently of the result. Designed for tool
+ integration (e.g., Claude Code WorktreeCreate hooks).
[default: text]
[possible values: text, json]
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 38104cfe9..87d905e3d 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -461,8 +461,15 @@ pub(crate) struct SwitchArgs {
/// Output format
///
- /// JSON prints structured result to stdout. Designed for tool
- /// integration (e.g., Claude Code WorktreeCreate hooks).
+ /// JSON prints one structured result to stdout once the switch, including
+ /// any --execute command, completes.
+ /// Once arguments are accepted, failures print an object with an `error`
+ /// string. Argument errors use stderr only. Diagnostics and
+ /// --execute output go to stderr. A worktree created before a later failure
+ /// remains in place.
+ /// Canceling the interactive picker produces no result.
+ /// Background hooks run independently of the result.
+ /// Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).
#[arg(long, default_value = "text", help_heading = "Automation")]
pub(crate) format: SwitchFormat,
}
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index b7b821e3e..efbd69ea9 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -91,8 +91,8 @@ mod types;
pub use finish::{FinishAfterMergeArgs, finish_after_merge};
pub use push::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
pub use resolve::{compute_worktree_path, is_worktree_at_expected_path, worktree_display_name};
-pub(crate) use switch::SwitchPipeline;
pub use switch::handle_switch_command;
+pub(crate) use switch::{SwitchPipeline, print_switch_json_error};
pub use types::{
BranchFate, MergeOperations, RemovalPlan, RetainedReason, SharedBranchCheckout,
SwitchBranchInfo, SwitchResult,
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 541399eb7..883fa404a 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -7,6 +7,7 @@
use std::path::{Path, PathBuf};
use crate::display::format_relative_time_short;
+use ansi_str::AnsiStr as _;
use anyhow::{Context, bail};
use color_print::cformat;
use dunce::canonicalize;
@@ -1589,7 +1590,7 @@ impl SwitchJsonOutput {
}
}
-/// Emit the structured `--format=json` result to stdout when requested.
+/// Emit the structured `--format=json` result after synchronous work succeeds.
///
/// 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.
@@ -1611,6 +1612,13 @@ fn emit_switch_json(
Ok(())
}
+/// Emit the single failure result for a parsed JSON switch invocation.
+/// Main owns the failure boundary, including errors before pipeline creation.
+pub(crate) fn print_switch_json_error(message: &str) {
+ let payload = serde_json::json!({ "error": message.ansi_strip() });
+ println!("{payload}");
+}
+
/// Options for the switch command
struct SwitchOptions<'a> {
branch: &'a str,
@@ -1839,8 +1847,8 @@ fn capture_switch_source(repo: &Repository, is_recovered: bool) -> (String, Stri
/// else runs in [`SwitchPipeline::run`] — target resolution, the bare-repo
/// path-fix offer, pre-switch hooks, source-identity capture, `plan_switch` →
/// `approve_switch_hooks` → `validate_switch_templates` → `execute_switch` →
-/// output → background hooks → `--execute`. One sequence, so the two entry
-/// points cannot drift. In particular the single `verify` / `yes` pair gates
+/// output → background hooks → `--execute` → JSON result. One sequence, so the
+/// two entry points cannot drift. In particular the single `verify` / `yes` pair gates
/// every hook, so the picker and the argument path cannot diverge on hook
/// approval — the picker once auto-approved `pre-switch` hooks because it kept
/// its own copy of that call.
@@ -1991,14 +1999,9 @@ impl SwitchPipeline<'_> {
let (result, branch_info) =
execute_switch(repo, plan, config, yes, hooks_approved, &hook_plan)?;
- // --format=json: write structured result to stdout. All behavior
- // (hooks, --execute, shell integration) proceeds normally — format only
- // affects output.
- emit_switch_json(format, &result, &branch_info)?;
-
// Early exit for benchmarking time-to-first-output.
if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
- return Ok(());
+ return emit_switch_json(format, &result, &branch_info);
}
// Show success message (temporal locality: immediately after the
@@ -2120,10 +2123,14 @@ impl SwitchPipeline<'_> {
&argv,
display_paths.execute.as_deref(),
&display_paths.execute_dir,
+ format == SwitchFormat::Json,
)?;
}
- Ok(())
+ // Reserve stdout for one result after every fallible synchronous step.
+ // A late failure still leaves the worktree in place, but reports no
+ // success document. Detached hooks keep their independent lifecycle.
+ emit_switch_json(format, &result, &branch_info)
}
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 54a65f787..10f66efa3 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -2356,6 +2356,9 @@ mod tests {
}
.into();
assert_eq!(err.interrupt_signal(), Some(15));
+ let err = err.context(WorktrunkError::AlreadyDisplayed { exit_code: 143 });
+ assert_eq!(err.interrupt_signal(), Some(15));
+ assert_eq!(err.exit_code(), Some(143));
// An already-classified interrupt stays one (idempotence for loops
// that re-check errors bubbling through them).
diff --git a/src/help.rs b/src/help.rs
index c53426721..f548b1697 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -286,7 +286,7 @@ pub fn maybe_handle_help_with_pager(
// Page only when stdout is a TTY; redirected help stays on stdout.
// use_pager=false for -h (short help), true for --help (long help)
if let Err(error) = crate::help_pager::show_help_in_pager(&help, use_pager) {
- crate::handle_command_failure(error, 0, &args.join(" "));
+ crate::handle_command_failure(error, 0, &args.join(" "), false);
}
process::exit(0);
}
diff --git a/src/main.rs b/src/main.rs
index 3c8763606..3d57df0d4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -997,6 +997,15 @@ fn format_command_error(error: &anyhow::Error) -> String {
use std::fmt::Write;
let mut out = String::new();
+ // An AlreadyDisplayed context retains a child failure as its source for
+ // structured output, but its presentation marker still suppresses stderr.
+ if matches!(
+ error.downcast_ref::<WorktrunkError>(),
+ Some(WorktrunkError::AlreadyDisplayed { .. })
+ ) {
+ return out;
+ }
+
// Locate the first error in the chain that implements `Diagnostic`.
// Most typed errors render directly even when wrapped in
// `.context(...)`: their styled block is self-contained and the
@@ -1113,7 +1122,24 @@ fn finish_command(verbose_level: u8, command_line: &str, error: Option<&anyhow::
let _ = output::terminate_output();
}
-fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line: &str) -> ! {
+fn handle_command_failure(
+ error: anyhow::Error,
+ verbose_level: u8,
+ command_line: &str,
+ switch_json: bool,
+) -> ! {
+ if switch_json {
+ // The JSON error carries what stderr shows. A child failure shows
+ // nothing there (the child spoke for itself), so name its exit instead.
+ let message = match error.interrupt_signal() {
+ Some(signal) => format!("Interrupted by signal {signal}"),
+ None => match format_command_error(&error) {
+ rendered if rendered.is_empty() => error.root_cause().to_string(),
+ rendered => rendered.trim_end().to_string(),
+ },
+ };
+ commands::worktree::print_switch_json_error(&message);
+ }
print_command_error(&error);
print_cwd_removed_hint_if_needed();
@@ -1207,6 +1233,10 @@ fn main() {
yes,
command,
} = cli;
+ let switch_json = matches!(
+ command.as_ref(),
+ Some(Commands::Switch(args)) if args.format == SwitchFormat::Json
+ );
// `WORKTRUNK_VERBOSE` provides a baseline verbosity the `-v`/`-vv` flags
// raise but never lower (`max`). It also drives shell completion, which
// answers and returns above, before `parse_cli` — see
@@ -1264,7 +1294,7 @@ fn main() {
})
});
if let Some(Err(error)) = git_version_result {
- handle_command_failure(error, verbose, &command_line);
+ handle_command_failure(error, verbose, &command_line, switch_json);
}
{
@@ -1283,7 +1313,7 @@ fn main() {
#[cfg(unix)]
let operation = match worktrunk::signal_forwarder::CommandOperation::start() {
Ok(operation) => operation,
- Err(error) => handle_command_failure(error.into(), verbose, &command_line),
+ Err(error) => handle_command_failure(error.into(), verbose, &command_line, switch_json),
};
let result = dispatch_command(command, directory, yes);
#[cfg(unix)]
@@ -1294,7 +1324,7 @@ fn main() {
match result {
Ok(()) => finish_command(verbose, &command_line, None),
- Err(error) => handle_command_failure(error, verbose, &command_line),
+ Err(error) => handle_command_failure(error, verbose, &command_line, switch_json),
}
}
diff --git a/src/output/global.rs b/src/output/global.rs
index 789e5e740..8db35d931 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -338,7 +338,12 @@ pub(crate) fn format_exec_argv(argv: &[String]) -> String {
/// The caller names the directory rather than reading one the shell directive
/// left behind: the program goes where the switch pointed, whether or not the
/// user's shell follows it there.
-pub fn execute(argv: Vec<String>, dir: &Path) -> anyhow::Result<()> {
+/// JSON callers route stdout to stderr to keep their result stream separate.
+pub fn execute(
+ argv: Vec<String>,
+ dir: &Path,
+ redirect_stdout_to_stderr: bool,
+) -> anyhow::Result<()> {
if argv.first().is_none_or(String::is_empty) {
anyhow::bail!("--execute requires a non-empty program");
}
@@ -353,6 +358,11 @@ pub fn execute(argv: Vec<String>, dir: &Path) -> anyhow::Result<()> {
.hand_off_terminal()
.current_dir(dir)
.scrub_git_discovery_env();
+ let cmd = if redirect_stdout_to_stderr {
+ cmd.stdout(std::process::Stdio::from(std::io::stderr()))
+ } else {
+ cmd
+ };
#[cfg(unix)]
let cmd = cmd.propagate_sigpipe();
@@ -368,7 +378,10 @@ fn suppress_child_exit_message(result: anyhow::Result<()>) -> anyhow::Result<()>
if let Some(WorktrunkError::ChildProcessExited { code, .. }) =
err.downcast_ref::<WorktrunkError>()
{
- return Err(WorktrunkError::AlreadyDisplayed { exit_code: *code }.into());
+ let exit_code = *code;
+ // Retain the typed child failure for structured output while the
+ // context marker keeps the normal stderr presentation silent.
+ return Err(err.context(WorktrunkError::AlreadyDisplayed { exit_code }));
}
return Err(err);
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 465ed00a1..37456f3e6 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1166,6 +1166,7 @@ pub fn execute_user_command(
argv: &[String],
display_path: Option<&Path>,
dir: &Path,
+ redirect_stdout_to_stderr: bool,
) -> anyhow::Result<()> {
super::global::print_outdated_execute_wrapper_warning();
let command = super::global::format_exec_argv(argv);
@@ -1182,7 +1183,7 @@ pub fn execute_user_command(
eprintln!("{}", progress_message(header));
eprintln!("{}", format_bash_with_gutter(&command));
- super::execute(argv.to_vec(), dir)?;
+ super::execute(argv.to_vec(), dir, redirect_stdout_to_stderr)?;
Ok(())
}
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 0131ab26a..4dfa1673d 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -8784,6 +8784,304 @@ fn test_switch_format_json_already_at(mut repo: TestRepo) {
assert_eq!(json["branch"], "already-json");
}
+#[rstest]
+fn test_switch_format_json_failures_emit_one_error(repo: TestRepo) {
+ let early = repo
+ .wt_command()
+ .args([
+ "switch",
+ "missing-json",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ ])
+ .output()
+ .unwrap();
+ assert!(!early.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&early.stdout).unwrap();
+ assert_eq!(json.as_object().unwrap().len(), 1);
+ insta::assert_snapshot!(json["error"].as_str().expect("error is a plain string"), @"
+ ✗ No branch named missing-json
+ ↳ To create a new branch, run wt switch --create missing-json; to list branches, run wt list --branches --remotes
+ ");
+ assert!(!early.stderr.is_empty());
+
+ // An invalid branch name is rejected before any worktree is created.
+ let rejected = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "bad..name",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ ])
+ .output()
+ .unwrap();
+ assert!(!rejected.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&rejected.stdout).unwrap();
+ let error = json["error"].as_str().expect("error is a plain string");
+ assert!(
+ error.contains("Invalid branch name bad..name"),
+ "JSON must retain the rejection reason: {error}"
+ );
+ assert_eq!(error, error.ansi_strip());
+ assert!(String::from_utf8_lossy(&rejected.stderr).contains("Invalid branch name"));
+
+ // The worktree is created before --execute fails. The result must describe
+ // the whole synchronous command, rather than reporting success too early.
+ let late = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "failed-json",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ "--execute=sh",
+ "--",
+ "-c",
+ "echo child-output; exit 7",
+ ])
+ .output()
+ .unwrap();
+ assert_eq!(late.status.code(), Some(7));
+ let json: serde_json::Value = serde_json::from_slice(&late.stdout).unwrap();
+ assert_eq!(json, serde_json::json!({ "error": "exit code 7" }));
+ assert!(String::from_utf8_lossy(&late.stderr).contains("child-output"));
+ assert!(
+ repo.root_path()
+ .parent()
+ .unwrap()
+ .join("repo.failed-json")
+ .is_dir()
+ );
+}
+
+#[rstest]
+fn test_switch_format_json_fetch_failure(#[from(repo_with_remote)] repo: TestRepo) {
+ let github_url = "https://github.com/owner/test-repo.git";
+ repo.run_git(&["remote", "set-url", "origin", github_url]);
+ // Redirect the URL to an absent local repository: exercise real Git
+ // failure without a network request or an external authentication state.
+ let missing = repo.root_path().join("missing-remote");
+ repo.run_git(&[
+ "config",
+ &format!("url.{}.insteadOf", missing.display()),
+ github_url,
+ ]);
+ let response = r#"{"title":"Missing branch","user":{"login":"owner"},"state":"open","draft":false,"head":{"ref":"missing-head","repo":{"name":"test-repo","owner":{"login":"owner"}}},"base":{"ref":"main","repo":{"name":"test-repo","owner":{"login":"owner"}}},"html_url":"https://github.com/owner/test-repo/pull/101"}"#;
+ let mock_bin = setup_mock_gh_for_pr(&repo, response);
+ let mut cmd = repo.wt_command();
+ cmd.args(["switch", "pr:101", "--format=json", "--no-cd", "--yes"]);
+ configure_mock_cli_env(&mut cmd, &mock_bin);
+ let output = cmd.output().unwrap();
+ assert!(!output.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let message = json["error"].as_str().unwrap();
+ assert!(
+ message.contains("does not appear to be a git repository"),
+ "{json}"
+ );
+ assert!(message.contains(missing.to_str().unwrap()), "{json}");
+ assert!(json.get("action").is_none());
+}
+
+#[rstest]
+fn test_switch_format_json_directive_failure_emits_one_error(repo: TestRepo) {
+ // The directory cannot be opened as a CD directive file. That write runs
+ // after the worktree has already been created.
+ let mut cmd = repo.wt_command();
+ configure_directive_file(&mut cmd, repo.root_path());
+ let output = cmd
+ .args([
+ "switch",
+ "--create",
+ "failed-directive-json",
+ "--format=json",
+ "--yes",
+ ])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let message = json["error"].as_str().unwrap();
+ assert!(
+ message.contains("Failed to write the cd directive file"),
+ "{message}"
+ );
+ assert!(message.contains(repo.root_path().to_str().unwrap()));
+ assert!(json.get("action").is_none());
+ assert!(
+ String::from_utf8_lossy(&output.stderr).contains("Failed to write the cd directive file")
+ );
+ assert!(
+ repo.root_path()
+ .parent()
+ .unwrap()
+ .join("repo.failed-directive-json")
+ .is_dir()
+ );
+}
+
+#[rstest]
+fn test_switch_format_json_early_validation_errors(repo: TestRepo) {
+ for args in [
+ vec!["switch", "main", "--format=json", "--base"],
+ vec!["switch", "main", "--oops", "--format=json"],
+ vec!["switch", "main", "--format=json", "--oops"],
+ ] {
+ let invalid_args = repo.wt_command().args(args).output().unwrap();
+ assert_eq!(invalid_args.status.code(), Some(2));
+ assert!(invalid_args.stdout.is_empty());
+ assert!(!invalid_args.stderr.is_empty());
+ }
+
+ // -C discovery fails before planning, with the requested JSON mode intact.
+ let missing_dir = repo.root_path().join("missing-cwd");
+ let invalid_cwd = repo
+ .wt_command()
+ .arg("-C")
+ .arg(&missing_dir)
+ .args(["switch", "main", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(!invalid_cwd.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&invalid_cwd.stdout).unwrap();
+ assert!(
+ json["error"]
+ .as_str()
+ .unwrap()
+ .contains("git rev-parse --git-common-dir"),
+ "JSON: {json}"
+ );
+
+ // A spawn failure must describe its producer, rather than expose only an
+ // AlreadyDisplayed marker or append an error after a success object.
+ let missing_program = repo
+ .wt_command()
+ .args([
+ "switch",
+ "main",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ "--execute=wt-json-missing-executable-14",
+ ])
+ .output()
+ .unwrap();
+ assert!(!missing_program.status.success());
+ let json: serde_json::Value = serde_json::from_slice(&missing_program.stdout).unwrap();
+ assert!(
+ json["error"]
+ .as_str()
+ .unwrap()
+ .contains("Failed to execute wt-json-missing-executable-14")
+ );
+}
+
+#[cfg(unix)]
+#[rstest]
+fn test_switch_format_json_execute_signal(repo: TestRepo) {
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "main",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ "--execute=sh",
+ "--",
+ "-c",
+ "kill -TERM $$",
+ ])
+ .output()
+ .unwrap();
+ assert_eq!(
+ std::os::unix::process::ExitStatusExt::signal(&output.status),
+ Some(15)
+ );
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(
+ json,
+ serde_json::json!({ "error": "Interrupted by signal 15" })
+ );
+
+ // Hook interruption has its own typed signal error whose terminal display
+ // is deliberately silent. JSON must still describe the actual signal.
+ repo.write_test_config("pre-switch = \"kill -INT $$\"\n");
+ let interrupted = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "interrupted-json",
+ "--format=json",
+ "--no-cd",
+ "--yes",
+ "--execute=sh",
+ "--",
+ "-c",
+ "echo should-not-run",
+ ])
+ .output()
+ .unwrap();
+ assert_eq!(
+ std::os::unix::process::ExitStatusExt::signal(&interrupted.status),
+ Some(2)
+ );
+ assert!(
+ !repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.interrupted-json")
+ .exists()
+ );
+ assert!(!String::from_utf8_lossy(&interrupted.stderr).contains("should-not-run"));
+ let json: serde_json::Value = serde_json::from_slice(&interrupted.stdout).unwrap();
+ assert_eq!(
+ json,
+ serde_json::json!({ "error": "Interrupted by signal 2" })
+ );
+}
+
+#[rstest]
+fn test_switch_execute_stdout_follows_format(repo: TestRepo) {
+ for format in ["json", "text"] {
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "main",
+ "--no-cd",
+ "--yes",
+ "--format",
+ format,
+ "--execute=sh",
+ "--",
+ "-c",
+ "echo child-output",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ if format == "json" {
+ // Parsing the complete stream rejects a second document or child
+ // output before/after the result.
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["action"], "already_at");
+ assert_eq!(json["branch"], "main");
+ assert!(String::from_utf8_lossy(&output.stderr).contains("child-output"));
+ } else {
+ assert_eq!(String::from_utf8(output.stdout).unwrap(), "child-output\n");
+ }
+ }
+}
+
#[rstest]
fn test_switch_format_table_rejected_by_clap(repo: TestRepo) {
let output = repo
@@ -8906,7 +9204,9 @@ fn switch_base_accepts_worktree_path(mut repo: TestRepo) {
}
#[rstest]
-fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo) {
+#[case(false)]
+#[case(true)]
+fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo, #[case] json: bool) {
// `git worktree add -b` writes the branch ref before it populates the
// worktree, so a failure in between leaves the branch with nothing checked
// out on it (issue #4108). A regular file where the worktree's leading
@@ -8914,11 +9214,12 @@ fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo) {
repo.write_test_config(r#"worktree-path = "blocked/{{ branch | sanitize }}""#);
fs::write(repo.root_path().join("blocked"), "not a directory").unwrap();
- let output = repo
- .wt_command()
- .args(["switch", "--create", "stranded"])
- .output()
- .unwrap();
+ let mut cmd = repo.wt_command();
+ cmd.args(["switch", "--create", "stranded"]);
+ if json {
+ cmd.args(["--format=json", "--no-cd"]);
+ }
+ let output = cmd.output().unwrap();
assert!(
!output.status.success(),
"switch --create should fail when git cannot create the worktree"
@@ -8951,6 +9252,21 @@ fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo) {
stderr.contains("wt switch stranded"),
"expected a recovery suggestion for the leftover branch, got: {stderr}"
);
+ if json {
+ let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ let error = result["error"].as_str().expect("error is a plain string");
+ assert!(
+ error.contains("fatal: could not create leading directories"),
+ "JSON must retain Git's directory-creation error: {error}"
+ );
+ assert!(
+ error.contains("Branch stranded was created before the failure, with no worktree")
+ && error.contains("git branch -d -- stranded")
+ && error.contains("wt switch stranded"),
+ "JSON must name the leftover branch and both recovery choices: {error}"
+ );
+ assert_eq!(error, error.ansi_strip());
+ }
}
// `--path` tests
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index e820627f8..6ee246d74 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -123,7 +123,8 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
--format <FORMAT>
Output format
- JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code WorktreeCreate hooks).
+ JSON prints one structured result to stdout once the switch, including any --execute command, completes. Once arguments are accepted, failures print an object with an error string. Argument errors use stderr only. Diagnostics and --execute output go to stderr. A worktree created before a later failure remains in place. Canceling the interactive picker produces no result. Background hooks run independently of the result. Designed for tool integration (e.g., Claude Code WorktreeCreate
+ hooks).
[default: text]
[possible values: text, json]