Skip to content

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

feat: add --format=json to seven step + hook commands (#2560)

Maximilian Roos275eaead9162
diff --git a/docs/content/step.md b/docs/content/step.md
index 4713e8dc8..832614746 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -152,6 +152,18 @@ Usage: <b><span class=c>wt step commit</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>Automation:</span></b>
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format
+
+ JSON prints structured result to stdout after the commit 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
@@ -235,6 +247,18 @@ Usage: <b><span class=c>wt step squash</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>Automation:</span></b>
+ <b><span class=c>--format</span></b><span class=c> &lt;FORMAT&gt;</span>
+ Output format
+
+ JSON prints structured result to stdout after the squash 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
@@ -437,6 +461,18 @@ Usage: <b><span class=c>wt step copy-ignored</span></b> <span class=c>[OPTIONS]<
<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
+
+ JSON prints structured result to stdout after the copy 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
@@ -832,6 +868,18 @@ Usage: <b><span class=c>wt step relocate</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
+
+ JSON prints structured result to stdout after the relocate 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/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index ef1e45a1c..4278f655c 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -147,6 +147,18 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Automation:
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after the commit completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
@@ -234,6 +246,18 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Automation:
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after the squash completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
@@ -446,6 +470,18 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Automation:
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after the copy completes.
+
+ Possible values:
+ - text: Human-readable text output
+ - json: JSON output
+
+ [default: text]
+
Global Options:
-C <path>
Working directory for this command
@@ -875,6 +911,18 @@ Options:
-h, --help
Print help (see a summary with '-h')
+Automation:
+ --format <FORMAT>
+ Output format
+
+ JSON prints structured result to stdout after the relocate 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/src/cli/hook.rs b/src/cli/hook.rs
index 0fd5ac001..7a4d52fbd 100644
--- a/src/cli/hook.rs
+++ b/src/cli/hook.rs
@@ -81,6 +81,12 @@ pub enum HookCommand {
/// Show expanded commands with current variables
#[arg(long)]
expanded: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout — one record per configured command.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// Internal: run a serialized pipeline from stdin
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 6c019ec9f..ec342945c 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -25,6 +25,12 @@ pub struct CommitArgs {
/// Render prompt to stdout without running LLM
#[arg(long, hide = true)]
pub(crate) show_prompt: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the commit completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ pub(crate) format: crate::cli::SwitchFormat,
}
#[derive(Args)]
@@ -54,6 +60,12 @@ pub struct SquashArgs {
/// Render prompt to stdout without running LLM
#[arg(long, hide = true)]
pub(crate) show_prompt: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the squash completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ pub(crate) format: crate::cli::SwitchFormat,
}
// Ordering: `wt merge` pipeline steps first (commit → squash → rebase → push),
@@ -165,6 +177,12 @@ $ wt step rebase develop # Rebase onto develop
/// Defaults to default branch.
#[arg(add = crate::completion::branch_value_completer())]
target: Option<String>,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the rebase completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// Fast-forward target to current branch
@@ -195,6 +213,12 @@ Similar to `git push . HEAD:<target>`, but uses `receive.denyCurrentBranch=updat
/// Allow fast-forward (default)
#[arg(long, overrides_with = "no_ff", hide = true)]
ff: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the push completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// Show all changes since branching
@@ -360,6 +384,12 @@ The `.worktreeinclude` pattern is shared with [Claude Code on desktop](https://c
/// Overwrite existing files in destination
#[arg(long)]
force: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the copy completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// \[experimental\] Evaluate a template expression
@@ -646,6 +676,12 @@ Note: This command is experimental and may change in future versions.
/// Moves blocking paths to `<path>.bak-<timestamp>`.
#[arg(long)]
clobber: bool,
+
+ /// Output format
+ ///
+ /// JSON prints structured result to stdout after the relocate completes.
+ #[arg(long, default_value = "text", help_heading = "Automation")]
+ format: crate::cli::SwitchFormat,
},
/// Catch-all for alias lookup
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index bc66f1bb2..2d6eb7087 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -15,6 +15,17 @@ use super::template_vars::TemplateVars;
// Re-export StageMode from config for use by CLI
pub use worktrunk::config::StageMode;
+/// Outcome of a successful commit operation. Returned so callers (e.g.
+/// `step commit --format=json`) can render structured output.
+///
+/// `stage_mode` is the *resolved* mode that was actually applied (CLI flag
+/// merged with config defaults), not the user-supplied flag.
+pub struct CommitOutcome {
+ pub sha: String,
+ pub message: String,
+ pub stage_mode: StageMode,
+}
+
/// Whether pre/post-commit hooks run, and — if not — whether to print the skip message.
/// Two distinct paths disable hooks: `--no-hooks` (we own the skip message) and declined
/// approval (the caller already printed its own message).
@@ -121,7 +132,7 @@ impl<'a> CommitGenerator<'a> {
show_progress: bool,
show_no_squash_note: bool,
stage_mode: StageMode,
- ) -> anyhow::Result<()> {
+ ) -> anyhow::Result<CommitOutcome> {
// Fail early if nothing is staged (avoids confusing LLM prompt with empty diff)
if !wt.has_staged_changes()? {
anyhow::bail!("Nothing to commit");
@@ -172,17 +183,22 @@ impl<'a> CommitGenerator<'a> {
wt.run_command(&["commit", "-m", &commit_message])
.context("Failed to commit")?;
- let commit_hash = wt
- .run_command(&["rev-parse", "--short", "HEAD"])?
- .trim()
- .to_string();
+ let commit_sha = wt.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
+ // Display uses `--short` to honor `core.abbrev` and auto-extend for
+ // ambiguous prefixes; the JSON payload carries the full SHA.
+ let commit_hash = wt.run_command(&["rev-parse", "--short", "HEAD"])?;
+ let commit_hash = commit_hash.trim();
eprintln!(
"{}",
success_message(cformat!("Committed changes @ <dim>{commit_hash}</>"))
);
- Ok(())
+ Ok(CommitOutcome {
+ sha: commit_sha,
+ message: commit_message,
+ stage_mode,
+ })
}
}
@@ -194,7 +210,7 @@ impl CommitOptions<'_> {
/// --squash` batching post-commit + post-remove + post-switch + post-merge)
/// share one announce line; standalone callers (e.g. `wt commit`)
/// construct an announcer of their own and flush right after.
- pub fn commit(self, announcer: &mut HookAnnouncer<'_>) -> anyhow::Result<()> {
+ pub fn commit(self, announcer: &mut HookAnnouncer<'_>) -> anyhow::Result<CommitOutcome> {
let project_config = self.ctx.repo.load_project_config()?;
let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());
let (user_cfg, proj_cfg) = super::hooks::lookup_hook_configs(
@@ -255,7 +271,7 @@ impl CommitOptions<'_> {
}
let effective_config = self.ctx.commit_generation();
- CommitGenerator::new(&effective_config).commit_staged_changes(
+ let outcome = CommitGenerator::new(&effective_config).commit_staged_changes(
&wt,
true, // show_progress
self.show_no_squash_note,
@@ -268,7 +284,7 @@ impl CommitOptions<'_> {
announcer.register(self.ctx, HookType::PostCommit, &extra_vars, None)?;
}
- Ok(())
+ Ok(outcome)
}
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 17f009362..9970ded1d 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -367,14 +367,17 @@ pub fn run_hook(
}
/// Handle `wt hook show` command - display configured hooks
-pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyhow::Result<()> {
+pub fn handle_hook_show(
+ hook_type_filter: Option<&str>,
+ expanded: bool,
+ format: crate::cli::SwitchFormat,
+) -> anyhow::Result<()> {
use crate::help_pager::show_help_in_pager;
let repo = Repository::current().context("Failed to show hooks")?;
- let LoadedConfigs {
- user: config,
- project: project_config,
- } = LoadedConfigs::load(&repo).context("Failed to load configs")?;
+ let configs = LoadedConfigs::load(&repo).context("Failed to load configs")?;
+ let config: &UserConfig = configs.user;
+ let project_config: Option<&ProjectConfig> = configs.project;
let approvals = Approvals::load().context("Failed to load approvals")?;
let project_id = repo.project_identifier().ok();
@@ -403,6 +406,18 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
};
let ctx = env.as_ref().map(|e| e.context(false));
+ if format == crate::cli::SwitchFormat::Json {
+ return emit_hook_show_json(
+ config,
+ project_config,
+ &approvals,
+ project_id.as_deref(),
+ filter,
+ ctx.as_ref(),
+ expanded,
+ );
+ }
+
let mut output = String::new();
// Render user hooks
@@ -428,6 +443,89 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho
Ok(())
}
+/// Emit configured hooks as a JSON array of structured records.
+///
+/// Each record carries the hook type, source (user or project), optional name,
+/// raw template, project approval status, and — when `--expanded` was passed —
+/// the rendered command preview.
+#[allow(clippy::too_many_arguments)]
+fn emit_hook_show_json(
+ user_config: &UserConfig,
+ project_config: Option<&ProjectConfig>,
+ approvals: &Approvals,
+ project_id: Option<&str>,
+ filter: Option<HookType>,
+ ctx: Option<&CommandContext>,
+ expanded: bool,
+) -> anyhow::Result<()> {
+ let mut entries: Vec<serde_json::Value> = Vec::new();
+
+ let mut emit = |hook_type: HookType,
+ source: &'static str,
+ cfg: &CommandConfig,
+ needs_approval_for: Option<(&Approvals, Option<&str>)>|
+ -> anyhow::Result<()> {
+ for cmd in cfg.commands() {
+ let needs_approval = needs_approval_for
+ .map(|(approvals, project_id)| {
+ project_id.is_some_and(|pid| !approvals.is_command_approved(pid, &cmd.template))
+ })
+ .unwrap_or(false);
+
+ let mut obj = serde_json::json!({
+ "type": hook_type.to_string(),
+ "source": source,
+ "name": cmd.name,
+ "template": cmd.template,
+ "needs_approval": needs_approval,
+ });
+
+ if expanded && let Some(command_ctx) = ctx {
+ let rendered = expand_command_template(
+ &cmd.template,
+ command_ctx,
+ hook_type,
+ cmd.name.as_deref(),
+ )?;
+ obj["expanded"] = serde_json::Value::String(rendered);
+ }
+
+ entries.push(obj);
+ }
+ Ok(())
+ };
+
+ // User hooks
+ let user_hooks = &user_config.hooks;
+ for hook_type in HookType::iter() {
+ if let Some(f) = filter
+ && f != hook_type
+ {
+ continue;
+ }
+ if let Some(cfg) = user_hooks.get(hook_type) {
+ emit(hook_type, "user", cfg, None)?;
+ }
+ }
+
+ // Project hooks
+ if let Some(project) = project_config {
+ for hook_type in HookType::iter() {
+ if let Some(f) = filter
+ && f != hook_type
+ {
+ continue;
+ }
+ if let Some(cfg) = project.hooks.get(hook_type) {
+ emit(hook_type, "project", cfg, Some((approvals, project_id)))?;
+ }
+ }
+ }
+
+ println!("{}", serde_json::to_string_pretty(&entries)?);
+ Ok(())
+}
+
/// Render user hooks section
fn render_user_hooks(
out: &mut String,
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 7f95845f1..dae53c590 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -219,7 +219,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
options.warn_about_untracked = stage_mode == super::commit::StageMode::All;
options.show_no_squash_note = true;
- options.commit(&mut announcer)?;
+ let _ = options.commit(&mut announcer)?;
true // Committed directly
}
} else {
@@ -238,7 +238,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
Some(stage_mode),
&mut announcer,
)?,
- super::step_commands::SquashResult::Squashed
+ super::step_commands::SquashResult::Squashed { .. }
)
} else {
false
@@ -249,7 +249,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
// Auto-rebase onto target
matches!(
super::step_commands::handle_rebase(Some(&target_branch))?,
- super::step_commands::RebaseResult::Rebased
+ super::step_commands::RebaseResult::Rebased { .. }
)
} else {
// --no-rebase: verify already rebased, fail if not
@@ -284,10 +284,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
});
if !ff {
// Create a merge commit on the target branch via commit-tree + update-ref
- handle_no_ff_merge(Some(&target_branch), operations, &current_branch)?;
+ let _ = handle_no_ff_merge(Some(&target_branch), operations, &current_branch)?;
} else {
// Fast-forward push to target branch
- handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?;
+ let _ = handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?;
}
let removed = finish_after_merge(
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 252607db8..cc3bfa6a0 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -56,7 +56,10 @@ impl RelocationCandidate {
/// Result of gathering relocation candidates.
pub struct GatherResult {
pub candidates: Vec<RelocationCandidate>,
- pub template_errors: usize,
+ /// Branches whose `worktree-path` template failed to expand. Counted in
+ /// the human-readable text output and surfaced as `skipped` entries with
+ /// `reason: "template_error"` in JSON output.
+ pub template_error_branches: Vec<String>,
}
/// A candidate that passed pre-checks (not locked, not dirty or committed).
@@ -79,6 +82,21 @@ struct TempRelocation {
original_path: PathBuf,
}
+/// A worktree that was successfully relocated.
+pub struct RelocatedEntry {
+ pub branch: String,
+ pub from: PathBuf,
+ pub to: PathBuf,
+}
+
+/// A worktree that was skipped during validation or execution. `reason` is a
+/// short stable identifier suitable for JSON / scripting (e.g. `"locked"`,
+/// `"uncommitted"`, `"target_blocked"`).
+pub struct SkippedEntry {
+ pub branch: String,
+ pub reason: &'static str,
+}
+
/// Executes relocations in dependency order, handling cycles via temp moves.
///
/// Git commands route through `repo.worktree_at(path).run_command(...)` rather
@@ -99,9 +117,19 @@ pub struct RelocationExecutor<'a> {
temp_relocated: Vec<TempRelocation>,
/// Temp directory for cycle breaking
temp_dir: PathBuf,
- /// Counters for summary
- pub skipped: usize,
- pub relocated: usize,
+ /// Per-branch records (used for JSON output and counting).
+ pub relocated_entries: Vec<RelocatedEntry>,
+ pub skipped_entries: Vec<SkippedEntry>,
+}
+
+impl RelocationExecutor<'_> {
+ pub fn relocated_count(&self) -> usize {
+ self.relocated_entries.len()
+ }
+
+ pub fn skipped_count(&self) -> usize {
+ self.skipped_entries.len()
+ }
}
// ============================================================================
@@ -140,7 +168,7 @@ pub fn gather_candidates(
// Find mismatched worktrees
let mut candidates = Vec::new();
- let mut template_errors = 0;
+ let mut template_error_branches: Vec<String> = Vec::new();
for wt in worktrees {
let Some(branch) = wt.branch.as_deref() else {
@@ -170,14 +198,14 @@ pub fn gather_candidates(
))
);
eprintln!("{}", e);
- template_errors += 1;
+ template_error_branches.push(branch.to_string());
}
}
}
Ok(GatherResult {
candidates,
- template_errors,
+ template_error_branches,
})
}
@@ -188,7 +216,7 @@ pub fn gather_candidates(
/// Result of validating candidates.
pub struct ValidationResult {
pub validated: Vec<ValidatedCandidate>,
- pub skipped: usize,
+ pub skipped: Vec<SkippedEntry>,
}
/// Check each candidate for locked/dirty state and optionally auto-commit.
@@ -202,7 +230,7 @@ pub fn validate_candidates(
repo_path: &Path,
) -> anyhow::Result<ValidationResult> {
let mut validated = Vec::new();
- let mut skipped = 0;
+ let mut skipped: Vec<SkippedEntry> = Vec::new();
for candidate in candidates {
let branch = candidate.branch();
@@ -218,7 +246,10 @@ pub fn validate_candidates(
"{}",
warning_message(cformat!("Skipping <bold>{branch}</> (locked{reason_text})"))
);
- skipped += 1;
+ skipped.push(SkippedEntry {
+ branch: branch.to_string(),
+ reason: "locked",
+ });
continue;
}
@@ -254,7 +285,10 @@ pub fn validate_candidates(
"To auto-commit changes before relocating, use <underline>--commit</>"
))
);
- skipped += 1;
+ skipped.push(SkippedEntry {
+ branch: branch.to_string(),
+ reason: "uncommitted",
+ });
continue;
}
}
@@ -295,7 +329,7 @@ impl<'a> RelocationExecutor<'a> {
}
let mut blocked: HashSet<usize> = HashSet::new();
- let mut skipped = 0;
+ let mut skipped_entries: Vec<SkippedEntry> = Vec::new();
// Classify targets and handle blockers
for (i, candidate) in validated.iter().enumerate() {
@@ -327,7 +361,10 @@ impl<'a> RelocationExecutor<'a> {
let hint = cformat!("Relocate or remove <underline>{occupant_name}</> first");
eprintln!("{}", hint_message(hint));
blocked.insert(i);
- skipped += 1;
+ skipped_entries.push(SkippedEntry {
+ branch: branch.to_string(),
+ reason: "target_is_worktree",
+ });
continue;
}
@@ -367,7 +404,10 @@ impl<'a> RelocationExecutor<'a> {
))
);
blocked.insert(i);
- skipped += 1;
+ skipped_entries.push(SkippedEntry {
+ branch: branch.to_string(),
+ reason: "target_blocked",
+ });
}
}
@@ -379,8 +419,8 @@ impl<'a> RelocationExecutor<'a> {
moved: HashSet::new(),
temp_relocated: Vec::new(),
temp_dir,
- skipped,
- relocated: 0,
+ relocated_entries: Vec::new(),
+ skipped_entries,
})
}
@@ -413,7 +453,10 @@ impl<'a> RelocationExecutor<'a> {
);
eprintln!("{}", warning_message(msg));
self.blocked.insert(i);
- self.skipped += 1;
+ self.skipped_entries.push(SkippedEntry {
+ branch: branch.to_string(),
+ reason: "target_occupied",
+ });
}
}
}
@@ -499,7 +542,11 @@ impl<'a> RelocationExecutor<'a> {
}
self.moved.insert(idx);
- self.relocated += 1;
+ self.relocated_entries.push(RelocatedEntry {
+ branch,
+ from: src_path,
+ to: dest_path,
+ });
Ok(())
}
@@ -613,7 +660,11 @@ impl<'a> RelocationExecutor<'a> {
let msg = cformat!("Relocated <bold>{branch}</>: {src_display} → {dest_display}");
eprintln!("{}", success_message(msg));
- self.relocated += 1;
+ self.relocated_entries.push(RelocatedEntry {
+ branch: branch.to_string(),
+ from: temp.original_path,
+ to: candidate.expected_path.clone(),
+ });
}
Ok(())
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 5c33f947a..b93a17f04 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -37,7 +37,7 @@ use worktrunk::styling::{
use super::command_approval::approve_or_skip;
use super::command_executor::FailureStrategy;
-use super::commit::{CommitGenerator, CommitOptions, HookGate, StageMode};
+use super::commit::{CommitGenerator, CommitOptions, CommitOutcome, HookGate, StageMode};
use super::context::CommandEnv;
use super::hooks::{HookAnnouncer, execute_hook};
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
@@ -55,12 +55,13 @@ pub fn step_commit(
stage: Option<StageMode>,
show_prompt: bool,
dry_run: bool,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<Option<CommitOutcome>> {
// --show-prompt and --dry-run skip hooks and the commit itself; --dry-run still
// mirrors --stage against a temp index so the previewed prompt matches what a real
- // run would send the LLM.
+ // run would send the LLM. Neither path produces a CommitOutcome.
if show_prompt || dry_run {
- return preview_commit(stage, dry_run);
+ preview_commit(stage, dry_run)?;
+ return Ok(None);
}
// Load config once, run LLM setup prompt, then reuse config
@@ -95,8 +96,9 @@ pub fn step_commit(
options.warn_about_untracked = stage_mode == StageMode::All;
let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, false);
- options.commit(&mut announcer)?;
- announcer.flush()
+ let outcome = options.commit(&mut announcer)?;
+ announcer.flush()?;
+ Ok(Some(outcome))
}
/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.
@@ -213,8 +215,13 @@ fn print_dry_run(
/// Result of a squash operation
#[derive(Debug, Clone)]
pub enum SquashResult {
- /// Squash or commit occurred
- Squashed,
+ /// Squash or commit occurred. Carries the resulting commit's SHA, message,
+ /// and resolved stage mode so callers can render structured output.
+ Squashed {
+ sha: String,
+ message: String,
+ stage_mode: StageMode,
+ },
/// Nothing to squash: no commits ahead of target branch
NoCommitsAhead(String),
/// Nothing to squash: already a single commit
@@ -344,8 +351,16 @@ pub fn handle_squash(
if commit_count == 0 && has_staged {
// Just staged changes, no commits - commit them directly (no squashing needed)
- generator.commit_staged_changes(&wt, true, true, stage_mode)?;
- return Ok(SquashResult::Squashed);
+ let CommitOutcome {
+ sha,
+ message,
+ stage_mode,
+ } = generator.commit_staged_changes(&wt, true, true, stage_mode)?;
+ return Ok(SquashResult::Squashed {
+ sha,
+ message,
+ stage_mode,
+ });
}
if commit_count == 1 && !has_staged {
@@ -457,11 +472,11 @@ pub fn handle_squash(
repo.run_command(&["commit", "-m", &commit_message])
.context("Failed to create squash commit")?;
- // Get commit hash for display
- let commit_hash = repo
- .run_command(&["rev-parse", "--short", "HEAD"])?
- .trim()
- .to_string();
+ // Full SHA for the JSON payload, plus a `--short`-rendered hash for the
+ // success line (honors `core.abbrev` and auto-extends for ambiguous prefixes).
+ let commit_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
+ let commit_hash = repo.run_command(&["rev-parse", "--short", "HEAD"])?;
+ let commit_hash = commit_hash.trim();
// Show success immediately after completing the squash
eprintln!(
@@ -475,7 +490,11 @@ pub fn handle_squash(
announcer.register(&ctx, HookType::PostCommit, &extra_vars, None)?;
}
- Ok(SquashResult::Squashed)
+ Ok(SquashResult::Squashed {
+ sha: commit_sha,
+ message: commit_message,
+ stage_mode,
+ })
}
/// Handle `wt step squash --show-prompt`
@@ -545,8 +564,8 @@ fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
/// Result of a rebase operation
pub enum RebaseResult {
- /// Rebase occurred (either true rebase or fast-forward)
- Rebased,
+ /// Rebase occurred. `fast_forward` distinguishes the two flavors.
+ Rebased { target: String, fast_forward: bool },
/// Already up-to-date with target branch
UpToDate(String),
}
@@ -623,7 +642,10 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
};
eprintln!("{}", success_message(msg));
- Ok(RebaseResult::Rebased)
+ Ok(RebaseResult::Rebased {
+ target: integration_target,
+ fast_forward: is_fast_forward,
+ })
}
/// Handle `wt step diff` command
@@ -833,6 +855,7 @@ pub fn step_copy_ignored(
to: Option<&str>,
dry_run: bool,
force: bool,
+ format: crate::cli::SwitchFormat,
) -> anyhow::Result<()> {
// Self-lower only when we're running inside a background hook pipeline
// (parent `wt` sets `WORKTRUNK_FOREGROUND=-1` on the detached runner).
@@ -842,6 +865,7 @@ pub fn step_copy_ignored(
if worktrunk::priority::in_background_hook() {
worktrunk::priority::lower_current_process();
}
+ let json_mode = format == crate::cli::SwitchFormat::Json;
let repo = Repository::current()?;
let copy_ignored_config = resolve_copy_ignored_config(&repo)?;
@@ -881,10 +905,22 @@ pub fn step_copy_ignored(
};
if source_path == dest_path {
- eprintln!(
- "{}",
- info_message("Source and destination are the same worktree")
- );
+ if json_mode {
+ let payload = serde_json::json!({
+ "outcome": "same_worktree",
+ "from": source_path,
+ "to": dest_path,
+ "entries": Vec::<serde_json::Value>::new(),
+ "files": 0,
+ "bytes": 0,
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ } else {
+ eprintln!(
+ "{}",
+ info_message("Source and destination are the same worktree")
+ );
+ }
return Ok(());
}
@@ -901,14 +937,49 @@ pub fn step_copy_ignored(
)?;
if entries_to_copy.is_empty() {
- eprintln!("{}", info_message("No matching files to copy"));
+ if json_mode {
+ let payload = serde_json::json!({
+ "outcome": if dry_run { "planned" } else { "copied" },
+ "dry_run": dry_run,
+ "from": source_path,
+ "to": dest_path,
+ "entries": Vec::<serde_json::Value>::new(),
+ "files": 0,
+ "bytes": 0,
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ } else {
+ eprintln!("{}", info_message("No matching files to copy"));
+ }
return Ok(());
}
let verbose = verbosity();
- // Show entries in verbose or dry-run mode
- if verbose >= 1 || dry_run {
+ if dry_run {
+ if json_mode {
+ let entries: Vec<_> = entries_to_copy
+ .iter()
+ .map(|(src_entry, is_dir)| {
+ let relative = src_entry
+ .strip_prefix(&source_path)
+ .unwrap_or(src_entry.as_path());
+ serde_json::json!({
+ "path": relative,
+ "kind": if *is_dir { "dir" } else { "file" },
+ })
+ })
+ .collect();
+ let payload = serde_json::json!({
+ "outcome": "planned",
+ "dry_run": true,
+ "from": source_path,
+ "to": dest_path,
+ "entries": entries,
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ return Ok(());
+ }
let items: Vec<String> = entries_to_copy
.iter()
.map(|(src_entry, is_dir)| {
@@ -920,23 +991,44 @@ pub fn step_copy_ignored(
})
.collect();
let entry_word = if items.len() == 1 { "entry" } else { "entries" };
- let verb = if dry_run { "Would copy" } else { "Copying" };
eprintln!(
"{}",
info_message(format!(
- "{verb} {} {}:\n{}",
+ "Would copy {} {}:\n{}",
+ items.len(),
+ entry_word,
+ format_with_gutter(&items.join("\n"), None)
+ ))
+ );
+ return Ok(());
+ }
+
+ // Show entries in verbose mode (text only — JSON mode emits the full list at the end).
+ if verbose >= 1 && !json_mode {
+ let items: Vec<String> = entries_to_copy
+ .iter()
+ .map(|(src_entry, is_dir)| {
+ let relative = src_entry
+ .strip_prefix(&source_path)
+ .unwrap_or(src_entry.as_path());
+ let entry_type = if *is_dir { "dir" } else { "file" };
+ format!("{} ({})", format_path_for_display(relative), entry_type)
+ })
+ .collect();
+ let entry_word = if items.len() == 1 { "entry" } else { "entries" };
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Copying {} {}:\n{}",
items.len(),
entry_word,
format_with_gutter(&items.join("\n"), None)
))
);
- if dry_run {
- return Ok(());
- }
}
// `start` auto-detects the TTY; verbose/dry-run already print enough.
- let progress = if verbose >= 1 || dry_run {
+ let progress = if verbose >= 1 || json_mode {
Progress::disabled()
} else {
Progress::start("Copying")
@@ -976,15 +1068,43 @@ pub fn step_copy_ignored(
}
progress.finish();
- // Show summary
- let file_word = if copied_count == 1 { "file" } else { "files" };
- eprintln!(
- "{}",
- success_message(format!(
- "Copied {copied_count} {file_word} · {}",
- format_bytes(copied_bytes)
- ))
- );
+ if json_mode {
+ // `entries` mirrors dry-run: the top-level units selected for copy
+ // (files and dirs). `files` counts the actual leaves written
+ // (recursive + skipping pre-existing files), `bytes` sums their size.
+ let entries: Vec<_> = entries_to_copy
+ .iter()
+ .map(|(src_entry, is_dir)| {
+ let relative = src_entry
+ .strip_prefix(&source_path)
+ .unwrap_or(src_entry.as_path());
+ serde_json::json!({
+ "path": relative,
+ "kind": if *is_dir { "dir" } else { "file" },
+ })
+ })
+ .collect();
+ let payload = serde_json::json!({
+ "outcome": "copied",
+ "dry_run": false,
+ "from": source_path,
+ "to": dest_path,
+ "entries": entries,
+ "files": copied_count,
+ "bytes": copied_bytes,
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ } else {
+ // Show summary
+ let file_word = if copied_count == 1 { "file" } else { "files" };
+ eprintln!(
+ "{}",
+ success_message(format!(
+ "Copied {copied_count} {file_word} · {}",
+ format_bytes(copied_bytes)
+ ))
+ );
+ }
Ok(())
}
@@ -1967,12 +2087,15 @@ pub fn step_relocate(
dry_run: bool,
commit: bool,
clobber: bool,
+ format: crate::cli::SwitchFormat,
) -> anyhow::Result<()> {
use super::relocate::{
GatherResult, RelocationExecutor, ValidationResult, gather_candidates, show_all_skipped,
show_dry_run_preview, show_no_relocations_needed, show_summary, validate_candidates,
};
+ let json_mode = format == crate::cli::SwitchFormat::Json;
+
let repo = Repository::current()?;
let config = UserConfig::load()?;
let default_branch = repo.default_branch().unwrap_or_default();
@@ -1988,26 +2111,58 @@ pub fn step_relocate(
// Phase 1: Gather candidates (worktrees not at expected paths)
let GatherResult {
candidates,
- template_errors,
+ template_error_branches,
} = gather_candidates(&repo, &config, &branches)?;
+ let template_skips: Vec<super::relocate::SkippedEntry> = template_error_branches
+ .iter()
+ .map(|b| super::relocate::SkippedEntry {
+ branch: b.clone(),
+ reason: "template_error",
+ })
+ .collect();
+
if candidates.is_empty() {
- show_no_relocations_needed(template_errors);
+ if json_mode {
+ print_relocate_json(&[], &template_skips, dry_run)?;
+ } else {
+ show_no_relocations_needed(template_error_branches.len());
+ }
return Ok(());
}
// Dry run: show preview and exit
if dry_run {
- show_dry_run_preview(&candidates);
+ if json_mode {
+ let planned: Vec<_> = candidates
+ .iter()
+ .map(|c| RelocatedEntryView {
+ branch: c.branch().to_string(),
+ from: c.wt.path.clone(),
+ to: c.expected_path.clone(),
+ })
+ .collect();
+ print_relocate_json(&planned, &template_skips, true)?;
+ } else {
+ show_dry_run_preview(&candidates);
+ }
return Ok(());
}
// Phase 2: Validate candidates (check locked/dirty, optionally auto-commit)
- let ValidationResult { validated, skipped } =
- validate_candidates(&repo, &config, candidates, commit, &repo_path)?;
+ let ValidationResult {
+ validated,
+ skipped: validation_skipped,
+ } = validate_candidates(&repo, &config, candidates, commit, &repo_path)?;
if validated.is_empty() {
- show_all_skipped(skipped);
+ if json_mode {
+ let mut all_skipped = template_skips;
+ all_skipped.extend(validation_skipped);
+ print_relocate_json(&[], &all_skipped, false)?;
+ } else {
+ show_all_skipped(validation_skipped.len());
+ }
return Ok(());
}
@@ -2016,10 +2171,53 @@ pub fn step_relocate(
let cwd = std::env::current_dir().ok();
executor.execute(&default_branch, cwd.as_deref())?;
- // Show summary
- let total_skipped = skipped + executor.skipped;
- show_summary(executor.relocated, total_skipped);
+ if json_mode {
+ let relocated_views: Vec<RelocatedEntryView> = executor
+ .relocated_entries
+ .iter()
+ .map(|e| RelocatedEntryView {
+ branch: e.branch.clone(),
+ from: e.from.clone(),
+ to: e.to.clone(),
+ })
+ .collect();
+ let mut all_skipped = template_skips;
+ all_skipped.extend(validation_skipped);
+ all_skipped.extend(executor.skipped_entries);
+ print_relocate_json(&relocated_views, &all_skipped, false)?;
+ } else {
+ let total_skipped = validation_skipped.len() + executor.skipped_count();
+ show_summary(executor.relocated_count(), total_skipped);
+ }
+
+ Ok(())
+}
+
+/// Internal projection of a relocation event for JSON output.
+struct RelocatedEntryView {
+ branch: String,
+ from: PathBuf,
+ to: PathBuf,
+}
+fn print_relocate_json(
+ entries: &[RelocatedEntryView],
+ skipped: &[super::relocate::SkippedEntry],
+ dry_run: bool,
+) -> anyhow::Result<()> {
+ let payload = serde_json::json!({
+ "dry_run": dry_run,
+ "entries": entries.iter().map(|e| serde_json::json!({
+ "branch": e.branch,
+ "from": e.from,
+ "to": e.to,
+ })).collect::<Vec<_>>(),
+ "skipped": skipped.iter().map(|s| serde_json::json!({
+ "branch": s.branch,
+ "reason": s.reason,
+ })).collect::<Vec<_>>(),
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
Ok(())
}
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index f8c944053..18bf59731 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -90,7 +90,7 @@ mod types;
// Re-export public types and functions
pub use finish::{FinishAfterMergeArgs, finish_after_merge};
-pub use push::{PushKind, handle_no_ff_merge, handle_push};
+pub use push::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
pub use resolve::{
compute_worktree_path, is_worktree_at_expected_path, offer_bare_repo_worktree_path_fix,
path_mismatch, resolve_worktree_arg, worktree_display_name,
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index e85dfbb44..742cb463b 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -44,6 +44,22 @@ impl PushKind {
}
}
+/// Outcome of a push or no-ff merge, returned for JSON output.
+pub struct PushResult {
+ pub target: String,
+ pub commit_count: usize,
+ pub outcome: PushOutcome,
+}
+
+pub enum PushOutcome {
+ /// Target was fast-forwarded to HEAD.
+ FastForwarded,
+ /// Target already contained HEAD; nothing to push.
+ UpToDate,
+ /// A new merge commit was created on the target branch.
+ MergeCommit { merge_sha: String },
+}
+
// ---------------------------------------------------------------------------
// Shared scaffolding
// ---------------------------------------------------------------------------
@@ -279,7 +295,7 @@ pub fn handle_push(
target: Option<&str>,
kind: PushKind,
operations: Option<MergeOperations>,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<PushResult> {
let mut ctx = MergeContext::prepare(target, operations)?;
ctx.show_progress(kind.verb_progressive(), "", operations)?;
@@ -304,13 +320,19 @@ pub fn handle_push(
ctx.restore_stash();
- if ctx.commit_count > 0 {
+ let outcome = if ctx.commit_count > 0 {
ctx.show_success(kind.verb_past(), "", "");
+ PushOutcome::FastForwarded
} else {
ctx.show_up_to_date_if_needed(operations);
- }
+ PushOutcome::UpToDate
+ };
- Ok(())
+ Ok(PushResult {
+ target: ctx.target_branch,
+ commit_count: ctx.commit_count,
+ outcome,
+ })
}
// ---------------------------------------------------------------------------
@@ -335,13 +357,17 @@ pub fn handle_no_ff_merge(
target: Option<&str>,
operations: Option<MergeOperations>,
feature_branch: &str,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<PushResult> {
let mut ctx = MergeContext::prepare(target, operations)?;
ctx.show_progress("Merging", " (--no-ff)", operations)?;
if ctx.show_up_to_date_if_needed(operations) {
- return Ok(());
+ return Ok(PushResult {
+ target: ctx.target_branch,
+ commit_count: 0,
+ outcome: PushOutcome::UpToDate,
+ });
}
// Create the merge commit using git plumbing.
@@ -419,7 +445,11 @@ pub fn handle_no_ff_merge(
let sha_suffix = cformat!(" @ <dim>{merge_sha_short}</>");
ctx.show_success("Merged to", &sha_suffix, ", --no-ff");
- Ok(())
+ Ok(PushResult {
+ target: ctx.target_branch,
+ commit_count: ctx.commit_count,
+ outcome: PushOutcome::MergeCommit { merge_sha },
+ })
}
#[cfg(test)]
diff --git a/src/main.rs b/src/main.rs
index 3d9739deb..ffda8eb8f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -46,7 +46,7 @@ use commands::commit::HookGate;
#[cfg(unix)]
use commands::handle_picker;
use commands::repository_ext::RepositoryCliExt;
-use commands::worktree::{PushKind, handle_no_ff_merge, handle_push};
+use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
use commands::{
HookCliArgs, MergeFlagOverrides, MergeOptions, OperationMode, RebaseResult, RemoveTarget,
SquashResult, SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run,
@@ -162,7 +162,8 @@ fn handle_hook_command(action: HookCommand, yes: bool) -> anyhow::Result<()> {
HookCommand::Show {
hook_type,
expanded,
- } => handle_hook_show(hook_type.as_deref(), expanded),
+ format,
+ } => handle_hook_show(hook_type.as_deref(), expanded, format),
HookCommand::RunPipeline => commands::run_pipeline(),
HookCommand::Approvals { action } => {
eprintln!(
@@ -208,17 +209,40 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
match action {
StepCommand::Commit(args) => {
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
- step_commit(
+ let format = args.format;
+ // `--show-prompt` and `--dry-run` emit raw text (rendered prompt or LLM
+ // preview), which would corrupt a JSON consumer's stdout. Refuse the
+ // combination rather than silently emit non-JSON.
+ if format == SwitchFormat::Json && (args.show_prompt || args.dry_run) {
+ anyhow::bail!("--show-prompt / --dry-run cannot be combined with --format=json");
+ }
+ let outcome = step_commit(
args.branch,
yes,
verify,
args.stage,
args.show_prompt,
args.dry_run,
- )
+ )?;
+ if format == SwitchFormat::Json
+ && let Some(outcome) = outcome
+ {
+ let payload = serde_json::json!({
+ "commit": outcome.sha,
+ "message": outcome.message,
+ "stage_mode": outcome.stage_mode,
+ });
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ }
+ Ok(())
}
StepCommand::Squash(args) => {
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
+ // `--show-prompt` and `--dry-run` emit raw text (rendered prompt or LLM
+ // preview), which would corrupt a JSON consumer's stdout.
+ if args.format == SwitchFormat::Json && (args.show_prompt || args.dry_run) {
+ anyhow::bail!("--show-prompt / --dry-run cannot be combined with --format=json");
+ }
// --show-prompt and --dry-run skip the squash and exit after preview output.
if args.show_prompt {
commands::step_show_squash_prompt(args.target.as_deref())
@@ -234,6 +258,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
HookGate::NoHooksFlag
};
let mut announcer = HookAnnouncer::new(&repo, &config, false);
+ let format = args.format;
let result = handle_squash(
args.target.as_deref(),
yes,
@@ -242,45 +267,111 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
&mut announcer,
)?;
announcer.flush()?;
- match result {
- SquashResult::Squashed | SquashResult::NoNetChanges => {}
- SquashResult::NoCommitsAhead(branch) => {
- eprintln!(
- "{}",
- info_message(format!(
- "Nothing to squash; no commits ahead of {branch}"
- ))
- );
- }
- SquashResult::AlreadySingleCommit => {
- eprintln!(
- "{}",
- info_message("Nothing to squash; already a single commit")
- );
+ if format == SwitchFormat::Json {
+ let payload = match &result {
+ SquashResult::Squashed {
+ sha,
+ message,
+ stage_mode,
+ } => serde_json::json!({
+ "outcome": "squashed",
+ "commit": sha,
+ "message": message,
+ "stage_mode": stage_mode,
+ }),
+ SquashResult::NoCommitsAhead(target) => serde_json::json!({
+ "outcome": "no_commits_ahead",
+ "target": target,
+ }),
+ SquashResult::AlreadySingleCommit => serde_json::json!({
+ "outcome": "already_single_commit",
+ }),
+ SquashResult::NoNetChanges => serde_json::json!({
+ "outcome": "no_net_changes",
+ }),
+ };
+ println!("{}", serde_json::to_string_pretty(&payload)?);
+ } else {
+ match result {
+ SquashResult::Squashed { .. } | SquashResult::NoNetChanges => {}
+ SquashResult::NoCommitsAhead(branch) => {
+ eprintln!(
+ "{}",
+ info_message(format!(
+ "Nothing to squash; no commits ahead of {branch}"
+ ))
+ );
+ }
+ SquashResult::AlreadySingleCommit => {
+ eprintln!(
+ "{}",
+ info_message("Nothing to squash; already a single commit")
+ );
+ }
}
}
Ok(())
}
}
- StepCommand::Push { target, no_ff, .. } => {
- if no_ff {
+ StepCommand::Push {
+ target,
+ no_ff,
+ format,
+ ..
+ } => {
+ let result = if no_ff {
let repo = Repository::current()?;
let current_branch = repo.require_current_branch("step push --no-ff")?;
- handle_no_ff_merge(target.as_deref(), None, &current_branch)
+ handle_no_ff_merge(target.as_deref(), None, &current_branch)?
} else {
- handle_push(target.as_deref(), PushKind::Standalone, None)
+ handle_push(target.as_deref(), PushKind::Standalone, None)?
+ };
+ if format == SwitchFormat::Json {
+ let PushResult {
+ target,
+ commit_count,
+ outcome,
+ } = result;
+ let mut payload = serde_json::json!({
+ "target": target,
+ "outcome": match outcome {
+ PushOutcome::FastForwarded => "fast_forwarded",
+ PushOutcome::UpToDate => "up_to_date",
+ PushOutcome::MergeCommit { .. } => "merge_commit",
+ },
+ "commits": commit_count,
+ });
+ if let PushOutcome::MergeCommit { merge_sha } = outcome {
+ payload["merge_sha"] = serde_json::Value::String(merge_sha);
+ }
+ println!("{}", serde_json::to_string_pretty(&payload)?);
}
+ Ok(())
}
- StepCommand::Rebase { target } => {
- handle_rebase(target.as_deref()).map(|result| match result {
- RebaseResult::Rebased => (),
- RebaseResult::UpToDate(branch) => {
- eprintln!(
- "{}",
- info_message(cformat!("Already up to date with <bold>{branch}</>"))
- );
- }
- })
+ StepCommand::Rebase { target, format } => {
+ let result = handle_rebase(target.as_deref())?;
+ if format == SwitchFormat::Json {
+ let output = match &result {
+ RebaseResult::Rebased {
+ target,
+ fast_forward,
+ } => serde_json::json!({
+ "target": target,
+ "outcome": if *fast_forward { "fast_forwarded" } else { "rebased" },
+ }),
+ RebaseResult::UpToDate(target) => serde_json::json!({
+ "target": target,
+ "outcome": "up_to_date",
+ }),
+ };
+ println!("{}", serde_json::to_string_pretty(&output)?);
+ } else if let RebaseResult::UpToDate(branch) = &result {
+ eprintln!(
+ "{}",
+ info_message(cformat!("Already up to date with <bold>{branch}</>"))
+ );
+ }
+ Ok(())
}
StepCommand::Diff { target, extra_args } => step_diff(target.as_deref(), &extra_args),
StepCommand::CopyIgnored {
@@ -288,7 +379,8 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
to,
dry_run,
force,
- } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force),
+ format,
+ } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force, format),
StepCommand::Eval { template, dry_run } => step_eval(&template, dry_run),
StepCommand::ForEach { format, args } => step_for_each(args, format),
StepCommand::Promote { branch } => {
@@ -315,7 +407,8 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
dry_run,
commit,
clobber,
- } => step_relocate(branches, dry_run, commit, clobber),
+ format,
+ } => step_relocate(branches, dry_run, commit, clobber, format),
StepCommand::External(args) => commands::step_alias(args, yes),
}
}
diff --git a/tests/integration_tests/hook_show.rs b/tests/integration_tests/hook_show.rs
index aaec64c0d..8d7448aef 100644
--- a/tests/integration_tests/hook_show.rs
+++ b/tests/integration_tests/hook_show.rs
@@ -388,6 +388,141 @@ optional-var = "echo {{ base }}"
});
}
+/// `hook show --format=json` emits one record per configured command, with
+/// type / source / template / approval status, plus `expanded` when requested.
+#[rstest]
+fn test_hook_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"),
+ r#"worktree-path = "../{{ repo }}.{{ branch }}"
+
+[pre-commit]
+user-lint = "pre-commit run --all-files"
+"#,
+ )
+ .unwrap();
+
+ repo.write_project_config(
+ r#"pre-merge = [
+ {build = "cargo build"},
+]
+
+[post-start]
+deps = "npm install"
+"#,
+ );
+ repo.commit("Add project config");
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env(
+ "WORKTRUNK_CONFIG_PATH",
+ global_config_dir.join("config.toml"),
+ );
+ cmd.args(["hook", "show", "--format=json"])
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "hook show --format=json failed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+ let entries = parsed.as_array().expect("array");
+ assert_eq!(
+ entries.len(),
+ 3,
+ "user pre-commit + project pre-merge + project post-start"
+ );
+
+ // User entry
+ let user_lint = entries
+ .iter()
+ .find(|e| e["name"] == "user-lint")
+ .expect("user-lint present");
+ assert_eq!(user_lint["type"], "pre-commit");
+ assert_eq!(user_lint["source"], "user");
+ assert_eq!(user_lint["template"], "pre-commit run --all-files");
+ assert_eq!(user_lint["needs_approval"], false);
+
+ // Project entry — project hooks need approval until approved
+ let build = entries
+ .iter()
+ .find(|e| e["name"] == "build")
+ .expect("build present");
+ assert_eq!(build["type"], "pre-merge");
+ assert_eq!(build["source"], "project");
+ assert_eq!(build["needs_approval"], true);
+}
+
+/// `hook show <type> --expanded --format=json` filters by hook type across
+/// both user and project hooks, and includes the rendered `expanded` field
+/// for each surviving entry.
+#[rstest]
+fn test_hook_show_filtered_expanded_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"),
+ r#"worktree-path = "../{{ repo }}.{{ branch }}"
+
+[pre-commit]
+user-lint = "echo {{ branch }}"
+
+[post-start]
+user-greet = "echo hi"
+"#,
+ )
+ .unwrap();
+ repo.write_project_config(
+ r#"[pre-commit]
+project-fmt = "echo fmt {{ branch }}"
+
+[post-start]
+project-deps = "echo deps"
+"#,
+ );
+ repo.commit("Add project config");
+
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ cmd.env(
+ "WORKTRUNK_CONFIG_PATH",
+ global_config_dir.join("config.toml"),
+ );
+ cmd.args(["hook", "show", "pre-commit", "--expanded", "--format=json"])
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "hook show --expanded --format=json failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+ let entries = parsed.as_array().expect("array");
+
+ // Filter dropped the post-start hooks from both user and project.
+ let names: Vec<&str> = entries
+ .iter()
+ .map(|e| e["name"].as_str().unwrap())
+ .collect();
+ assert_eq!(entries.len(), 2, "only pre-commit hooks survive: {names:?}");
+ assert!(names.contains(&"user-lint"));
+ assert!(names.contains(&"project-fmt"));
+ for entry in entries {
+ assert_eq!(entry["type"], "pre-commit");
+ let expanded = entry["expanded"].as_str().expect("expanded field present");
+ assert!(
+ expanded.starts_with("echo "),
+ "expanded should render template: {expanded}"
+ );
+ }
+}
+
/// Test that valid templates expand correctly with --expanded.
#[rstest]
fn test_hook_show_expanded_valid_template(repo: TestRepo, temp_home: TempDir) {
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index b84058a59..0d908173c 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2630,6 +2630,298 @@ fn test_step_rebase_already_up_to_date(mut repo: TestRepo) {
));
}
+// =============================================================================
+// JSON output tests
+// =============================================================================
+
+/// `step rebase --format=json` reports `up_to_date` when nothing to do.
+#[rstest]
+fn test_step_rebase_up_to_date_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree("feature");
+ let output = repo
+ .wt_command()
+ .args(["step", "rebase", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "up_to_date");
+ assert_eq!(parsed["target"], "main");
+}
+
+/// `step rebase --format=json` reports `fast_forwarded` when target advanced cleanly.
+#[rstest]
+fn test_step_rebase_fast_forwarded_json(mut repo: TestRepo) {
+ // feature created BEFORE main advances → main is ahead, feature has no new commits
+ let feature_wt = repo.add_worktree("feature");
+ fs::write(repo.root_path().join("main-update.txt"), "x").unwrap();
+ repo.run_git(&["add", "main-update.txt"]);
+ repo.run_git(&["commit", "-m", "Update main"]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "rebase", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "fast_forwarded");
+ assert_eq!(parsed["target"], "main");
+}
+
+/// `step push --format=json` reports `fast_forwarded` plus commit count.
+#[rstest]
+fn test_step_push_fast_forwarded_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit("feature", "f.txt", "x", "feat: x");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "push", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "fast_forwarded");
+ assert_eq!(parsed["target"], "main");
+ assert_eq!(parsed["commits"], 1);
+}
+
+/// `step push --no-ff --format=json` reports `merge_commit` and includes
+/// the new merge SHA — the field that was previously discarded.
+#[rstest]
+fn test_step_push_no_ff_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit("feature", "f.txt", "x", "feat: x");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "push", "--no-ff", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "step push --no-ff --format=json failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "merge_commit");
+ assert_eq!(parsed["target"], "main");
+ assert_eq!(parsed["commits"], 1);
+ let merge_sha = parsed["merge_sha"].as_str().expect("merge_sha string");
+ assert_eq!(
+ merge_sha.len(),
+ 40,
+ "expected full 40-char merge SHA, got {merge_sha}"
+ );
+}
+
+/// `step push --format=json` reports `up_to_date` when target already contains HEAD.
+#[rstest]
+fn test_step_push_up_to_date_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree("feature");
+ let output = repo
+ .wt_command()
+ .args(["step", "push", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "up_to_date");
+ assert_eq!(parsed["commits"], 0);
+}
+
+/// `step commit --format=json` reports the new commit's SHA + message + stage_mode.
+#[rstest]
+fn test_step_commit_json(repo: TestRepo) {
+ fs::write(repo.root_path().join("file1.txt"), "content").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "commit", "--no-hooks", "--format=json"])
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'feat: add file'",
+ )
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "step commit failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ let sha = parsed["commit"].as_str().expect("commit SHA");
+ assert_eq!(sha.len(), 40, "expected full 40-char SHA, got {sha}");
+ assert_eq!(parsed["message"], "feat: add file");
+ // Without --stage on the CLI, the resolved default ("all") is emitted —
+ // not null. Scripters get a stable identifier for what was applied.
+ assert_eq!(parsed["stage_mode"], "all");
+}
+
+/// `step squash --format=json` reports `no_commits_ahead` cleanly.
+#[rstest]
+fn test_step_squash_no_commits_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree("feature");
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "no_commits_ahead");
+ assert_eq!(parsed["target"], "main");
+}
+
+/// `step squash --format=json` reports `already_single_commit` when nothing to squash.
+#[rstest]
+fn test_step_squash_already_single_commit_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit("feature", "f.txt", "x", "feat: single");
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "already_single_commit");
+}
+
+/// `step squash --format=json` reports `squashed` with the new commit's full
+/// SHA and the LLM-generated message when there are multiple commits to squash.
+#[rstest]
+fn test_step_squash_squashed_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit("feature", "a.txt", "1", "feat: a");
+ fs::write(feature_wt.join("b.txt"), "2").unwrap();
+ repo.git_command()
+ .current_dir(&feature_wt)
+ .args(["add", "b.txt"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .current_dir(&feature_wt)
+ .args(["commit", "-m", "feat: b"])
+ .run()
+ .unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--no-hooks", "--format=json"])
+ .current_dir(&feature_wt)
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'feat: combined ab'",
+ )
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "step squash failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "squashed");
+ let sha = parsed["commit"].as_str().expect("commit SHA");
+ assert_eq!(sha.len(), 40);
+ assert_eq!(parsed["message"], "feat: combined ab");
+ assert_eq!(parsed["stage_mode"], "all");
+}
+
+/// `step squash --format=json` reports `no_net_changes` when commits cancel
+/// each other out so the squash produces an empty diff.
+#[rstest]
+fn test_step_squash_no_net_changes_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree("feature");
+ let file_path = feature_wt.join("file.txt");
+ let initial = std::fs::read_to_string(&file_path).unwrap();
+
+ repo.commit_in_worktree(&feature_wt, "file.txt", "change1", "change 1");
+ repo.commit_in_worktree(&feature_wt, "file.txt", "change2", "change 2");
+ repo.commit_in_worktree(&feature_wt, "file.txt", &initial, "revert to initial");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--no-hooks", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "step squash failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "no_net_changes");
+}
+
+/// `step rebase --format=json` reports `rebased` (not `fast_forwarded`) when
+/// the feature branch has its own commits that need to be replayed onto a
+/// moved target.
+#[rstest]
+fn test_step_rebase_rebased_json(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit("feature", "f.txt", "x", "feat: f");
+ // Advance main with an unrelated commit so feature must be rebased.
+ fs::write(repo.root_path().join("main-update.txt"), "y").unwrap();
+ repo.run_git(&["add", "main-update.txt"]);
+ repo.run_git(&["commit", "-m", "update main"]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "rebase", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "step rebase failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
+ assert_eq!(parsed["outcome"], "rebased");
+ assert_eq!(parsed["target"], "main");
+}
+
+/// `step commit --show-prompt --format=json` is rejected — show-prompt emits
+/// raw text that would corrupt JSON output.
+#[rstest]
+fn test_step_commit_show_prompt_with_json_rejected(repo: TestRepo) {
+ let output = repo
+ .wt_command()
+ .args(["step", "commit", "--show-prompt", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("cannot be combined with --format=json"),
+ "stderr: {stderr}"
+ );
+}
+
+/// Same guard for squash.
+#[rstest]
+fn test_step_squash_show_prompt_with_json_rejected(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree("feature");
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--show-prompt", "--format=json"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("cannot be combined with --format=json"),
+ "stderr: {stderr}"
+ );
+}
+
// =============================================================================
// Target validation tests
// =============================================================================
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index dcfcd634c..3fc3906d4 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -1620,3 +1620,127 @@ fn test_copy_ignored_many_directories_no_emfile(mut repo: TestRepo) {
}
}
}
+
+/// `copy-ignored --dry-run --format=json` lists planned entries instead of copying.
+#[rstest]
+fn test_copy_ignored_dry_run_json(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();
+ fs::write(repo.root_path().join(".worktreeinclude"), ".env\n").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored", "--dry-run", "--format=json"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["outcome"], "planned");
+ assert_eq!(parsed["dry_run"], true);
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0]["path"], ".env");
+ assert_eq!(entries[0]["kind"], "file");
+
+ // Dry run did not copy
+ assert!(!feature_path.join(".env").exists());
+}
+
+/// `copy-ignored --format=json` after execution emits file/byte counts.
+#[rstest]
+fn test_copy_ignored_json_summary(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();
+ fs::write(repo.root_path().join(".worktreeinclude"), ".env\n").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored", "--format=json"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["outcome"], "copied");
+ assert_eq!(parsed["dry_run"], false);
+ assert_eq!(parsed["files"], 1);
+ // .env content "SECRET=value" is 12 bytes
+ assert_eq!(parsed["bytes"], 12);
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0]["path"], ".env");
+ assert!(feature_path.join(".env").exists());
+}
+
+/// `copy-ignored --format=json` reports `same_worktree` when source and
+/// destination resolve to the same path, with empty entries.
+#[rstest]
+fn test_copy_ignored_same_worktree_json(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "copy-ignored",
+ "--from=feature",
+ "--to=feature",
+ "--format=json",
+ ])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "copy-ignored same-worktree should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["outcome"], "same_worktree");
+ assert_eq!(parsed["files"], 0);
+ assert_eq!(parsed["bytes"], 0);
+ assert_eq!(
+ parsed["entries"].as_array().expect("entries array").len(),
+ 0
+ );
+}
+
+/// `copy-ignored --format=json` reports `copied` with zero counts when no
+/// ignored files match — distinct from the same-worktree case.
+#[rstest]
+fn test_copy_ignored_no_matches_json(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+ // No .gitignore / .worktreeinclude — nothing to copy.
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored", "--format=json"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "copy-ignored should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["outcome"], "copied");
+ assert_eq!(parsed["dry_run"], false);
+ assert_eq!(parsed["files"], 0);
+ assert_eq!(parsed["bytes"], 0);
+ assert_eq!(
+ parsed["entries"].as_array().expect("entries array").len(),
+ 0
+ );
+}
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index d5afeefea..071f2e2c3 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -703,3 +703,166 @@ fn test_relocate_empty_default_branch(repo: TestRepo) {
// Relocate should fail early with helpful error
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
}
+
+/// `step relocate --dry-run --format=json` lists planned moves with from/to paths.
+#[rstest]
+fn test_relocate_dry_run_json(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "relocate", "--dry-run", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "relocate dry-run JSON should succeed"
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["dry_run"], true);
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0]["branch"], "feature");
+ assert!(
+ entries[0]["from"]
+ .as_str()
+ .unwrap()
+ .ends_with("wrong-location")
+ );
+ assert!(entries[0]["to"].as_str().unwrap().ends_with("repo.feature"));
+
+ assert_eq!(
+ parsed["skipped"].as_array().expect("skipped array").len(),
+ 0
+ );
+
+ // Dry run did not move
+ assert!(wrong_path.exists());
+}
+
+/// `step relocate --format=json` after execution emits per-branch records and
+/// distinguishes relocated vs skipped (with stable `reason` codes).
+#[rstest]
+fn test_relocate_json_with_skip(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+ // Make the worktree dirty so it's skipped during validation
+ fs::write(wrong_path.join("dirty.txt"), "uncommitted").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "relocate", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "relocate JSON should succeed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["dry_run"], false);
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 0);
+
+ let skipped = parsed["skipped"].as_array().expect("skipped array");
+ assert_eq!(skipped.len(), 1);
+ assert_eq!(skipped[0]["branch"], "feature");
+ assert_eq!(skipped[0]["reason"], "uncommitted");
+}
+
+/// `step relocate --format=json` after a successful execution emits the
+/// per-branch `entries` array with `from` / `to` paths.
+#[rstest]
+fn test_relocate_executes_json(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ let output = repo
+ .wt_command()
+ .args(["step", "relocate", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "relocate JSON should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ assert_eq!(parsed["dry_run"], false);
+ let entries = parsed["entries"].as_array().expect("entries array");
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0]["branch"], "feature");
+ assert!(
+ entries[0]["from"]
+ .as_str()
+ .unwrap()
+ .ends_with("wrong-location")
+ );
+ assert!(entries[0]["to"].as_str().unwrap().ends_with("repo.feature"));
+
+ // The actual move should have happened.
+ assert!(!wrong_path.exists());
+ assert!(parent.join("repo.feature").exists());
+}
+
+/// `step relocate --format=json` surfaces template-expansion failures as
+/// `skipped` entries with `reason: "template_error"` rather than silently
+/// reporting an empty success — automation needs to detect a broken config.
+#[rstest]
+fn test_relocate_template_error_json(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ // Add a worktree so something exists to evaluate the template against.
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ // Reference an undefined template variable to force expansion failure.
+ let worktrunk_config = r#"
+worktree-path = "../{{ undefined_var }}.{{ branch }}"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "relocate", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "relocate JSON should succeed");
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let parsed: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
+
+ let skipped = parsed["skipped"].as_array().expect("skipped array");
+ assert!(
+ skipped.iter().any(|s| s["reason"] == "template_error"),
+ "template_error skip missing from JSON: {parsed}"
+ );
+}