Skip to content

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

feat(layout): Extract list width computation and unify display field computations

Maximilian Roos2007221d4a91
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 12173331c..db9a7b6b5 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -250,19 +250,6 @@ fn compute_item_status_symbols(
}
}
-fn compute_all_status_symbols(
- all_items: &mut [ListItem],
- sorted_worktrees: &[Worktree],
- primary: &Worktree,
-) {
- let mut worktree_idx = 0;
- for item in all_items.iter_mut() {
- if compute_item_status_symbols(item, sorted_worktrees, primary, worktree_idx) {
- worktree_idx += 1;
- }
- }
-}
-
/// Drain cell updates from the channel and apply them to worktree_items.
///
/// This is the shared logic between progressive and buffered collection modes.
@@ -417,11 +404,9 @@ pub fn collect(
fetch_ci,
);
- // Single-line invariant: compute width from the draw target (stderr) with right guard
- // to prevent line wrapping (which breaks indicatif's line-based cursor math).
- // Keep 2 columns free: off-by-one terminal behavior + emoji width safety margin.
- let (_, term_cols) = console::Term::stderr().size();
- let max_width = term_cols.saturating_sub(2) as usize;
+ // Single-line invariant: use safe width to prevent line wrapping
+ // (which breaks indicatif's line-based cursor math).
+ let max_width = super::layout::get_safe_list_width();
let clamp = |s: &str| -> String {
if console::measure_text_width(s) > max_width {
@@ -736,27 +721,33 @@ pub fn collect(
// Compute status_symbols for any items that didn't get computed during progressive loading
// (fallback for buffered mode or if progressive computation was skipped for some reason)
- compute_all_status_symbols(&mut all_items, &sorted_worktrees, &primary);
-
- // Buffered mode: compute display fields (progressive mode doesn't need this as rendering uses raw data)
- if !show_progress {
- for info in &mut all_items {
- info.display = super::model::DisplayFields::from_common_fields(
- &info.counts,
- &info.branch_diff,
- &info.upstream,
- &info.pr_status,
- );
-
- if let super::model::ItemKind::Worktree(ref mut wt_data) = info.kind
- && let Some(ref working_tree_diff) = wt_data.working_tree_diff
- {
- wt_data.working_diff_display = super::columns::ColumnKind::WorkingDiff
- .format_diff_plain(working_tree_diff.added, working_tree_diff.deleted);
+ {
+ let mut worktree_idx = 0;
+ for item in all_items.iter_mut() {
+ if compute_item_status_symbols(item, &sorted_worktrees, &primary, worktree_idx) {
+ worktree_idx += 1;
}
}
}
+ // Compute display fields for all items (used by JSON output and buffered mode)
+ // Progressive mode renders from raw data during collection but still populates these for consistency
+ for info in &mut all_items {
+ info.display = super::model::DisplayFields::from_common_fields(
+ &info.counts,
+ &info.branch_diff,
+ &info.upstream,
+ &info.pr_status,
+ );
+
+ if let super::model::ItemKind::Worktree(ref mut wt_data) = info.kind
+ && let Some(ref working_tree_diff) = wt_data.working_tree_diff
+ {
+ wt_data.working_diff_display = super::columns::ColumnKind::WorkingDiff
+ .format_diff_plain(working_tree_diff.added, working_tree_diff.deleted);
+ }
+ }
+
// all_items now contains both worktrees and branches (if requested)
let items = all_items;
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 51d6ffc75..e73d68a21 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -197,6 +197,17 @@ pub const HEADER_CI: &str = "CI";
pub const HEADER_COMMIT: &str = "Commit";
pub const HEADER_MESSAGE: &str = "Message";
+/// Get safe terminal width for list rendering.
+///
+/// Reserves 2 columns as a safety margin to prevent line wrapping:
+/// - Off-by-one terminal behavior
+/// - Emoji width safety margin
+///
+/// This matches the clamping logic in progressive mode (collect.rs).
+pub fn get_safe_list_width() -> usize {
+ get_terminal_width().saturating_sub(2)
+}
+
/// Calculate maximum display width for a value using compact notation.
/// Returns the character width (including suffix) when the value is formatted.
///
@@ -319,21 +330,6 @@ pub struct LayoutMetadata {
const EMPTY_PENALTY: u8 = 10;
-#[derive(Clone, Copy, Debug)]
-pub struct DiffDigits {
- pub added: usize,
- pub deleted: usize,
-}
-
-impl From<DiffWidths> for DiffDigits {
- fn from(widths: DiffWidths) -> Self {
- Self {
- added: widths.added_digits,
- deleted: widths.deleted_digits,
- }
- }
-}
-
#[derive(Clone, Copy, Debug)]
pub struct DiffDisplayConfig {
pub variant: DiffVariant,
@@ -392,7 +388,8 @@ pub enum ColumnFormat {
#[derive(Clone, Copy, Debug)]
pub struct DiffColumnConfig {
- pub digits: DiffDigits,
+ pub added_digits: usize,
+ pub deleted_digits: usize,
pub total_width: usize,
pub display: DiffDisplayConfig,
}
@@ -442,7 +439,8 @@ impl ColumnIdeal {
Some(Self {
width: widths.total,
format: ColumnFormat::Diff(DiffColumnConfig {
- digits: widths.into(),
+ added_digits: widths.added_digits,
+ deleted_digits: widths.deleted_digits,
total_width: widths.total,
display,
}),
@@ -787,7 +785,7 @@ pub fn calculate_responsive_layout(
show_full: bool,
fetch_ci: bool,
) -> LayoutConfig {
- let terminal_width = get_terminal_width();
+ let terminal_width = get_safe_list_width();
let paths: Vec<&Path> = items
.iter()
.filter_map(|item| item.worktree_path().map(|path| path.as_path()))
@@ -847,7 +845,7 @@ pub fn calculate_layout_from_basics(
show_full: bool,
fetch_ci: bool,
) -> LayoutConfig {
- let terminal_width = get_terminal_width();
+ let terminal_width = get_safe_list_width();
// Calculate common prefix from paths
let paths: Vec<&Path> = worktrees.iter().map(|wt| wt.path.as_path()).collect();
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index d209bf2d9..d769ed352 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -132,13 +132,8 @@ pub fn handle_list(
match format {
crate::OutputFormat::Json => {
- // Enrich with formatted display fields for JSON output
- let enriched_items: Vec<_> = items
- .into_iter()
- .map(ListItem::with_display_fields)
- .collect();
-
- let json = serde_json::to_string_pretty(&enriched_items).map_err(|e| {
+ // Display fields are already computed in collect()
+ let json = serde_json::to_string_pretty(&items).map_err(|e| {
GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))
})?;
crate::output::raw(json)?;
@@ -289,32 +284,3 @@ impl LayoutConfig {
Ok(())
}
}
-
-impl ListItem {
- /// Enrich a ListItem with formatted display fields for JSON output.
- ///
- /// This converts the progressive display format (None = use actual data)
- /// into fully formatted ANSI strings for all fields.
- fn with_display_fields(mut self) -> Self {
- // Create formatted display fields from common fields
- let mut display = model::DisplayFields::from_common_fields(
- &self.counts,
- &self.branch_diff,
- &self.upstream,
- &self.pr_status,
- );
-
- // Preserve status_display (git symbols + user status)
- display.status_display = self.display.status_display.clone();
-
- // Handle worktree-specific field
- if let model::ItemKind::Worktree(data) = &mut self.kind {
- data.working_diff_display = data.working_tree_diff.as_ref().and_then(|diff| {
- columns::ColumnKind::WorkingDiff.format_diff_plain(diff.added, diff.deleted)
- });
- }
-
- self.display = display;
- self
- }
-}
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index e158e4a6d..98238a861 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -217,16 +217,16 @@ impl DiffColumnConfig {
let mut segment = StyledLine::new();
// Check for overflow
- let positive_overflow = Self::exceeds_width(positive, self.digits.added);
- let negative_overflow = Self::exceeds_width(negative, self.digits.deleted);
+ let positive_overflow = Self::exceeds_width(positive, self.added_digits);
+ let negative_overflow = Self::exceeds_width(negative, self.deleted_digits);
if positive == 0 && negative == 0 && !self.display.always_show_zeros {
segment.push_raw(" ".repeat(self.total_width));
return segment;
}
- let positive_width = 1 + self.digits.added;
- let negative_width = 1 + self.digits.deleted;
+ let positive_width = 1 + self.added_digits;
+ let negative_width = 1 + self.deleted_digits;
// Fixed content width ensures vertical alignment of subcolumns
let content_width = positive_width + 1 + negative_width;
@@ -662,7 +662,7 @@ impl ColumnLayout {
#[cfg(test)]
mod tests {
use super::*;
- use crate::commands::list::layout::{DiffDigits, DiffDisplayConfig};
+ use crate::commands::list::layout::DiffDisplayConfig;
use worktrunk::styling::{ADDITION, DELETION, StyledLine};
fn format_diff_like_column(
@@ -678,16 +678,13 @@ mod tests {
use super::super::columns::DiffVariant;
// Case 1: Single-digit diffs with total=6 (to fit "WT +/-" header)
- let digits = DiffDigits {
- added: 1,
- deleted: 1,
- };
let total = 6;
let result = format_diff_like_column(
1,
1,
DiffColumnConfig {
- digits,
+ added_digits: 1,
+ deleted_digits: 1,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -704,16 +701,13 @@ mod tests {
);
// Case 2: Two-digit diffs with total=8
- let digits = DiffDigits {
- added: 2,
- deleted: 2,
- };
let total = 8;
let result = format_diff_like_column(
10,
50,
DiffColumnConfig {
- digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -730,16 +724,13 @@ mod tests {
);
// Case 3: Asymmetric digit counts with total=9
- let digits = DiffDigits {
- added: 3,
- deleted: 2,
- };
let total = 9;
let result = format_diff_like_column(
100,
50,
DiffColumnConfig {
- digits,
+ added_digits: 3,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -756,16 +747,13 @@ mod tests {
);
// Case 4: Zero diff should also pad to total width
- let digits = DiffDigits {
- added: 1,
- deleted: 1,
- };
let total = 6;
let result = format_diff_like_column(
0,
0,
DiffColumnConfig {
- digits,
+ added_digits: 1,
+ deleted_digits: 1,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -783,17 +771,14 @@ mod tests {
// Test that diff values are right-aligned within the total width
use super::super::columns::DiffVariant;
- let digits = DiffDigits {
- added: 1,
- deleted: 1,
- };
let total = 6;
let result = format_diff_like_column(
1,
1,
DiffColumnConfig {
- digits,
+ added_digits: 1,
+ deleted_digits: 1,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -925,10 +910,6 @@ mod tests {
use super::super::columns::DiffVariant;
use worktrunk::styling::{ADDITION, DELETION};
- let digits = DiffDigits {
- added: 2,
- deleted: 2,
- };
let total = 7;
let dim_deletion = DELETION.dimmed();
@@ -939,7 +920,8 @@ mod tests {
ahead,
behind,
DiffColumnConfig {
- digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -958,10 +940,6 @@ mod tests {
use super::super::columns::DiffVariant;
use worktrunk::styling::{ADDITION, DELETION};
- let digits = DiffDigits {
- added: 0,
- deleted: 2,
- };
let total = 7;
let dim_deletion = DELETION.dimmed();
@@ -970,7 +948,8 @@ mod tests {
0,
0,
DiffColumnConfig {
- digits,
+ added_digits: 0,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -986,7 +965,8 @@ mod tests {
0,
50,
DiffColumnConfig {
- digits,
+ added_digits: 0,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -1004,10 +984,6 @@ mod tests {
use super::super::columns::DiffVariant;
use worktrunk::styling::{ADDITION, DELETION};
- let digits = DiffDigits {
- added: 1,
- deleted: 1,
- };
let total = 7;
let dim_deletion = DELETION.dimmed();
@@ -1017,7 +993,8 @@ mod tests {
0,
0,
DiffColumnConfig {
- digits,
+ added_digits: 1,
+ deleted_digits: 1,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -1037,7 +1014,8 @@ mod tests {
0,
0,
DiffColumnConfig {
- digits,
+ added_digits: 1,
+ deleted_digits: 1,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -1123,10 +1101,6 @@ mod tests {
// Test that numbers are right-aligned on the ones column
// When we have 2-digit allocation but use 1-digit values, they should have leading space
- let digits = DiffDigits {
- added: 2, // Allocates 3 chars: "+NN"
- deleted: 2,
- };
let total = 8; // 3 (added) + 1 (separator) + 3 (deleted) + 1 (leading padding)
// Test case 1: (53, 7) - large added, small deleted
@@ -1134,7 +1108,8 @@ mod tests {
53,
7,
DiffColumnConfig {
- digits,
+ added_digits: 2, // Allocates 3 chars: "+NN"
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1153,7 +1128,8 @@ mod tests {
33,
23,
DiffColumnConfig {
- digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1172,7 +1148,8 @@ mod tests {
2,
2,
DiffColumnConfig {
- digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1216,10 +1193,6 @@ mod tests {
// Test overflow with Signs variant (+ and -)
// Allocated: 3 digits for added, 3 digits for deleted (total width 9)
// Max value: 999
- let digits = DiffDigits {
- added: 3,
- deleted: 3,
- };
let total = 9;
// Case 1: Value just within limit (should render normally)
@@ -1227,7 +1200,8 @@ mod tests {
999,
999,
DiffColumnConfig {
- digits,
+ added_digits: 3,
+ deleted_digits: 3,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1246,7 +1220,8 @@ mod tests {
1000,
500,
DiffColumnConfig {
- digits,
+ added_digits: 3,
+ deleted_digits: 3,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1275,7 +1250,8 @@ mod tests {
500,
1000,
DiffColumnConfig {
- digits,
+ added_digits: 3,
+ deleted_digits: 3,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1303,7 +1279,8 @@ mod tests {
100_000,
200_000,
DiffColumnConfig {
- digits,
+ added_digits: 3,
+ deleted_digits: 3,
total_width: total,
display: DiffDisplayConfig {
variant: DiffVariant::Signs,
@@ -1331,10 +1308,6 @@ mod tests {
);
// Test overflow with Arrows variant (↑ and ↓)
- let arrow_digits = DiffDigits {
- added: 2,
- deleted: 2,
- };
let arrow_total = 7;
// Case 5: Arrow positive overflow (100 exceeds 2 digits, max is 99)
@@ -1343,7 +1316,8 @@ mod tests {
1000, // Use larger value to show K suffix
50,
DiffColumnConfig {
- digits: arrow_digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: arrow_total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,
@@ -1372,7 +1346,8 @@ mod tests {
50,
1000, // Use larger value to show K suffix
DiffColumnConfig {
- digits: arrow_digits,
+ added_digits: 2,
+ deleted_digits: 2,
total_width: arrow_total,
display: DiffDisplayConfig {
variant: DiffVariant::Arrows,