Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(list): align JSON status symbols with terminal output (#4335)
Maximilian Roos85e685e313f7
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 4c62be425..8b2e0e02c 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -111,7 +111,7 @@ pub struct JsonItem {#[serde(skip_serializing_if = "Option::is_none")]pub statusline: Option<String>,- /// Raw status symbols without ANSI colors (e.g., "+! ✖ ↑")+ /// Raw status symbols without ANSI colors (e.g., `"+!⚐↑"`)#[serde(skip_serializing_if = "Option::is_none")]pub symbols: Option<String>,@@ -391,7 +391,7 @@ impl JsonItem {// Statusline and symbols (raw, without ANSI codes)let statusline = item.statusline.clone();- let symbols = Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty());+ let symbols = Some(item.status_symbols.format_raw()).filter(|s| !s.is_empty());let marker = item.user_marker.clone().flatten();// Per-branch vars data (pre-fetched, moved out to avoid cloning)@@ -511,62 +511,6 @@ impl JsonCi {}}-/// Format status symbols as raw characters (no ANSI codes).-///-/// Unresolved gates (`None` fields) contribute nothing — their symbols are-/// simply absent from the output string, not replaced by a placeholder.-/// This matches the per-symbol atomic model: machine consumers see only the-/// symbols that have been computed so far.-///-/// Shared with `json_v2` (the `display.symbols` field).-pub(crate) fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {- let mut result = String::new();-- // Working tree symbols (gate 1)- if let Some(wt) = symbols.working_tree {- result.push_str(&wt.to_symbols());- }-- // Main state (gate 3) — merged column: ^_⊂✗↕↑↓- if let Some(ms) = symbols.main_state {- let s = ms.to_string();- if !s.is_empty() {- result.push_str(&s);- }- }-- // Upstream divergence (gate 4)- if let Some(div) = symbols.upstream_divergence {- let s = div.symbol();- if !s.is_empty() {- result.push_str(s);- }- }-- // Worktree state (gate 2) — operations (✘↻) take priority over- // location (/⚐⊟⊞). Gate 2 is "operation_state is Some"; the metadata- // worktree_state is filled synchronously and always Some by the time- // the operation family is known.- if let Some(op) = symbols.operation_state {- let s = op.to_string();- if !s.is_empty() {- result.push_str(&s);- } else if let Some(wt_state) = symbols.worktree_state {- let s = wt_state.to_string();- if !s.is_empty() {- result.push_str(&s);- }- }- }-- // User marker (gate 5)- if let Some(Some(ref marker)) = symbols.user_marker {- result.push_str(marker);- }-- result-}-/// Convert a list of ListItems to JSON output////// Reads all vars from the bulk config snapshot (no subprocess, and —@@ -601,7 +545,6 @@ pub fn to_json_items(mod tests {use insta::assert_snapshot;use worktrunk::git::GitRepoProvider;- use worktrunk::git::InProgressOperation;use super::*;use crate::commands::list::ci_status::{CiStatus, PrRef};@@ -920,72 +863,6 @@ mod tests {assert_eq!(reason, Some("in use".to_string()));}- // ============================================================================- // format_raw_symbols Tests- // ============================================================================-- #[test]- fn test_format_raw_symbols_empty() {- let symbols = StatusSymbols::default();- assert!(format_raw_symbols(&symbols).is_empty());- }-- #[test]- fn test_format_raw_symbols_each_category() {- let working_tree = format_raw_symbols(&StatusSymbols {- working_tree: Some(WorkingTreeStatus::new(true, true, true, false, false)),- ..Default::default()- });- assert_snapshot!(working_tree, @"+!?");-- let main_state = format_raw_symbols(&StatusSymbols {- main_state: Some(MainState::Ahead),- ..Default::default()- });- assert_snapshot!(main_state, @"↑");-- let upstream = format_raw_symbols(&StatusSymbols {- upstream_divergence: Some(Divergence::Behind),- ..Default::default()- });- assert_snapshot!(upstream, @"⇣");-- // Operation state takes priority over worktree state- let operation = format_raw_symbols(&StatusSymbols {- operation_state: Some(OperationState::InProgress(InProgressOperation::Rebase)),- ..Default::default()- });- assert_snapshot!(operation, @"↻");-- // Worktree metadata renders only once the operation-family gate- // has resolved to "no operation" — otherwise we can't rule out- // ✘↻ taking priority. Callers that want just the metadata- // symbol must set both `operation_state` and `worktree_state`.- let worktree = format_raw_symbols(&StatusSymbols {- operation_state: Some(OperationState::None),- worktree_state: Some(WorktreeState::Locked),- ..Default::default()- });- assert_snapshot!(worktree, @"⊞");-- let marker = format_raw_symbols(&StatusSymbols {- user_marker: Some(Some("\u{1f525}".to_string())),- ..Default::default()- });- assert_snapshot!(marker, @"🔥");- }-- #[test]- fn test_format_raw_symbols_combined() {- let result = format_raw_symbols(&StatusSymbols {- working_tree: Some(WorkingTreeStatus::new(true, false, false, false, false)),- main_state: Some(MainState::Behind),- upstream_divergence: Some(Divergence::Ahead),- ..Default::default()- });- assert_snapshot!(result, @"+↓⇡");- }-// ============================================================================// JSON Serialization Tests// ============================================================================diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rsindex 316162f63..4a4c26591 100644--- a/src/commands/list/json_v2.rs+++ b/src/commands/list/json_v2.rs@@ -38,7 +38,7 @@ use worktrunk::git::{use super::ci_status::{CiSource, CiStatus, PrStatus, ReviewState};use super::custom_columns::ResolvedCustomColumn;-use super::json_output::{JsonDiff, format_raw_symbols};+use super::json_output::JsonDiff;use super::model::{BranchScope, Collected, ItemKind, ListItem, MainState, WorktreeData};/// Tri-state field encoding the absence rule (see module docs).@@ -704,7 +704,7 @@ impl JsonItemV2 {.status_symbols.main_state.and_then(JsonMainState::from_main_state),- symbols: Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty()),+ symbols: Some(item.status_symbols.format_raw()).filter(|s| !s.is_empty()),statusline: item.statusline.clone(),columns,};diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rsindex 917dd5e77..49f22b47b 100644--- a/src/commands/list/model/status_symbols.rs+++ b/src/commands/list/model/status_symbols.rs@@ -342,7 +342,7 @@ impl WorkingTreeStatus {/// Format as display string for JSON serialization and raw output (e.g., "+!?").///- /// For styled terminal rendering, use `StatusSymbols::styled_symbols()` instead.+ /// For styled terminal rendering, use `StatusSymbols::render_with_mask()` instead.pub fn to_symbols(self) -> String {let mut s = String::with_capacity(5);if self.staged {@@ -459,7 +459,7 @@ impl StatusSymbols {let mut result = String::with_capacity(64);- for (pos, slot) in self.styled_symbols() {+ for (pos, slot) in self.symbols(SymbolFormat::Styled) {let allocated_width = mask.width(pos);match slot {@@ -495,7 +495,7 @@ impl StatusSymbols {////// Uses the same styled symbols as `render_with_mask()`, just without padding.pub fn format_compact(&self) -> String {- self.styled_symbols()+ self.symbols(SymbolFormat::Styled).into_iter().filter_map(|(_, slot)| match slot {SlotState::Visible(s) => Some(s),@@ -507,7 +507,21 @@ impl StatusSymbols {.collect()}- /// Build styled symbols array with position indices.+ /// Raw JSON symbols in the same gate order as terminal output.+ ///+ /// Unresolved gates are omitted. Working-tree rename/delete glyphs and+ /// user marker text retain their raw JSON representation.+ pub(crate) fn format_raw(&self) -> String {+ self.symbols(SymbolFormat::Raw)+ .into_iter()+ .filter_map(|(_, slot)| match slot {+ SlotState::Visible(s) => Some(s),+ SlotState::Loading | SlotState::Empty => None,+ })+ .collect()+ }++ /// Build symbols in Status-column order with shared gate selection.////// Returns one [`SlotState`] per position. The renderer uses this to/// emit three kinds of cell content: `Loading` slots are rendered as the@@ -522,14 +536,20 @@ impl StatusSymbols {/// - Red: Conflicts (blocking problems)/// - Yellow: Git operations, would_conflict, locked/prunable (states needing attention)/// - Dimmed: Main state symbols, divergence arrows, branch indicator (informational)- pub(crate) fn styled_symbols(&self) -> [(usize, SlotState); 7] {+ fn symbols(&self, format: SymbolFormat) -> [(usize, SlotState); 7] {use color_print::cformat;// Gate 1 — working tree flags (positions 0-2). One logical decision,// so while loading we emit a single `·` at the lead position and// blank-pad the other two — keeps the gate's visual weight equal to- // the single-position gates 2-5.+ // the single-position gates 2-5. Raw output has no alignment, so+ // the lead slot contains all working-tree glyphs, including »✘.let (staged, modified, untracked) = match self.working_tree {+ Some(wt) if matches!(format, SymbolFormat::Raw) => (+ SlotState::from_content(wt.to_symbols()),+ SlotState::Empty,+ SlotState::Empty,+ ),Some(wt) => {let flag = |has: bool, sym: char| -> SlotState {if has {@@ -549,19 +569,19 @@ impl StatusSymbols {// Gate 3 — main state (position 4).let main_state_slot = match self.main_state {- Some(ms) => match ms.styled() {- Some(s) => SlotState::Visible(s),- None => SlotState::Empty,- },+ Some(ms) => SlotState::from_content(match format {+ SymbolFormat::Raw => ms.to_string(),+ SymbolFormat::Styled => ms.styled().unwrap_or_default(),+ }),None => SlotState::Loading,};// Gate 4 — upstream divergence (position 5).let upstream_slot = match self.upstream_divergence {- Some(d) => match d.styled() {- Some(s) => SlotState::Visible(s),- None => SlotState::Empty,- },+ Some(d) => SlotState::from_content(match format {+ SymbolFormat::Raw => d.symbol().to_string(),+ SymbolFormat::Styled => d.styled().unwrap_or_default(),+ }),None => SlotState::Loading,};@@ -575,17 +595,21 @@ impl StatusSymbols {// it's always `Some` by the time `operation_state` resolves).let worktree_slot = match self.operation_state {None => SlotState::Loading,- Some(op) if op != OperationState::None => {- SlotState::Visible(op.styled().unwrap_or_default())- }+ Some(op) if op != OperationState::None => SlotState::Visible(match format {+ SymbolFormat::Raw => op.to_string(),+ SymbolFormat::Styled => op.styled().unwrap_or_default(),+ }),Some(_) => match self.worktree_state {None | Some(WorktreeState::None) => SlotState::Empty,- Some(- state @ (WorktreeState::Branch- | WorktreeState::BranchWorktreeMismatch- | WorktreeState::DuplicateBranch),- ) => SlotState::Visible(cformat!("<dim>{state}</>")),- Some(other) => SlotState::Visible(cformat!("<yellow>{}</>", other)),+ Some(state) => SlotState::Visible(match format {+ SymbolFormat::Raw => state.to_string(),+ SymbolFormat::Styled => match state {+ WorktreeState::Branch+ | WorktreeState::BranchWorktreeMismatch+ | WorktreeState::DuplicateBranch => cformat!("<dim>{state}</>"),+ _ => cformat!("<yellow>{state}</>"),+ },+ }),},};@@ -610,13 +634,20 @@ impl StatusSymbols {}}+/// Raw JSON uses compact glyphs; terminal output uses styled, aligned slots.+#[derive(Clone, Copy)]+enum SymbolFormat {+ Raw,+ Styled,+}+/// State of a single Status-column slot when rendering.///-/// Returned by [`StatusSymbols::styled_symbols`] so the renderer can decide,+/// Returned by [`StatusSymbols::symbols`] so the renderer can decide,/// per position, whether to emit a position-level placeholder (`Loading`),/// blank whitespace (`Empty`), or the styled content (`Visible`).#[derive(Debug, Clone)]-pub(crate) enum SlotState {+enum SlotState {/// Gate has not resolved — emit the placeholder glyph padded to the/// slot's allocated width.Loading,@@ -628,6 +659,16 @@ pub(crate) enum SlotState {Visible(String),}+impl SlotState {+ fn from_content(content: String) -> Self {+ if content.is_empty() {+ Self::Empty+ } else {+ Self::Visible(content)+ }+ }+}+#[cfg(test)]mod tests {use insta::assert_snapshot;@@ -635,6 +676,128 @@ mod tests {use super::*;+ // ============================================================================+ // format_raw_symbols Tests+ // ============================================================================++ #[test]+ fn test_format_raw_symbols_empty() {+ let symbols = StatusSymbols::default();+ assert!(symbols.format_raw().is_empty());+ }++ #[test]+ fn test_format_raw_symbols_each_category() {+ let working_tree = (StatusSymbols {+ working_tree: Some(WorkingTreeStatus::new(true, true, true, false, false)),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(working_tree, @"+!?");++ let main_state = (StatusSymbols {+ main_state: Some(MainState::Ahead),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(main_state, @"↑");++ let upstream = (StatusSymbols {+ upstream_divergence: Some(Divergence::Behind),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(upstream, @"⇣");++ // Operation state takes priority over worktree state+ let operation = (StatusSymbols {+ operation_state: Some(OperationState::InProgress(InProgressOperation::Rebase)),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(operation, @"↻");++ // Worktree metadata renders only once the operation-family gate+ // has resolved to "no operation" — otherwise we can't rule out+ // ✘↻ taking priority. Callers that want just the metadata+ // symbol must set both `operation_state` and `worktree_state`.+ let worktree = (StatusSymbols {+ operation_state: Some(OperationState::None),+ worktree_state: Some(WorktreeState::Locked),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(worktree, @"⊞");++ let marker = (StatusSymbols {+ user_marker: Some(Some("\u{1f525}".to_string())),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(marker, @"🔥");+ }++ #[test]+ fn test_format_raw_symbols_combined() {+ let result = (StatusSymbols {+ working_tree: Some(WorkingTreeStatus::new(true, false, false, false, false)),+ main_state: Some(MainState::Behind),+ upstream_divergence: Some(Divergence::Ahead),+ ..Default::default()+ })+ .format_raw();+ assert_snapshot!(result, @"+↓⇡");+ }++ /// Pin all gates together against the rendered cell's order.+ #[test]+ fn test_format_raw_symbols_follow_rendered_order() {+ let symbols = StatusSymbols {+ working_tree: Some(WorkingTreeStatus::new(false, true, false, false, false)),+ operation_state: Some(OperationState::None),+ worktree_state: Some(WorktreeState::BranchWorktreeMismatch),+ main_state: Some(MainState::Ahead),+ upstream_divergence: Some(Divergence::Diverged),+ user_marker: Some(Some("\u{1f525}".to_string())),+ };+ let raw = symbols.format_raw();+ assert_snapshot!(raw, @"!⚐↑⇅🔥");+ assert_eq!(+ raw,+ anstream::adapter::strip_str(&symbols.format_compact()).to_string(),+ "raw symbols must match the rendered cell with its ANSI stripped"+ );+ }++ #[test]+ fn test_format_raw_preserves_working_tree_glyphs() {+ let symbols = StatusSymbols {+ working_tree: Some(WorkingTreeStatus::new(true, true, true, true, true)),+ main_state: Some(MainState::Ahead),+ ..Default::default()+ };+ assert_eq!(symbols.format_raw(), "+!?»✘↑");+ assert_eq!(+ anstream::adapter::strip_str(&symbols.format_compact()).to_string(),+ "+!?↑"+ );+ }++ #[test]+ fn test_format_raw_worktree_gate_priority() {+ let mut symbols = StatusSymbols {+ worktree_state: Some(WorktreeState::Locked),+ main_state: Some(MainState::Ahead),+ ..Default::default()+ };+ // Metadata stays hidden until the operation gate resolves.+ assert_eq!(symbols.format_raw(), "↑");+ symbols.operation_state = Some(OperationState::InProgress(InProgressOperation::Rebase));+ assert_eq!(symbols.format_raw(), "↻↑");+ symbols.operation_state = Some(OperationState::None);+ assert_eq!(symbols.format_raw(), "⊞↑");+ }+/// True iff every gate is either unresolved (`None`) or resolved to a/// "nothing to display" variant. Sanity check for `Default` //// `None`-variant semantics of gate outputs.diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex d9a18d33f..ae3bc4088 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1084,6 +1084,13 @@ fn setup_snapshot_settings_for_paths_with_home("$1 # $2",);+ // Git 2.56 names ambiguous remote-tracking branches; older Git reports+ // the same failed worktree-add lookup as an invalid reference.+ settings.add_filter(+ r"fatal: '([^'\r\n]+)' matched multiple \(\d+\) remote tracking branches",+ "fatal: invalid reference: $1",+ );+// Normalize OS-specific error messages in gutter output// Ubuntu may produce "Broken pipe (os error 32)" instead of the expected error// when capturing stderr from shell commands due to timing/buffering differencesdiff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 0eec5ab93..122cf303a 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -1178,6 +1178,85 @@ fn test_list_json_with_user_marker(mut repo: TestRepo) {});}+/// Extract the populated Status cell from the all-gates fixture below.+/// Its ASCII marker leaves the column padding as runs of two or more spaces.+fn status_cell(table: &str, branch: &str) -> String {+ let fields = table+ .lines()+ .map(|line| {+ line.split(" ")+ .map(str::trim)+ .filter(|field| !field.is_empty())+ .collect::<Vec<_>>()+ })+ .find(|fields| fields.first().is_some_and(|f| f.ends_with(branch)))+ .unwrap_or_else(|| panic!("no row for {branch:?}:\n{table}"));+ fields[1].chars().filter(|c| !c.is_whitespace()).collect()+}++/// Both JSON schemas follow the rendered Status column's gate order.+/// The fixture populates every gate: an off-template worktree path, commits+/// missing from main and upstream, an uncommitted edit, and an ASCII marker.+#[rstest]+fn test_list_json_symbols_follow_status_column(#[from(repo_with_remote)] mut repo: TestRepo) {+ use ansi_str::AnsiStr;++ let off_template = repo+ .root_path()+ .parent()+ .expect("repo has a parent directory")+ .join("off-template");+ let feature = repo.add_worktree_at_path("feature", &off_template);+ repo.commit_in_worktree(&feature, "feature.txt", "one\n", "Add feature file");+ repo.run_git_in(&feature, &["push", "-u", "origin", "feature"]);+ repo.commit_in_worktree(&feature, "second.txt", "two\n", "Add second file");+ std::fs::write(feature.join("feature.txt"), "edited\n").unwrap();+ repo.set_marker("feature", "*");++ let run = |args: &[&str]| {+ let output = repo+ .wt_command()+ .args(args)+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ assert!(output.status.success(), "wt {args:?} should succeed");+ output.stdout+ };++ repo.write_test_config("[list]\njson-schema = 2\n");+ let table = String::from_utf8_lossy(&run(&["list"]))+ .ansi_strip()+ .into_owned();+ let rendered = status_cell(&table, "feature");+ assert_eq!(rendered, "!⚐↑⇡*", "every gate populated:\n{table}");++ let envelope: serde_json::Value =+ serde_json::from_slice(&run(&["list", "--format=json"])).unwrap();+ let schema_2 = envelope["items"]+ .as_array()+ .expect("items array")+ .iter()+ .find(|item| item["branch"] == "feature")+ .expect("feature row")["display"]["symbols"]+ .as_str()+ .expect("symbols")+ .to_string();+ assert_eq!(schema_2, rendered, "schema 2 follows the rendered order");++ repo.write_test_config("[list]\njson-schema = 1\n");+ let items: Vec<serde_json::Value> =+ serde_json::from_slice(&run(&["list", "--format=json"])).unwrap();+ let schema_1 = items+ .iter()+ .find(|item| item["branch"] == "feature")+ .expect("feature row")["symbols"]+ .as_str()+ .expect("symbols")+ .to_string();+ assert_eq!(schema_1, rendered, "schema 1 follows the rendered order");+}+/// Schema 2 reports the branch marker as its own `marker` field, and folds/// it into `display.symbols` the way the table folds it into the Status/// column. A branch with no marker set omits the field entirely.diff --git a/tests/snapshots/integration__integration_tests__list__list_bisect_json.snap b/tests/snapshots/integration__integration_tests__list__list_bisect_json.snapindex d7a65eaf7..f6e054327 100644--- a/tests/snapshots/integration__integration_tests__list__list_bisect_json.snap+++ b/tests/snapshots/integration__integration_tests__list__list_bisect_json.snap@@ -153,7 +153,7 @@ exit_code: 0},"display": {"state": "empty",- "symbols": "_↻",+ "symbols": "↻_","statusline": "bisecting \u001b[33m↻\u001b[39m\u001b[2m_\u001b[22m"}},diff --git a/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap b/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snapindex 86c982d45..b8626c6dd 100644--- a/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap+++ b/tests/snapshots/integration__integration_tests__list__list_json_schema_2_envelope.snap@@ -338,7 +338,7 @@ exit_code: 0},"display": {"state": "empty",- "symbols": "_⊞",+ "symbols": "⊞_","statusline": "locked-feature \u001b[33m⊞\u001b[39m\u001b[2m_\u001b[22m"}}diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snapindex 67e2bc031..0acacea0d 100644--- a/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_git_operation.snap@@ -285,7 +285,7 @@ exit_code: 0},"display": {"state": "would_conflict",- "symbols": "✗✘",+ "symbols": "✘✗","statusline": "feature \u001b[31m✘\u001b[39m\u001b[33m✗\u001b[39m \u001b[32m↑1\u001b[0m \u001b[2m\u001b[31m↓1\u001b[0m ^\u001b[32m+2\u001b[0m \u001b[31m-2\u001b[0m"}}diff --git a/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snapindex b9be2a2f5..d08a4d625 100644--- a/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap+++ b/tests/snapshots/integration__integration_tests__list__list_json_with_metadata.snap@@ -290,7 +290,7 @@ exit_code: 0"is_current": false,"is_previous": false,"statusline": "locked-feature \u001b[33m⊞\u001b[39m\u001b[2m_\u001b[22m",- "symbols": "_⊞"+ "symbols": "⊞_"}]