Skip to content

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

fix: JSON output follow-ups from --format=json rollout (#2001)

Maximilian Roos65e58d364794
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index afbfc7adb..887e36fe5 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -167,7 +167,9 @@ fn partition_log_files_json(
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)
+ b_time
+ .cmp(&a_time)
+ .then_with(|| a.file_name().cmp(&b.file_name()))
});
let mut cmd_log = Vec::new();
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index e4dffafdd..6cc604aa9 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -100,7 +100,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
}
}
Err(err) => {
- let (exit_code, error_detail) = match &err {
+ match &err {
CommandError::SpawnFailed(e) => {
eprintln!(
"{}",
@@ -109,7 +109,6 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
))
);
eprintln!("{}", format_with_gutter(e, None));
- (None, Some(e.clone()))
}
CommandError::ExitCode(code) => {
let exit_info = code
@@ -119,21 +118,17 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
"{}",
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!({
+ json_results.push(serde_json::json!({
"branch": wt.branch,
"path": wt.path,
- "exit_code": exit_code,
+ "exit_code": err.exit_code(),
"success": false,
- });
- if let Some(e) = error_detail {
- entry["error"] = serde_json::Value::String(e);
- }
- json_results.push(entry);
+ "error": err.to_string(),
+ }));
}
}
}
@@ -183,6 +178,25 @@ pub(crate) enum CommandError {
ExitCode(Option<i32>),
}
+impl CommandError {
+ fn exit_code(&self) -> Option<i32> {
+ match self {
+ CommandError::SpawnFailed(_) => None,
+ CommandError::ExitCode(code) => *code,
+ }
+ }
+}
+
+impl std::fmt::Display for CommandError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ CommandError::SpawnFailed(e) => write!(f, "spawn failed: {e}"),
+ CommandError::ExitCode(Some(c)) => write!(f, "exit code {c}"),
+ CommandError::ExitCode(None) => write!(f, "killed by signal"),
+ }
+ }
+}
+
/// Run a shell command, streaming both stdout and stderr in real-time.
///
/// Returns `Ok(())` on success, or `Err(CommandError)` on failure.
@@ -245,3 +259,23 @@ pub(crate) fn run_command_streaming(
Err(CommandError::ExitCode(status.code()))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_command_error_display_and_exit_code() {
+ let spawn = CommandError::SpawnFailed("no such file".into());
+ assert_eq!(spawn.to_string(), "spawn failed: no such file");
+ assert_eq!(spawn.exit_code(), None);
+
+ let exit = CommandError::ExitCode(Some(42));
+ assert_eq!(exit.to_string(), "exit code 42");
+ assert_eq!(exit.exit_code(), Some(42));
+
+ let signal = CommandError::ExitCode(None);
+ assert_eq!(signal.to_string(), "killed by signal");
+ assert_eq!(signal.exit_code(), None);
+ }
+}
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 8b648cf79..e987b5c43 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -3634,3 +3634,40 @@ fn test_config_show_json_with_project_config(repo: TestRepo, temp_home: TempDir)
assert!(json["project"]["exists"].as_bool().unwrap());
assert!(json["project"]["config"].is_object());
}
+
+#[rstest]
+fn test_config_show_json_outside_repo(repo: TestRepo, temp_home: TempDir) {
+ let temp_dir = tempfile::tempdir().unwrap();
+
+ 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(temp_dir.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"]["config"].is_object());
+
+ // Outside a repo: project path and config are null
+ assert!(json["project"]["path"].is_null());
+ assert!(!json["project"]["exists"].as_bool().unwrap());
+ assert!(json["project"]["config"].is_null());
+}
diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rs
index 61513f0f8..ec5c94937 100644
--- a/tests/integration_tests/for_each.rs
+++ b/tests/integration_tests/for_each.rs
@@ -164,8 +164,10 @@ fn test_for_each_json_with_failure(repo: TestRepo) {
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);
+ assert_eq!(item["exit_code"], 1);
+ // error field is always present on failure (both ExitCode and SpawnFailed)
+ assert_eq!(item["error"], "exit code 1");
}
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 002c63aeb..c2ddf187b 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2863,3 +2863,39 @@ fn test_remove_json_multi_with_branch_only(mut repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stdout));
});
}
+
+/// Multi-remove with current worktree in the target list exercises the
+/// `plans.current` JSON path (deferred removal, last in output).
+#[cfg(not(target_os = "windows"))]
+#[rstest]
+fn test_remove_json_multi_with_current(mut repo: TestRepo) {
+ repo.commit("initial");
+ repo.add_worktree("other-feature");
+ let current_wt = repo.add_worktree("current-feature");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "other-feature",
+ "current-feature",
+ "--format=json",
+ "--yes",
+ "--foreground",
+ ])
+ .current_dir(&current_wt)
+ .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_eq!(items.len(), 2);
+
+ // other-feature removed first (plans.others), current-feature last (plans.current)
+ assert_eq!(items[0]["branch"], "other-feature");
+ assert_eq!(items[0]["kind"], "worktree");
+ assert_eq!(items[1]["branch"], "current-feature");
+ assert_eq!(items[1]["kind"], "worktree");
+}