Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(list): Enhance JSON output with display fields
Maximilian Roosf7dce73a4102
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex cc24bccdf..cba63a36f 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -404,6 +404,11 @@ mod tests {upstream: UpstreamStatus::from_parts(Some("origin".to_string()), 4, 0),worktree_state: None,pr_status: None,+ commits_display: None,+ working_diff_display: None,+ branch_diff_display: None,+ upstream_display: None,+ ci_status_display: None,};let widths = calculate_column_widths(&[super::ListItem::Worktree(info1)]);diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex f553647d4..2994f552c 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -8,9 +8,84 @@ mod spacing_test;use layout::calculate_responsive_layout;use model::{ListData, ListItem, gather_list_data};-use render::{format_header_line, format_list_item_line};+use render::{+ format_ahead_behind_plain, format_ci_status_plain, format_diff_plain, format_header_line,+ format_list_item_line,+};use worktrunk::git::{GitError, Repository};+/// Helper to enrich common display fields shared between worktrees and branches+fn enrich_common_fields(+ counts: &model::AheadBehind,+ branch_diff: &model::BranchDiffTotals,+ upstream: &model::UpstreamStatus,+ pr_status: &Option<ci_status::PrStatus>,+) -> (+ Option<String>,+ Option<String>,+ Option<String>,+ Option<String>,+) {+ let commits_display = format_ahead_behind_plain(counts.ahead, counts.behind);++ let (added, deleted) = branch_diff.diff;+ let branch_diff_display = format_diff_plain(added, deleted);++ let upstream_display = upstream+ .active()+ .and_then(|(_, upstream_ahead, upstream_behind)| {+ format_ahead_behind_plain(upstream_ahead, upstream_behind)+ });++ let ci_status_display = pr_status.as_ref().map(format_ci_status_plain);++ (+ commits_display,+ branch_diff_display,+ upstream_display,+ ci_status_display,+ )+}++/// Enrich a ListItem with display fields for json-pretty format+fn enrich_with_display_fields(mut item: ListItem) -> ListItem {+ match &mut item {+ ListItem::Worktree(info) => {+ let (commits_display, branch_diff_display, upstream_display, ci_status_display) =+ enrich_common_fields(+ &info.counts,+ &info.branch_diff,+ &info.upstream,+ &info.pr_status,+ );++ info.commits_display = commits_display;+ info.branch_diff_display = branch_diff_display;+ info.upstream_display = upstream_display;+ info.ci_status_display = ci_status_display;++ // Working tree specific field+ let (added, deleted) = info.working_tree_diff;+ info.working_diff_display = format_diff_plain(added, deleted);+ }+ ListItem::Branch(info) => {+ let (commits_display, branch_diff_display, upstream_display, ci_status_display) =+ enrich_common_fields(+ &info.counts,+ &info.branch_diff,+ &info.upstream,+ &info.pr_status,+ );++ info.commits_display = commits_display;+ info.branch_diff_display = branch_diff_display;+ info.upstream_display = upstream_display;+ info.ci_status_display = ci_status_display;+ }+ }+ item+}+pub fn handle_list(format: crate::OutputFormat,show_branches: bool,@@ -27,7 +102,10 @@ pub fn handle_list(match format {crate::OutputFormat::Json => {- let json = serde_json::to_string_pretty(&items).map_err(|e| {+ let enriched_items: Vec<_> =+ items.into_iter().map(enrich_with_display_fields).collect();++ let json = serde_json::to_string_pretty(&enriched_items).map_err(|e| {GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))})?;println!("{}", json);diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex d74e94d58..189ea5819 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -20,6 +20,18 @@ pub struct WorktreeInfo {pub upstream: UpstreamStatus,pub worktree_state: Option<String>,pub pr_status: Option<PrStatus>,++ // Display fields for json-pretty format (with ANSI colors)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub commits_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub working_diff_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub branch_diff_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub upstream_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ci_status_display: Option<String>,}#[derive(serde::Serialize)]@@ -35,6 +47,16 @@ pub struct BranchInfo {#[serde(flatten)]pub upstream: UpstreamStatus,pub pr_status: Option<PrStatus>,++ // Display fields for json-pretty format (with ANSI colors)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub commits_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub branch_diff_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub upstream_display: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub ci_status_display: Option<String>,}#[derive(serde::Serialize, Clone)]@@ -252,6 +274,10 @@ impl BranchInfo {branch_diff,upstream,pr_status,+ commits_display: None,+ branch_diff_display: None,+ upstream_display: None,+ ci_status_display: None,})}}@@ -295,6 +321,11 @@ impl WorktreeInfo {upstream,worktree_state,pr_status,+ commits_display: None,+ working_diff_display: None,+ branch_diff_display: None,+ upstream_display: None,+ ci_status_display: None,})}}diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex c06871a4c..2f2c71313 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -6,6 +6,80 @@ use super::ci_status::{CiStatus, PrStatus};use super::layout::{DiffWidths, LayoutConfig};use super::model::{ListItem, WorktreeInfo};+/// Format ahead/behind counts as plain text with ANSI colors (for json-pretty)+pub fn format_ahead_behind_plain(ahead: usize, behind: usize) -> Option<String> {+ match (ahead, behind) {+ (0, 0) => None,+ (a, 0) => Some(format!("{}↑{}{}", ADDITION, a, ADDITION.render_reset())),+ (0, b) => {+ let dim_deletion = DELETION.dimmed();+ Some(format!(+ "{}↓{}{}",+ dim_deletion,+ b,+ dim_deletion.render_reset()+ ))+ }+ (a, b) => {+ let dim_deletion = DELETION.dimmed();+ Some(format!(+ "{}↑{}{} {}↓{}{}",+ ADDITION,+ a,+ ADDITION.render_reset(),+ dim_deletion,+ b,+ dim_deletion.render_reset()+ ))+ }+ }+}++/// Format diff values as plain text with ANSI colors (for json-pretty)+pub fn format_diff_plain(added: usize, deleted: usize) -> Option<String> {+ match (added, deleted) {+ (0, 0) => None,+ (a, 0) => Some(format!("{}+{}{}", ADDITION, a, ADDITION.render_reset())),+ (0, d) => Some(format!("{}-{}{}", DELETION, d, DELETION.render_reset())),+ (a, d) => Some(format!(+ "{}+{}{} {}-{}{}",+ ADDITION,+ a,+ ADDITION.render_reset(),+ DELETION,+ d,+ DELETION.render_reset()+ )),+ }+}++/// Format CI status as plain text with ANSI colors (for json-pretty)+pub fn format_ci_status_plain(pr_status: &PrStatus) -> String {+ let color = match pr_status.ci_status {+ CiStatus::Passed => AnsiColor::Green,+ CiStatus::Running => AnsiColor::Blue,+ CiStatus::Failed => AnsiColor::Red,+ CiStatus::Conflicts => AnsiColor::Yellow,+ CiStatus::NoCI => AnsiColor::BrightBlack,+ };++ let style = if pr_status.is_stale {+ Style::new().fg_color(Some(Color::Ansi(color))).dimmed()+ } else {+ Style::new().fg_color(Some(Color::Ansi(color)))+ };++ let status_str = match pr_status.ci_status {+ CiStatus::Passed => "passed",+ CiStatus::Running => "running",+ CiStatus::Failed => "failed",+ CiStatus::Conflicts => "conflicts",+ CiStatus::NoCI => "no-ci",+ };++ format!("{}● {}{}", style, status_str, style.render_reset())+}+/// Format arrow-based counts (e.g., "↑6 ↓1") with alignment/// Down arrows always appear at the same column position by reserving space for ahead partfn format_arrow_column(@@ -426,6 +500,7 @@ pub fn format_list_item_line(#[cfg(test)]mod tests {use super::*;+ use worktrunk::styling::StyledLine;#[test]fn test_format_diff_column_pads_to_total_width() {diff --git a/src/main.rs b/src/main.rsindex 710ef5278..2a91f4968 100644--- a/src/main.rs+++ b/src/main.rs@@ -22,7 +22,7 @@ use output::{handle_remove_output, handle_switch_output};pub enum OutputFormat {/// Human-readable table formatTable,- /// JSON format+ /// JSON format with colored unicode display fieldsJson,}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex c7545b8bd..c82aa0c70 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -53,6 +53,12 @@ fn snapshot_list_json(test_name: &str, repo: &TestRepo) {// Normalize timestamps to fixed valuesettings.add_filter(r#""timestamp": \d+"#, r#""timestamp": 0"#);+ // Normalize ANSI escape codes to readable placeholders+ settings.add_filter(r"\\u001b\[32m", "[GREEN]"); // ADDITION color+ settings.add_filter(r"\\u001b\[31m", "[RED]"); // DELETION color+ settings.add_filter(r"\\u001b\[2m", "[DIM]"); // Dimming+ settings.add_filter(r"\\u001b\[0m", "[RESET]"); // Style reset+// Normalize Windows paths to Unix stylesettings.add_filter(r"\\\\", "/");@@ -267,3 +273,53 @@ fn test_list_with_branches_flag_only_branches() {snapshot_list_with_branches("with_branches_flag_only_branches", &repo);}++#[test]+fn test_list_json_with_display_fields() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit on main");++ // Create feature branch with commits (ahead of main)+ repo.add_worktree("feature-ahead", "feature-ahead");++ // Make commits in the feature worktree+ let feature_path = repo.worktree_path("feature-ahead");+ std::fs::write(feature_path.join("feature.txt"), "feature content")+ .expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "."])+ .current_dir(feature_path)+ .output()+ .expect("Failed to git add");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Feature commit 1"])+ .current_dir(feature_path)+ .output()+ .expect("Failed to commit");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "--allow-empty", "-m", "Feature commit 2"])+ .current_dir(feature_path)+ .output()+ .expect("Failed to commit");++ // Add uncommitted changes to show working_diff_display+ std::fs::write(feature_path.join("uncommitted.txt"), "uncommitted")+ .expect("Failed to write file");+ std::fs::write(feature_path.join("feature.txt"), "modified content")+ .expect("Failed to write file");++ // Create another feature that will be behind after main advances+ repo.add_worktree("feature-behind", "feature-behind");++ // Make more commits on main (so feature-behind is behind)+ repo.commit("Main commit 1");+ repo.commit("Main commit 2");++ snapshot_list_json("json_with_display_fields", &repo);+}diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 889e39e60..9fe45f364 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpfU8Y2k/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpldTCOx/test-config.toml---success: trueexit_code: 0diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 103420401..910b99fc0 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpEBLWf9/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0jIAhK/test-config.toml---success: trueexit_code: 0@@ -250,7 +250,7 @@ complete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_frcomplete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_from run-hook" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'complete -c wt -n "__fish_wt_using_subcommand dev; and __fish_seen_subcommand_from run-hook" -s h -l help -d 'Print help'complete -c wt -n "__fish_wt_using_subcommand list" -l format -d 'Output format' -r -f -a "table\t'Human-readable table format'-json\t'JSON format'"+json\t'JSON format with colored unicode display fields'"complete -c wt -n "__fish_wt_using_subcommand list" -l branches -d 'Also display branches that don\'t have worktrees'complete -c wt -n "__fish_wt_using_subcommand list" -l ci -d 'Fetch CI status from GitHub/GitLab PRs/MRs'complete -c wt -n "__fish_wt_using_subcommand list" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex e9f142401..d56d89400 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -16,7 +16,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIdFGcP/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpes26rH/test-config.toml---success: trueexit_code: 0@@ -258,7 +258,7 @@ esac(list)_arguments "${_arguments_options[@]}" : \'--format=[Output format]:FORMAT:((table\:"Human-readable table format"-json\:"JSON format"))' \+json\:"JSON format with colored unicode display fields"))' \'--branches[Also display branches that don'\''t have worktrees]' \'--ci[Fetch CI status from GitHub/GitLab PRs/MRs]' \'-v[Enable verbose output (show git commands and debug info)]' \diff --git a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snapnew file mode 100644index 000000000..ecff4f78f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap@@ -0,0 +1,121 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ - "--format=json"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp2EXKU6/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+[+ {+ "type": "worktree",+ "worktree": {+ "path": "[REPO]",+ "head": "[SHA]",+ "branch": "main",+ "bare": false,+ "detached": false,+ "locked": null,+ "prunable": null+ },+ "timestamp": 0,+ "commit_message": "Main commit 2",+ "ahead": 0,+ "behind": 0,+ "working_tree_diff": [+ 0,+ 0+ ],+ "branch_diff": [+ 0,+ 0+ ],+ "is_primary": true,+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "worktree_state": null,+ "pr_status": null+ },+ {+ "type": "worktree",+ "worktree": {+ "path": "[WORKTREE_FEATURE_AHEAD]",+ "head": "[SHA]",+ "branch": "feature-ahead",+ "bare": false,+ "detached": false,+ "locked": null,+ "prunable": null+ },+ "timestamp": 0,+ "commit_message": "Feature commit 2",+ "ahead": 2,+ "behind": 2,+ "working_tree_diff": [+ 1,+ 1+ ],+ "branch_diff": [+ 1,+ 0+ ],+ "is_primary": false,+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "worktree_state": null,+ "pr_status": null,+ "commits_display": "[GREEN]↑2[RESET] [DIM][RED]↓2[RESET]",+ "working_diff_display": "[GREEN]+1[RESET] [RED]-1[RESET]",+ "branch_diff_display": "[GREEN]+1[RESET]"+ },+ {+ "type": "worktree",+ "worktree": {+ "path": "[WORKTREE_FEATURE_BEHIND]",+ "head": "[SHA]",+ "branch": "feature-behind",+ "bare": false,+ "detached": false,+ "locked": null,+ "prunable": null+ },+ "timestamp": 0,+ "commit_message": "Initial commit on main",+ "ahead": 0,+ "behind": 2,+ "working_tree_diff": [+ 0,+ 0+ ],+ "branch_diff": [+ 0,+ 0+ ],+ "is_primary": false,+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "worktree_state": null,+ "pr_status": null,+ "commits_display": "[DIM][RED]↓2[RESET]"+ }+]++----- stderr -----