Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: simplify JSON output patterns (#1998)
Maximilian Roos7a464010e03f
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 6c0e5d729..afbfc7adb 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -143,6 +143,49 @@ fn log_entry_to_json(entry: &std::fs::DirEntry) -> serde_json::Value {serde_json::json!({ "file": name, "size": size, "modified_at": modified })}+/// Read and partition log files into command log, hook output, and diagnostic categories.+///+/// Reads all wt log files from the repository's log directory, sorts by modification+/// time (newest first), and partitions into three categories as JSON values.+fn partition_log_files_json(+ repo: &Repository,+) -> anyhow::Result<(+ Vec<serde_json::Value>,+ Vec<serde_json::Value>,+ Vec<serde_json::Value>,+)> {+ let log_dir = repo.wt_logs_dir();+ if !log_dir.exists() {+ return Ok((vec![], vec![], vec![]));+ }++ 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();+ let mut diagnostic = 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 if is_diagnostic_file(&name) {+ diagnostic.push(log_entry_to_json(entry));+ } else {+ hook_out.push(log_entry_to_json(entry));+ }+ }+ Ok((cmd_log, hook_out, diagnostic))+}+/// 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() {@@ -253,34 +296,11 @@ pub fn handle_logs_get(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 (command_log, hook_output, diagnostic) = partition_log_files_json(&repo)?;let output = serde_json::json!({"command_log": command_log,"hook_output": hook_output,+ "diagnostic": diagnostic,});println!("{}", serde_json::to_string_pretty(&output)?);}@@ -832,41 +852,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {}).collect();- // Get log files, partitioned into command log, hook output, and diagnostic- let log_dir = repo.wt_logs_dir();- let (command_log, hook_output, diagnostic): (- Vec<serde_json::Value>,- Vec<serde_json::Value>,- Vec<serde_json::Value>,- ) = if log_dir.exists() {- let mut all_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();-- all_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();- 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(log_entry_to_json(entry));- } else if is_diagnostic_file(&name) {- diagnostic.push(log_entry_to_json(entry));- } else {- hook_out.push(log_entry_to_json(entry));- }- }- (cmd_log, hook_out, diagnostic)- } else {- (vec![], vec![], vec![])- };+ let (command_log, hook_output, diagnostic) = partition_log_files_json(repo)?;// Get vars data (all branches) — collect into BTreeMap for sorted outputlet all_vars: std::collections::BTreeMap<_, _> = repo.all_vars_entries().into_iter().collect();diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex cc4634e24..2236a6897 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1302,6 +1302,16 @@ pub fn step_prune(BranchOnly,}+ impl CandidateKind {+ fn as_str(&self) -> &'static str {+ match self {+ CandidateKind::Current => "current",+ CandidateKind::Other => "worktree",+ CandidateKind::BranchOnly => "branch_only",+ }+ }+ }+/// Build a human-readable count like "3 worktrees & branches".////// Worktree + branch is the default pair (matching progress messages'@@ -1653,11 +1663,7 @@ pub fn step_prune(serde_json::json!({"branch": c.branch,"path": c.path,- "kind": match c.kind {- CandidateKind::Current => "current",- CandidateKind::Other => "worktree",- CandidateKind::BranchOnly => "branch_only",- },+ "kind": c.kind.as_str(),"reason": info.reason_desc,"target": info.effective_target,})@@ -1757,11 +1763,7 @@ pub fn step_prune(serde_json::json!({"branch": c.branch,"path": c.path,- "kind": match c.kind {- CandidateKind::Current => "current",- CandidateKind::Other => "worktree",- CandidateKind::BranchOnly => "branch_only",- },+ "kind": c.kind.as_str(),})}).collect();diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex acb343af0..33a333b7c 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -227,6 +227,36 @@ pub enum RemoveResult {},}+impl RemoveResult {+ /// Convert to a JSON value for structured output.+ pub fn to_json(&self) -> serde_json::Value {+ match self {+ 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(),+ }),+ }+ }+}+/// Operation mode for worktree resolution - determines which checks are performed.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum OperationMode {diff --git a/src/main.rs b/src/main.rsindex 7eabf1ef1..30faf6006 100644--- a/src/main.rs+++ b/src/main.rs@@ -724,34 +724,6 @@ 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);@@ -823,7 +795,7 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {handle_remove_output(&result, args.foreground, run_hooks, false)?;if json_mode {- let json = serde_json::json!([remove_result_to_json(&result)]);+ let json = serde_json::json!([result.to_json()]);println!("{}", serde_json::to_string_pretty(&json)?);}Ok(())@@ -852,29 +824,25 @@ 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 lastfor 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 {- 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 json_mode {+ let json_items: Vec<serde_json::Value> = plans+ .others+ .iter()+ .chain(&plans.branch_only)+ .chain(plans.current.as_ref())+ .map(RemoveResult::to_json)+ .collect();println!("{}", serde_json::to_string_pretty(&json_items)?);}diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 63582dfb5..be784a2c4 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -1953,6 +1953,7 @@ fn test_logs_get_json_empty(repo: TestRepo) {assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"{"command_log": [],+ "diagnostic": [],"hook_output": []}"#);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.snapindex 919553ab4..cd04f675a 100644--- 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@@ -10,6 +10,7 @@ expression: "String::from_utf8_lossy(&output.stdout)""size": "<SIZE>"}],+ "diagnostic": [],"hook_output": [{"file": "main-user-post-start-server.log",