Skip to content

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

feat: add --format=json to config state subcommands (#1969)

Maximilian Roos85c3dadf174a
diff --git a/docs/content/config.md b/docs/content/config.md
index c34423124..461867046 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -546,6 +546,16 @@ Usage: <b><span class=c>wt config show</span></b> <span class=c>[OPTIONS]</span>
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
Print help (see a summary with &#39;-h&#39;)
+<b><span class=g>Output:</span></b>
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format (text, json)
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
diff --git a/docs/content/merge.md b/docs/content/merge.md
index 323fb1753..3d50e773b 100644
--- a/docs/content/merge.md
+++ b/docs/content/merge.md
@@ -130,6 +130,17 @@ Usage: <b><span class=c>wt merge</span></b> <span class=c>[OPTIONS]</span> <span
<b><span class=c>--no-hooks</span></b>
Skip hooks
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format
+
+ JSON prints structured result to stdout after merge completes.
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
diff --git a/docs/content/remove.md b/docs/content/remove.md
index f1aed74ad..8f876da35 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -115,6 +115,17 @@ Usage: <b><span class=c>wt remove</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=c>--no-hooks</span></b>
Skip hooks
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format
+
+ JSON prints structured result to stdout after removal completes.
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
diff --git a/docs/content/step.md b/docs/content/step.md
index dc62198df..5543bd363 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -552,6 +552,16 @@ Usage: <b><span class=c>wt step for-each</span></b> <span class=c>[OPTIONS]</spa
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
Print help (see a summary with &#39;-h&#39;)
+<b><span class=g>Automation:</span></b>
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format (text, json)
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
@@ -690,6 +700,15 @@ Usage: <b><span class=c>wt step prune</span></b> <span class=c>[OPTIONS]</span>
<b><span class=c>-y</span></b>, <b><span class=c>--yes</span></b>
Skip approval prompts
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format (text, json)
+
+ Possible values:
+ - <b><span class=c>text</span></b>: Human-readable text output
+ - <b><span class=c>json</span></b>: JSON output
+
+ [default: text]
+
<b><span class=g>Global Options:</span></b>
<b><span class=c>-C</span></b><span class=c> &lt;path&gt;</span>
Working directory for this command
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 254492143..cfd3838fa 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -551,6 +551,16 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Output:
+ --format <FORMAT>
+ Output format (text, json)
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/skills/worktrunk/reference/merge.md b/skills/worktrunk/reference/merge.md
index c3226a8d3..cff5f2e96 100644
--- a/skills/worktrunk/reference/merge.md
+++ b/skills/worktrunk/reference/merge.md
@@ -120,6 +120,17 @@ Automation:
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after merge completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.md
index 33227cd50..5533fd13e 100644
--- a/skills/worktrunk/reference/remove.md
+++ b/skills/worktrunk/reference/remove.md
@@ -114,6 +114,17 @@ Automation:
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after removal completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index 87aa4c81b..bb7b1d685 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -581,6 +581,16 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Automation:
+ --format <FORMAT>
+ Output format (text, json)
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
@@ -729,6 +739,15 @@ Automation:
-y, --yes
Skip approval prompts
+ --format <FORMAT>
+ Output format (text, json)
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/src/cli/config.rs b/src/cli/config.rs
index 77bf7ded4..bba4d0bbe 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -1,5 +1,6 @@
use clap::Subcommand;
+use super::SwitchFormat;
use crate::commands::Shell;
#[derive(Subcommand)]
@@ -376,6 +377,10 @@ This tests:
/// Run diagnostic checks (CI tools, commit generation, version)
#[arg(long)]
full: bool,
+
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Output")]
+ format: SwitchFormat,
},
/// Update deprecated config settings
@@ -867,6 +872,10 @@ $ wt config state ci-status clear && wt config state ci-status get
/// Target branch (defaults to current)
#[arg(long, add = crate::completion::branch_value_completer())]
branch: Option<String>,
+
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Output")]
+ format: SwitchFormat,
},
/// Clear CI status cache
@@ -915,6 +924,10 @@ $ wt config state marker get --branch=feature
/// Target branch (defaults to current)
#[arg(long, add = crate::completion::branch_value_completer())]
branch: Option<String>,
+
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Output")]
+ format: SwitchFormat,
},
/// Set marker for a branch
@@ -1011,6 +1024,15 @@ $ wt config state logs get --hook=user:post-start:server --branch=feature
/// Target branch (defaults to current)
#[arg(long, add = crate::completion::branch_value_completer())]
branch: Option<String>,
+
+ /// Output format (text, json)
+ #[arg(
+ long,
+ default_value = "text",
+ conflicts_with = "hook",
+ help_heading = "Output"
+ )]
+ format: SwitchFormat,
},
/// Clear background operation logs
@@ -1030,7 +1052,11 @@ List shown hints:
$ wt config state hints
```"#
)]
- Get,
+ Get {
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Output")]
+ format: SwitchFormat,
+ },
/// Clear hints (re-show on next trigger)
#[command(
@@ -1120,6 +1146,10 @@ $ wt config state vars list --branch=feature
/// Target branch (defaults to current)
#[arg(long, add = crate::completion::branch_value_completer())]
branch: Option<String>,
+
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Output")]
+ format: SwitchFormat,
},
/// Clear a key or all keys
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 0ff1d7275..aa9ba250a 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -439,6 +439,12 @@ pub(crate) struct RemoveArgs {
/// artifacts). Without this flag, removal fails if untracked files exist.
#[arg(short, long)]
pub(crate) force: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after removal completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ pub(crate) format: SwitchFormat,
}
#[derive(Args)]
@@ -512,6 +518,12 @@ pub(crate) struct MergeArgs {
/// What to stage before committing [default: all]
#[arg(long)]
pub(crate) stage: Option<crate::commands::commit::StageMode>,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after merge completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ pub(crate) format: SwitchFormat,
}
#[derive(Subcommand)]
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 3f9edb545..a580c4230 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -452,6 +452,10 @@ Note: This command is experimental and may change in future versions.
"#
)]
ForEach {
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
+
/// Command template (see --help for all variables)
#[arg(required = true, last = true, num_args = 1..)]
args: Vec<String>,
@@ -558,6 +562,10 @@ $ wt step prune
/// Run removal in foreground (block until complete)
#[arg(long)]
foreground: bool,
+
+ /// Output format (text, json)
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// \[experimental\] Move worktrees to expected paths
diff --git a/src/commands/config/hints.rs b/src/commands/config/hints.rs
index d5f1e8bb0..abdeedf17 100644
--- a/src/commands/config/hints.rs
+++ b/src/commands/config/hints.rs
@@ -6,12 +6,16 @@ use color_print::cformat;
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message, println, success_message};
+use crate::cli::SwitchFormat;
+
/// Handle the hints get command (list shown hints)
-pub fn handle_hints_get() -> anyhow::Result<()> {
+pub fn handle_hints_get(format: SwitchFormat) -> anyhow::Result<()> {
let repo = Repository::current()?;
let hints = repo.list_shown_hints();
- if hints.is_empty() {
+ if format == SwitchFormat::Json {
+ println!("{}", serde_json::to_string_pretty(&hints)?);
+ } else if hints.is_empty() {
eprintln!("{}", info_message("No hints have been shown"));
} else {
for hint in hints {
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index cb2340df9..dbf05400e 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -23,7 +23,7 @@ use worktrunk::styling::{
};
use super::state::require_user_config_path;
-use crate::cli::version_str;
+use crate::cli::{SwitchFormat, version_str};
use crate::commands::configure_shell::{ConfigAction, scan_shell_configs};
use crate::commands::list::ci_status::{CiPlatform, CiToolsStatus, platform_for_repo};
use crate::help_pager::show_help_in_pager;
@@ -31,7 +31,10 @@ use crate::llm::test_commit_generation;
use crate::output;
/// Handle the config show command
-pub fn handle_config_show(full: bool) -> anyhow::Result<()> {
+pub fn handle_config_show(full: bool, format: SwitchFormat) -> anyhow::Result<()> {
+ if format == SwitchFormat::Json {
+ return handle_config_show_json();
+ }
// Build the complete output as a string
let mut show_output = String::new();
@@ -84,6 +87,50 @@ pub fn handle_config_show(full: bool) -> anyhow::Result<()> {
Ok(())
}
+/// JSON output for config show: paths, existence, and parsed config contents.
+fn handle_config_show_json() -> anyhow::Result<()> {
+ let user_path = require_user_config_path()?;
+ let user_exists = user_path.exists();
+ let user_config = if user_exists {
+ Some(serde_json::to_value(&UserConfig::load()?)?)
+ } else {
+ None
+ };
+
+ let (project_path, project_config) = if let Ok(repo) = Repository::current() {
+ let path = repo.current_worktree().root()?.join(".config/wt.toml");
+ let config = repo.load_project_config()?;
+ (
+ Some(path),
+ config.map(|c| serde_json::to_value(&c)).transpose()?,
+ )
+ } else {
+ (None, None)
+ };
+
+ let system_path = system_config_path().or_else(default_system_config_path);
+ let system_exists = system_path.as_ref().is_some_and(|p| p.exists());
+
+ let output = serde_json::json!({
+ "user": {
+ "path": user_path,
+ "exists": user_exists,
+ "config": user_config,
+ },
+ "project": {
+ "path": project_path,
+ "exists": project_path.as_ref().is_some_and(|p| p.exists()),
+ "config": project_config,
+ },
+ "system": {
+ "path": system_path,
+ "exists": system_exists,
+ },
+ });
+ worktrunk::styling::println!("{}", serde_json::to_string_pretty(&output)?);
+ Ok(())
+}
+
// ==================== Helper Functions ====================
/// Check if Claude Code CLI is available
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index 37947d01d..a88014743 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -16,7 +16,7 @@ use worktrunk::styling::{
warning_message,
};
-use crate::cli::OutputFormat;
+use crate::cli::{OutputFormat, SwitchFormat};
use crate::commands::process::HookLog;
use worktrunk::utils::epoch_now;
@@ -126,6 +126,23 @@ fn is_command_log_file(name: &str) -> bool {
name.ends_with(".jsonl") || name.ends_with(".jsonl.old")
}
+/// Convert a log directory entry to a JSON object with file, size, and modified_at.
+fn log_entry_to_json(entry: &std::fs::DirEntry) -> serde_json::Value {
+ let path = entry.path();
+ let name = path
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string();
+ let meta = entry.metadata().ok();
+ let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
+ let modified = meta
+ .and_then(|m| m.modified().ok())
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_secs());
+ serde_json::json!({ "file": name, "size": size, "modified_at": modified })
+}
+
/// Render a table of log file entries, or "(none)" if empty.
fn render_log_table(out: &mut String, entries: &mut [std::fs::DirEntry]) -> std::fmt::Result {
if entries.is_empty() {
@@ -227,10 +244,46 @@ pub(super) fn render_all_log_sections(out: &mut String, repo: &Repository) -> an
///
/// - `source:hook-type:name` for hook commands (e.g., `user:post-start:server`)
/// - `internal:op` for internal operations (e.g., `internal:remove`)
-pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::Result<()> {
+pub fn handle_logs_get(
+ hook: Option<String>,
+ branch: Option<String>,
+ format: SwitchFormat,
+) -> anyhow::Result<()> {
let repo = Repository::current()?;
match hook {
+ None if format == SwitchFormat::Json => {
+ let log_dir = repo.wt_logs_dir();
+ let (command_log, hook_output) = if log_dir.exists() {
+ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().is_file() && is_wt_log_file(&e.path()))
+ .collect();
+ entries.sort_by(|a, b| {
+ let a_time = a.metadata().and_then(|m| m.modified()).ok();
+ let b_time = b.metadata().and_then(|m| m.modified()).ok();
+ b_time.cmp(&a_time)
+ });
+ let mut cmd_log = Vec::new();
+ let mut hook_out = Vec::new();
+ for entry in &entries {
+ let name = entry.file_name().to_string_lossy().to_string();
+ if is_command_log_file(&name) {
+ cmd_log.push(log_entry_to_json(entry));
+ } else {
+ hook_out.push(log_entry_to_json(entry));
+ }
+ }
+ (cmd_log, hook_out)
+ } else {
+ (vec![], vec![])
+ };
+ let output = serde_json::json!({
+ "command_log": command_log,
+ "hook_output": hook_output,
+ });
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ }
None => {
// No hook specified, show all log files
let mut out = String::new();
@@ -308,7 +361,11 @@ pub fn handle_logs_get(hook: Option<String>, branch: Option<String>) -> anyhow::
// ==================== State Get/Set/Clear Commands ====================
/// Handle the state get command
-pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {
+pub fn handle_state_get(
+ key: &str,
+ branch: Option<String>,
+ format: SwitchFormat,
+) -> anyhow::Result<()> {
use super::super::list::ci_status::PrStatus;
let repo = Repository::current()?;
@@ -331,9 +388,32 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
Some(b) => b,
None => repo.require_current_branch("get marker for current branch")?,
};
- match repo.branch_marker(&branch_name) {
- Some(marker) => println!("{marker}"),
- None => println!(""),
+ if format == SwitchFormat::Json {
+ // Read raw config to get both marker and set_at
+ let config_key = format!("worktrunk.state.{branch_name}.marker");
+ let raw = repo
+ .run_command(&["config", "--get", &config_key])
+ .ok()
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty());
+ let output = match raw {
+ Some(json_str) => {
+ let parsed: serde_json::Value =
+ serde_json::from_str(&json_str).unwrap_or_default();
+ serde_json::json!({
+ "branch": branch_name,
+ "marker": parsed.get("marker").and_then(|v| v.as_str()),
+ "set_at": parsed.get("set_at").and_then(|v| v.as_u64()),
+ })
+ }
+ None => serde_json::json!(null),
+ };
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ } else {
+ match repo.branch_marker(&branch_name) {
+ Some(marker) => println!("{marker}"),
+ None => println!(""),
+ }
}
}
"ci-status" => {
@@ -369,12 +449,21 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>
}
let ci_branch = CiBranchName::from_branch_ref(&branch_name, is_remote);
- let ci_status = PrStatus::detect(&repo, &ci_branch, &head)
- .map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {
- s.ci_status
- });
- let status_str: &'static str = ci_status.into();
- println!("{status_str}");
+ let pr_status = PrStatus::detect(&repo, &ci_branch, &head);
+
+ if format == SwitchFormat::Json {
+ let output = pr_status
+ .as_ref()
+ .map(super::super::list::json_output::JsonCi::from);
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ } else {
+ let ci_status = pr_status
+ .map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {
+ s.ci_status
+ });
+ let status_str: &'static str = ci_status.into();
+ println!("{status_str}");
+ }
}
// TODO: Consider simplifying to just print the path and let users run `ls -al` themselves
"logs" => {
@@ -771,38 +860,17 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {
b_time.cmp(&a_time)
});
- let to_json = |entry: &std::fs::DirEntry| -> serde_json::Value {
- let path = entry.path();
- let name = path
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string();
- let meta = entry.metadata().ok();
- let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
- let modified = meta
- .and_then(|m| m.modified().ok())
- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
- .map(|d| d.as_secs());
-
- serde_json::json!({
- "file": name,
- "size": size,
- "modified_at": modified
- })
- };
-
let mut cmd_log = Vec::new();
let mut hook_out = Vec::new();
let mut diagnostic = Vec::new();
for entry in &all_entries {
let name = entry.file_name().to_string_lossy().to_string();
if is_command_log_file(&name) {
- cmd_log.push(to_json(entry));
+ cmd_log.push(log_entry_to_json(entry));
} else if is_diagnostic_file(&name) {
- diagnostic.push(to_json(entry));
+ diagnostic.push(log_entry_to_json(entry));
} else {
- hook_out.push(to_json(entry));
+ hook_out.push(log_entry_to_json(entry));
}
}
(cmd_log, hook_out, diagnostic)
@@ -1020,7 +1088,7 @@ pub fn handle_vars_set(key: &str, value: &str, branch: Option<String>) -> anyhow
}
/// Handle vars list
-pub fn handle_vars_list(branch: Option<String>) -> anyhow::Result<()> {
+pub fn handle_vars_list(branch: Option<String>, format: SwitchFormat) -> anyhow::Result<()> {
let repo = Repository::current()?;
let branch_name = match branch {
Some(b) => b,
@@ -1028,7 +1096,14 @@ pub fn handle_vars_list(branch: Option<String>) -> anyhow::Result<()> {
};
let entries: Vec<_> = repo.vars_entries(&branch_name).into_iter().collect();
- if entries.is_empty() {
+
+ if format == SwitchFormat::Json {
+ let obj: serde_json::Map<String, serde_json::Value> = entries
+ .into_iter()
+ .map(|(k, v)| (k, serde_json::Value::String(v)))
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&obj)?);
+ } else if entries.is_empty() {
eprintln!(
"{}",
info_message(cformat!("No variables for <bold>{branch_name}</>"))
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 3c58fbd3a..e4dffafdd 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -43,7 +43,8 @@ use crate::commands::worktree_display_name;
/// in real-time. Continues on errors and reports a summary at the end.
///
/// All template variables from hooks are available, and context JSON is piped to stdin.
-pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
+pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> anyhow::Result<()> {
+ let json_mode = format == crate::cli::SwitchFormat::Json;
let repo = Repository::current()?;
// Filter out prunable worktrees (directory deleted) - can't run commands there
let worktrees: Vec<_> = repo
@@ -54,6 +55,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let config = UserConfig::load()?;
let mut failed: Vec<String> = Vec::new();
+ let mut json_results: Vec<serde_json::Value> = Vec::new();
let total = worktrees.len();
// Join args into a template string (will be expanded per-worktree)
@@ -87,29 +89,65 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
// Execute command: stream both stdout and stderr in real-time
// Pipe context JSON to stdin for scripts that want structured data
match run_command_streaming(&command, &wt.path, Some(&context_json)) {
- Ok(()) => {}
- Err(CommandError::SpawnFailed(err)) => {
- eprintln!(
- "{}",
- error_message(cformat!("Failed in <bold>{display_name}</> (spawn failed)"))
- );
- eprintln!("{}", format_with_gutter(&err, None));
- failed.push(display_name.to_string());
+ Ok(()) => {
+ if json_mode {
+ json_results.push(serde_json::json!({
+ "branch": wt.branch,
+ "path": wt.path,
+ "exit_code": 0,
+ "success": true,
+ }));
+ }
}
- Err(CommandError::ExitCode(exit_code)) => {
- // stderr already streamed to terminal; just show failure message
- let exit_info = exit_code
- .map(|code| format!(" (exit code {code})"))
- .unwrap_or_default();
- eprintln!(
- "{}",
- error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))
- );
+ Err(err) => {
+ let (exit_code, error_detail) = match &err {
+ CommandError::SpawnFailed(e) => {
+ eprintln!(
+ "{}",
+ error_message(cformat!(
+ "Failed in <bold>{display_name}</> (spawn failed)"
+ ))
+ );
+ eprintln!("{}", format_with_gutter(e, None));
+ (None, Some(e.clone()))
+ }
+ CommandError::ExitCode(code) => {
+ let exit_info = code
+ .map(|c| format!(" (exit code {c})"))
+ .unwrap_or_default();
+ eprintln!(
+ "{}",
+ error_message(cformat!("Failed in <bold>{display_name}</>{exit_info}"))
+ );
+ (*code, None)
+ }
+ };
failed.push(display_name.to_string());
+ if json_mode {
+ let mut entry = serde_json::json!({
+ "branch": wt.branch,
+ "path": wt.path,
+ "exit_code": exit_code,
+ "success": false,
+ });
+ if let Some(e) = error_detail {
+ entry["error"] = serde_json::Value::String(e);
+ }
+ json_results.push(entry);
+ }
}
}
}
+ if json_mode {
+ println!("{}", serde_json::to_string_pretty(&json_results)?);
+ if failed.is_empty() {
+ return Ok(());
+ } else {
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());
+ }
+ }
+
// Summary
eprintln!();
if failed.is_empty() {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index b468b8f04..16e0c7c51 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -41,6 +41,8 @@ pub struct MergeOptions<'a> {
pub yes: bool,
/// CLI override for stage mode. None = use effective config default.
pub stage: Option<super::commit::StageMode>,
+ /// Output format (text or json).
+ pub format: crate::cli::SwitchFormat,
}
/// Collect all commands that will be executed during merge.
@@ -85,6 +87,7 @@ fn collect_merge_commands(
}
pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
+ let json_mode = opts.format == crate::cli::SwitchFormat::Json;
let MergeOptions {
target,
squash: squash_opt,
@@ -95,6 +98,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
verify: verify_opt,
yes,
stage,
+ ..
} = opts;
// Load config once, run LLM setup prompt if committing, then reuse config
@@ -360,5 +364,17 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
}
}
+ if json_mode {
+ let output = serde_json::json!({
+ "branch": current_branch,
+ "target": target_branch,
+ "committed": committed,
+ "squashed": squashed,
+ "rebased": rebased,
+ "removed": removed,
+ });
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ }
+
Ok(())
}
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 63b414780..cc4634e24 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1256,7 +1256,13 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {
/// entries (pruned + branch deleted), and orphan branches without worktrees (deleted).
/// Skips the main/primary worktree, locked worktrees, and worktrees younger than
/// `min_age`. Removes the current worktree last to trigger cd to primary.
-pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) -> anyhow::Result<()> {
+pub fn step_prune(
+ dry_run: bool,
+ yes: bool,
+ min_age: &str,
+ foreground: bool,
+ format: crate::cli::SwitchFormat,
+) -> anyhow::Result<()> {
let min_age_duration =
humantime::parse_duration(min_age).context("Invalid --min-age duration")?;
@@ -1639,6 +1645,28 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->
// Sort by original check order for deterministic output regardless of
// channel completion order.
dry_run_info.sort_by_key(|(c, _)| c.check_idx);
+
+ if format == crate::cli::SwitchFormat::Json {
+ let items: Vec<serde_json::Value> = dry_run_info
+ .iter()
+ .map(|(c, info)| {
+ serde_json::json!({
+ "branch": c.branch,
+ "path": c.path,
+ "kind": match c.kind {
+ CandidateKind::Current => "current",
+ CandidateKind::Other => "worktree",
+ CandidateKind::BranchOnly => "branch_only",
+ },
+ "reason": info.reason_desc,
+ "target": info.effective_target,
+ })
+ })
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&items)?);
+ return Ok(());
+ }
+
let mut dry_candidates = Vec::new();
for (candidate, info) in dry_run_info {
eprintln!(
@@ -1722,7 +1750,23 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->
removed.push(current);
}
- if removed.is_empty() {
+ if format == crate::cli::SwitchFormat::Json {
+ let items: Vec<serde_json::Value> = removed
+ .iter()
+ .map(|c| {
+ serde_json::json!({
+ "branch": c.branch,
+ "path": c.path,
+ "kind": match c.kind {
+ CandidateKind::Current => "current",
+ CandidateKind::Other => "worktree",
+ CandidateKind::BranchOnly => "branch_only",
+ },
+ })
+ })
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&items)?);
+ } else if removed.is_empty() {
if skipped_young.is_empty() {
eprintln!("{}", info_message("No merged worktrees to remove"));
}
diff --git a/src/main.rs b/src/main.rs
index a4135dfb2..7eabf1ef1 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -64,7 +64,8 @@ use cli::{
ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigCommand, ConfigPluginsClaudeCommand,
ConfigPluginsCommand, ConfigPluginsOpencodeCommand, ConfigShellCommand, DefaultBranchAction,
HintsAction, HookCommand, ListArgs, ListSubcommand, LogsAction, MarkerAction, MergeArgs,
- PreviousBranchAction, RemoveArgs, StateCommand, StepCommand, SwitchArgs, VarsAction,
+ PreviousBranchAction, RemoveArgs, StateCommand, StepCommand, SwitchArgs, SwitchFormat,
+ VarsAction,
};
use worktrunk::HookType;
@@ -332,7 +333,7 @@ fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {
force,
} => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force),
StepCommand::Eval { template, dry_run } => step_eval(&template, dry_run),
- StepCommand::ForEach { args } => step_for_each(args),
+ StepCommand::ForEach { format, args } => step_for_each(args, format),
StepCommand::Promote { branch } => {
handle_promote(branch.as_deref()).map(|result| match result {
commands::PromoteResult::Promoted => (),
@@ -351,7 +352,8 @@ fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {
yes,
min_age,
foreground,
- } => step_prune(dry_run, yes, &min_age, foreground),
+ format,
+ } => step_prune(dry_run, yes, &min_age, foreground, format),
StepCommand::Relocate {
branches,
dry_run,
@@ -367,39 +369,52 @@ fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {
fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
match action {
StateCommand::DefaultBranch { action } => match action {
- Some(DefaultBranchAction::Get) | None => handle_state_get("default-branch", None),
+ Some(DefaultBranchAction::Get) | None => {
+ handle_state_get("default-branch", None, SwitchFormat::Text)
+ }
Some(DefaultBranchAction::Set { branch }) => {
handle_state_set("default-branch", branch, None)
}
Some(DefaultBranchAction::Clear) => handle_state_clear("default-branch", None, false),
},
StateCommand::PreviousBranch { action } => match action {
- Some(PreviousBranchAction::Get) | None => handle_state_get("previous-branch", None),
+ Some(PreviousBranchAction::Get) | None => {
+ handle_state_get("previous-branch", None, SwitchFormat::Text)
+ }
Some(PreviousBranchAction::Set { branch }) => {
handle_state_set("previous-branch", branch, None)
}
Some(PreviousBranchAction::Clear) => handle_state_clear("previous-branch", None, false),
},
StateCommand::CiStatus { action } => match action {
- Some(CiStatusAction::Get { branch }) => handle_state_get("ci-status", branch),
- None => handle_state_get("ci-status", None),
+ Some(CiStatusAction::Get { branch, format }) => {
+ handle_state_get("ci-status", branch, format)
+ }
+ None => handle_state_get("ci-status", None, SwitchFormat::Text),
Some(CiStatusAction::Clear { branch, all }) => {
handle_state_clear("ci-status", branch, all)
}
},
StateCommand::Marker { action } => match action {
- Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch),
- None => handle_state_get("marker", None),
+ Some(MarkerAction::Get { branch, format }) => {
+ handle_state_get("marker", branch, format)
+ }
+ None => handle_state_get("marker", None, SwitchFormat::Text),
Some(MarkerAction::Set { value, branch }) => handle_state_set("marker", value, branch),
Some(MarkerAction::Clear { branch, all }) => handle_state_clear("marker", branch, all),
},
StateCommand::Logs { action } => match action {
- Some(LogsAction::Get { hook, branch }) => handle_logs_get(hook, branch),
- None => handle_logs_get(None, None),
+ Some(LogsAction::Get {
+ hook,
+ branch,
+ format,
+ }) => handle_logs_get(hook, branch, format),
+ None => handle_logs_get(None, None, SwitchFormat::Text),
Some(LogsAction::Clear) => handle_state_clear("logs", None, false),
},
StateCommand::Hints { action } => match action {
- Some(HintsAction::Get) | None => handle_hints_get(),
+ Some(HintsAction::Get { format }) => handle_hints_get(format),
+ None => handle_hints_get(SwitchFormat::Text),
Some(HintsAction::Clear { name }) => handle_hints_clear(name),
},
StateCommand::Vars { action } => match action {
@@ -408,7 +423,7 @@ fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
assignment: (key, value),
branch,
} => handle_vars_set(&key, &value, branch),
- VarsAction::List { branch } => handle_vars_list(branch),
+ VarsAction::List { branch, format } => handle_vars_list(branch, format),
VarsAction::Clear { key, all, branch } => {
handle_vars_clear(key.as_deref(), all, branch)
}
@@ -478,7 +493,7 @@ fn handle_config_command(action: ConfigCommand) -> anyhow::Result<()> {
match action {
ConfigCommand::Shell { action } => handle_config_shell_command(action),
ConfigCommand::Create { project } => handle_config_create(project),
- ConfigCommand::Show { full } => handle_config_show(full),
+ ConfigCommand::Show { full, format } => handle_config_show(full, format),
ConfigCommand::Update { yes } => handle_config_update(yes),
ConfigCommand::Plugins { action } => handle_plugins_command(action),
ConfigCommand::State { action } => handle_state_command(action),
@@ -709,7 +724,36 @@ fn validate_remove_targets(
plans
}
+/// Convert a RemoveResult to a JSON value for structured output.
+fn remove_result_to_json(result: &RemoveResult) -> serde_json::Value {
+ match result {
+ RemoveResult::RemovedWorktree {
+ worktree_path,
+ branch_name,
+ deletion_mode,
+ ..
+ } => serde_json::json!({
+ "kind": "worktree",
+ "branch": branch_name,
+ "path": worktree_path,
+ "branch_deleted": !deletion_mode.should_keep(),
+ }),
+ RemoveResult::BranchOnly {
+ branch_name,
+ deletion_mode,
+ pruned,
+ ..
+ } => serde_json::json!({
+ "kind": "branch_only",
+ "branch": branch_name,
+ "pruned": pruned,
+ "branch_deleted": !deletion_mode.should_keep(),
+ }),
+ }
+}
+
fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
+ let json_mode = args.format == SwitchFormat::Json;
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
UserConfig::load()
.context("Failed to load config")
@@ -777,7 +821,12 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
// "Approve at the Gate": approval happens AFTER validation passes
let run_hooks = verify && approve_remove(args.yes)?;
- handle_remove_output(&result, args.foreground, run_hooks, false)
+ handle_remove_output(&result, args.foreground, run_hooks, false)?;
+ if json_mode {
+ let json = serde_json::json!([remove_result_to_json(&result)]);
+ println!("{}", serde_json::to_string_pretty(&json)?);
+ }
+ Ok(())
} else {
// Multi-worktree removal: validate ALL first, then approve, then execute
let plans = validate_remove_targets(
@@ -803,15 +852,30 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
// but hooks execute in each target worktree.
let run_hooks = verify && approve_remove(args.yes)?;
+ let mut json_items: Vec<serde_json::Value> = Vec::new();
+
// Execute all validated plans: others first, branch-only next, current last
- for result in plans.others {
- handle_remove_output(&result, args.foreground, run_hooks, false)?;
+ for result in &plans.others {
+ if json_mode {
+ json_items.push(remove_result_to_json(result));
+ }
+ handle_remove_output(result, args.foreground, run_hooks, false)?;
}
- for result in plans.branch_only {
- handle_remove_output(&result, args.foreground, run_hooks, false)?;
+ for result in &plans.branch_only {
+ if json_mode {
+ json_items.push(remove_result_to_json(result));
+ }
+ handle_remove_output(result, args.foreground, run_hooks, false)?;
+ }
+ if let Some(ref result) = plans.current {
+ if json_mode {
+ json_items.push(remove_result_to_json(result));
+ }
+ handle_remove_output(result, args.foreground, run_hooks, false)?;
}
- if let Some(result) = plans.current {
- handle_remove_output(&result, args.foreground, run_hooks, false)?;
+
+ if json_mode {
+ println!("{}", serde_json::to_string_pretty(&json_items)?);
}
if !plans.errors.is_empty() {
@@ -976,6 +1040,7 @@ fn handle_merge_command(args: MergeArgs) -> anyhow::Result<()> {
verify: flag_pair(args.verify, args.no_hooks || args.no_verify),
yes: args.yes,
stage: args.stage,
+ format: args.format,
})
}
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 2442f1699..8b648cf79 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -3561,3 +3561,76 @@ mod plugin_prompt_pty {
);
}
}
+
+// ============================================================================
+// --format=json
+// ============================================================================
+
+#[rstest]
+fn test_config_show_json(repo: TestRepo, temp_home: TempDir) {
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ "worktree-path = \"../{{ repo }}.{{ branch }}\"\n",
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_xdg_config_path(&mut cmd, temp_home.path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+
+ assert!(json["user"]["exists"].as_bool().unwrap());
+ assert!(json["user"]["path"].as_str().is_some());
+ assert!(json["user"]["config"].is_object());
+
+ // Project config doesn't exist in this fixture
+ assert!(!json["project"]["exists"].as_bool().unwrap());
+}
+
+#[rstest]
+fn test_config_show_json_with_project_config(repo: TestRepo, temp_home: TempDir) {
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(global_config_dir.join("config.toml"), "").unwrap();
+
+ // Create project config
+ let config_dir = repo.root_path().join(".config");
+ fs::create_dir_all(&config_dir).unwrap();
+ fs::write(
+ config_dir.join("wt.toml"),
+ "[list]\nurl = \"http://localhost:3000\"\n",
+ )
+ .unwrap();
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_xdg_config_path(&mut cmd, temp_home.path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.args(["config", "show", "--format=json"])
+ .current_dir(repo.root_path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+
+ assert!(json["project"]["exists"].as_bool().unwrap());
+ assert!(json["project"]["config"].is_object());
+}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 156dabbf4..63582dfb5 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -37,11 +37,7 @@ fn write_ci_cache(repo: &TestRepo, branch: &str, json: &str) {
let cache_dir = git_dir.join("wt").join("cache").join("ci-status");
std::fs::create_dir_all(&cache_dir).unwrap();
- // Sanitize branch name for filename
- let safe_branch: String = branch
- .chars()
- .map(|c| if c == '/' || c == '\\' { '-' } else { c })
- .collect();
+ let safe_branch = sanitize_for_filename(branch);
let cache_file = cache_dir.join(format!("{safe_branch}.json"));
std::fs::write(&cache_file, json).unwrap();
}
@@ -235,6 +231,56 @@ fn test_state_clear_previous_branch_empty(repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stderr), @"○ No previous branch to clear");
}
+// ============================================================================
+// bare subcommand defaults (no action → implicit get)
+// ============================================================================
+
+/// `wt config state ci-status` (no subcommand) defaults to `get`.
+#[rstest]
+fn test_state_bare_ci_status(repo: TestRepo) {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.args(["config", "state", "ci-status"]);
+ cmd.current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "no-ci");
+}
+
+/// `wt config state marker` (no subcommand) defaults to `get`.
+#[rstest]
+fn test_state_bare_marker(repo: TestRepo) {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.args(["config", "state", "marker"]);
+ cmd.current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+ assert!(String::from_utf8_lossy(&output.stdout).trim().is_empty());
+}
+
+/// `wt config state logs` (no subcommand) defaults to `get`.
+#[rstest]
+fn test_state_bare_logs(repo: TestRepo) {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.args(["config", "state", "logs"]);
+ cmd.current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+}
+
+/// `wt config state hints` (no subcommand) defaults to `get`.
+#[rstest]
+fn test_state_bare_hints(repo: TestRepo) {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.args(["config", "state", "hints"]);
+ cmd.current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success());
+}
+
// ============================================================================
// ci-status
// ============================================================================
@@ -1893,3 +1939,156 @@ fn test_vars_json_branch_with_vars_in_name(repo: TestRepo) {
"vars key should be 'port', not a mangled key from bad split"
);
}
+
+// ============================================================================
+// --format=json on individual subcommands
+// ============================================================================
+
+#[rstest]
+fn test_logs_get_json_empty(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
+ {
+ "command_log": [],
+ "hook_output": []
+ }
+ "#);
+}
+
+#[rstest]
+fn test_logs_get_json_with_files(repo: TestRepo) {
+ let log_dir = repo.root_path().join(".git/wt/logs");
+ std::fs::create_dir_all(&log_dir).unwrap();
+ std::fs::write(log_dir.join("commands.jsonl"), "{}").unwrap();
+ std::fs::write(log_dir.join("main-user-post-start-server.log"), "output").unwrap();
+
+ let output = wt_state_cmd(&repo, "logs", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ // Redact dynamic timestamps and sizes
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""modified_at": \d+"#, r#""modified_at": "<TIMESTAMP>""#);
+ settings.add_filter(r#""size": \d+"#, r#""size": "<SIZE>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_ci_status_get_json(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"null");
+}
+
+#[rstest]
+fn test_ci_status_get_json_with_cached_data(repo: TestRepo) {
+ repo.commit("initial");
+ let head = repo.head_sha();
+
+ write_ci_cache(
+ &repo,
+ "main",
+ &format!(
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"{head}","branch":"main"}}"#
+ ),
+ );
+
+ let output = wt_state_cmd(&repo, "ci-status", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(&head, "<SHA>");
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_marker_get_json_empty(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "marker", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"null");
+}
+
+#[rstest]
+fn test_marker_get_json_with_value(repo: TestRepo) {
+ repo.run_git(&[
+ "config",
+ "worktrunk.state.main.marker",
+ &format!(r#"{{"marker":"🚧 WIP","set_at":{TEST_EPOCH}}}"#),
+ ]);
+
+ let output = wt_state_cmd(&repo, "marker", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
+ {
+ "branch": "main",
+ "marker": "🚧 WIP",
+ "set_at": 1735776000
+ }
+ "#);
+}
+
+#[rstest]
+fn test_vars_list_json_empty(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "vars", "list", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"{}");
+}
+
+#[rstest]
+fn test_vars_list_json_with_values(repo: TestRepo) {
+ repo.run_git(&["config", "worktrunk.state.main.vars.env", "staging"]);
+ repo.run_git(&["config", "worktrunk.state.main.vars.port", "3000"]);
+
+ let output = wt_state_cmd(&repo, "vars", "list", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
+ {
+ "env": "staging",
+ "port": "3000"
+ }
+ "#);
+}
+
+#[rstest]
+fn test_hints_get_json_empty(repo: TestRepo) {
+ let output = wt_state_cmd(&repo, "hints", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"[]");
+}
+
+#[rstest]
+fn test_hints_get_json_with_values(repo: TestRepo) {
+ repo.run_git(&["config", "worktrunk.hints.worktree-path", "true"]);
+
+ let output = wt_state_cmd(&repo, "hints", "get", &["--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
+ [
+ "worktree-path"
+ ]
+ "#);
+}
diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rs
index f4fc437e8..61513f0f8 100644
--- a/tests/integration_tests/for_each.rs
+++ b/tests/integration_tests/for_each.rs
@@ -118,3 +118,54 @@ fn test_for_each_skips_prunable_worktrees(mut repo: TestRepo) {
None,
));
}
+
+// ============================================================================
+// --format=json
+// ============================================================================
+
+#[rstest]
+fn test_for_each_json(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "for-each", "--format=json", "--", "true"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(items.len() >= 2, "expected at least 2 worktrees");
+ for item in items {
+ assert_eq!(item["success"], true);
+ assert_eq!(item["exit_code"], 0);
+ assert!(item["path"].as_str().is_some());
+ }
+ // feature worktree should be in results
+ assert!(
+ items.iter().any(|i| i["branch"] == "feature"),
+ "feature branch should be in results"
+ );
+}
+
+#[rstest]
+fn test_for_each_json_with_failure(repo: TestRepo) {
+ repo.commit("initial");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "for-each", "--format=json", "--", "false"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let json: serde_json::Value =
+ serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
+ let items = json.as_array().unwrap();
+ assert!(!items.is_empty());
+ // All should be failures
+ for item in items {
+ assert_eq!(item["success"], false);
+ }
+}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 041183e64..d29ddcf79 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -4,6 +4,7 @@ use crate::common::{
repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,
repo_with_multi_commit_feature, setup_snapshot_settings, wait_for_file, wait_for_file_content,
};
+use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
@@ -2704,3 +2705,34 @@ fn test_merge_post_merge_pipeline_serial_ordering(mut repo: TestRepo) {
"Step 2 should see step 1's output (serial pipeline), got: {content}"
);
}
+
+// ============================================================================
+// --format=json
+// ============================================================================
+
+#[rstest]
+fn test_merge_json(repo: TestRepo) {
+ let (repo, feature_wt) = merge_scenario(repo);
+
+ let output = repo
+ .wt_command()
+ .args(["merge", "--format=json", "--yes", "--no-hooks"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"
+ {
+ "branch": "feature",
+ "committed": false,
+ "rebased": false,
+ "removed": true,
+ "squashed": false,
+ "target": "main"
+ }
+ "#);
+}
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index 8c2221ac8..6e63adbe7 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -42,6 +42,12 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"picker/mod.rs",
// JSON output for wt switch --format=json
"handle_switch.rs",
+ // JSON output for wt config show --format=json
+ "config/show.rs",
+ // JSON output for wt step for-each --format=json
+ "for_each.rs",
+ // JSON output for wt merge --format=json
+ "merge.rs",
];
/// Substrings that indicate the line is a special case (e.g., in a comment or test reference)
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 518c22c13..002c63aeb 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -4,6 +4,7 @@ use crate::common::{
setup_temp_snapshot_settings, wt_command,
};
use ansi_str::AnsiStr;
+use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
@@ -2755,3 +2756,110 @@ fn restore_dir_permissions(dir: &std::path::Path) {
}
}
}
+
+// ============================================================================
+// --format=json
+// ============================================================================
+
+#[rstest]
+fn test_remove_json(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "feature",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[cfg(not(target_os = "windows"))] // foreground removal with cwd inside the worktree hits directory locking
+#[rstest]
+fn test_remove_json_current(mut repo: TestRepo) {
+ repo.commit("initial");
+ let feature_wt = repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--format=json", "--yes", "--foreground"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_remove_json_branch_only(repo: TestRepo) {
+ repo.commit("initial");
+ // Create a branch without a worktree (already merged into main)
+ repo.git_command()
+ .args(["branch", "orphan-branch"])
+ .run()
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "orphan-branch",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+}
+
+#[cfg(not(target_os = "windows"))]
+#[rstest]
+fn test_remove_json_multi_with_branch_only(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("wt-feature");
+ // Create a branch without a worktree
+ repo.git_command()
+ .args(["branch", "orphan-branch"])
+ .run()
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "wt-feature",
+ "orphan-branch",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 54ef6f8c3..014674c48 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -3,6 +3,7 @@
use crate::common::{
BareRepoTest, TestRepo, make_snapshot_cmd, repo, setup_temp_snapshot_settings,
};
+use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -604,3 +605,177 @@ fn test_prune_skips_default_branch_orphan() {
"Default branch 'main' should not have been pruned"
);
}
+
+// ============================================================================
+// --format=json
+// ============================================================================
+
+#[rstest]
+fn test_prune_dry_run_json(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("merged-a");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--dry-run",
+ "--min-age=0s",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_prune_dry_run_json_empty(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree_with_commit("feature", "f.txt", "content", "feature commit");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--dry-run",
+ "--min-age=0s",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout), @"[]");
+}
+
+#[rstest]
+fn test_prune_json_actual_removal(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("merged-a");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--min-age=0s",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[cfg(not(target_os = "windows"))]
+#[rstest]
+fn test_prune_dry_run_json_current_worktree(mut repo: TestRepo) {
+ repo.commit("initial");
+ let wt_path = repo.add_worktree("current-merged");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--dry-run",
+ "--min-age=0s",
+ "--format=json",
+ ])
+ .current_dir(&wt_path)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_prune_dry_run_json_orphan_branch(repo: TestRepo) {
+ repo.commit("initial");
+ // Orphan branch: integrated but no worktree
+ repo.create_branch("orphan-integrated");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--dry-run",
+ "--min-age=0s",
+ "--format=json",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+}
+
+#[cfg(not(target_os = "windows"))]
+#[rstest]
+fn test_prune_json_current_worktree(mut repo: TestRepo) {
+ repo.commit("initial");
+ let wt_path = repo.add_worktree("current-merged");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--min-age=0s",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .current_dir(&wt_path)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r#""path": "[^"]*""#, r#""path": "<PATH>""#);
+ settings.bind(|| {
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+ });
+}
+
+#[rstest]
+fn test_prune_json_orphan_branch(repo: TestRepo) {
+ repo.commit("initial");
+ repo.create_branch("orphan-integrated");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--min-age=0s",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+
+ assert_snapshot!(String::from_utf8_lossy(&output.stdout));
+}
diff --git a/tests/snapshots/integration__integration_tests__config_state__ci_status_get_json_with_cached_data.snap b/tests/snapshots/integration__integration_tests__config_state__ci_status_get_json_with_cached_data.snap
new file mode 100644
index 000000000..b90a66cbe
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__config_state__ci_status_get_json_with_cached_data.snap
@@ -0,0 +1,9 @@
+---
+source: tests/integration_tests/config_state.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+{
+ "status": "passed",
+ "source": "pr",
+ "stale": false
+}
diff --git a/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap b/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap
new file mode 100644
index 000000000..919553ab4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__config_state__logs_get_json_with_files.snap
@@ -0,0 +1,20 @@
+---
+source: tests/integration_tests/config_state.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+{
+ "command_log": [
+ {
+ "file": "commands.jsonl",
+ "modified_at": "<TIMESTAMP>",
+ "size": "<SIZE>"
+ }
+ ],
+ "hook_output": [
+ {
+ "file": "main-user-post-start-server.log",
+ "modified_at": "<TIMESTAMP>",
+ "size": "<SIZE>"
+ }
+ ]
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_show.snap b/tests/snapshots/integration__integration_tests__help__help_config_show.snap
index 4597a5cd1..227ae740a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_show.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_show.snap
@@ -44,6 +44,16 @@ Usage: wt config show [OPTIONS]
-h, --help
Print help (see a summary with '-h')
+Output:
+ --format <FORMAT>
+ Output format (text, json)
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
index e9c5b2403..38352a062 100644
--- a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
@@ -76,6 +76,17 @@ Automation:
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after merge completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
index 177d71616..b340301f0 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
@@ -78,6 +78,17 @@ Usage: wt merge [OPTIONS] [TARGET]
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after merge completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap b/tests/snapshots/integration__integration_tests__help__help_merge_short.snap
index 3be840b79..f12bef1ef 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_short.snap
@@ -49,8 +49,9 @@ Usage: wt merge [OPTIONS] [TARGET]
-h, --help Print help (see more with '--help')
Automation:
- -y, --yes Skip approval prompts
- --no-hooks Skip hooks
+ -y, --yes Skip approval prompts
+ --no-hooks Skip hooks
+ --format <FORMAT> Output format [default: text] [possible values: text, json]
Global Options:
-C <path> Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index e5b99fd1f..222eb670e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -67,6 +67,17 @@ Usage: wt remove [OPTIONS] [BRANCHES]...
--no-hooks
Skip hooks
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after removal completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
index 52322e689..27150f809 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_short.snap
@@ -47,8 +47,9 @@ Usage: wt remove [OPTIONS] [BRANCHES]...
-h, --help Print help (see more with '--help')
Automation:
- -y, --yes Skip approval prompts
- --no-hooks Skip hooks
+ -y, --yes Skip approval prompts
+ --no-hooks Skip hooks
+ --format <FORMAT> Output format [default: text] [possible values: text, json]
Global Options:
-C <path> Working directory for this command
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json.snap b/tests/snapshots/integration__integration_tests__remove__remove_json.snap
new file mode 100644
index 000000000..81c368f38
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_json.snap
@@ -0,0 +1,12 @@
+---
+source: tests/integration_tests/remove.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "feature",
+ "branch_deleted": true,
+ "kind": "worktree",
+ "path": "<PATH>"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap
new file mode 100644
index 000000000..8ea119c22
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap
@@ -0,0 +1,12 @@
+---
+source: tests/integration_tests/remove.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "orphan-branch",
+ "branch_deleted": true,
+ "kind": "branch_only",
+ "pruned": false
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap
new file mode 100644
index 000000000..81c368f38
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap
@@ -0,0 +1,12 @@
+---
+source: tests/integration_tests/remove.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "feature",
+ "branch_deleted": true,
+ "kind": "worktree",
+ "path": "<PATH>"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap
new file mode 100644
index 000000000..c22361d66
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap
@@ -0,0 +1,18 @@
+---
+source: tests/integration_tests/remove.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "wt-feature",
+ "branch_deleted": true,
+ "kind": "worktree",
+ "path": "<PATH>"
+ },
+ {
+ "branch": "orphan-branch",
+ "branch_deleted": true,
+ "kind": "branch_only",
+ "pruned": false
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap
new file mode 100644
index 000000000..5c74e0ce1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json.snap
@@ -0,0 +1,13 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "merged-a",
+ "kind": "worktree",
+ "path": "<PATH>",
+ "reason": "same commit as",
+ "target": "main"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap
new file mode 100644
index 000000000..1965321e1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_current_worktree.snap
@@ -0,0 +1,13 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "current-merged",
+ "kind": "current",
+ "path": "<PATH>",
+ "reason": "same commit as",
+ "target": "main"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap
new file mode 100644
index 000000000..15200150a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_json_orphan_branch.snap
@@ -0,0 +1,13 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "orphan-integrated",
+ "kind": "branch_only",
+ "path": null,
+ "reason": "same commit as",
+ "target": "main"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap
new file mode 100644
index 000000000..1feec03df
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_actual_removal.snap
@@ -0,0 +1,11 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "merged-a",
+ "kind": "worktree",
+ "path": "<PATH>"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap
new file mode 100644
index 000000000..45c22910b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_current_worktree.snap
@@ -0,0 +1,11 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "current-merged",
+ "kind": "current",
+ "path": "<PATH>"
+ }
+]
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap
new file mode 100644
index 000000000..c6be38604
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_json_orphan_branch.snap
@@ -0,0 +1,11 @@
+---
+source: tests/integration_tests/step_prune.rs
+expression: "String::from_utf8_lossy(&output.stdout)"
+---
+[
+ {
+ "branch": "orphan-integrated",
+ "kind": "branch_only",
+ "path": null
+ }
+]