Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Simplify render_cell design and remove unnecessary indirection (#575)
Maximilian Roos1894f9e3f94d
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex a14533b5f..ad3fc3966 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -1207,7 +1207,7 @@ pub fn collect(table.update_footer(footer_msg);// Re-render the row with caching (now includes status if computed)- let rendered = layout.format_list_item_line(item, previous_branch.as_deref());+ let rendered = layout.format_list_item_line(item);// Compare using full line so changes beyond the clamp (e.g., CI) still refresh.if rendered != last_rendered_lines[item_idx] {@@ -1288,7 +1288,7 @@ pub fn collect(if table.is_tty() {// Interactive: do final render pass and update footer to summaryfor (item_idx, item) in all_items.iter().enumerate() {- let rendered = layout.format_list_item_line(item, previous_branch.as_deref());+ let rendered = layout.format_list_item_line(item);table.update_row(item_idx, rendered);}table.finalize(final_msg)?;@@ -1297,9 +1297,7 @@ pub fn collect(// Progressive skeleton was suppressed; now output the final tablecrate::output::stdout(layout.format_header_line())?;for item in &all_items {- crate::output::stdout(- layout.format_list_item_line(item, previous_branch.as_deref()),- )?;+ crate::output::stdout(layout.format_list_item_line(item))?;}crate::output::stdout("")?;crate::output::stdout(final_msg)?;@@ -1314,7 +1312,7 @@ pub fn collect(crate::output::stdout(layout.format_header_line())?;for item in &all_items {- crate::output::stdout(layout.format_list_item_line(item, previous_branch.as_deref()))?;+ crate::output::stdout(layout.format_list_item_line(item))?;}crate::output::stdout("")?;crate::output::stdout(final_msg)?;diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex 50c4e808b..ef96e71fc 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -416,30 +416,44 @@ impl ColumnKind {}}+ /// Returns the ideal (width, format) for this column, or None if width is 0 or Message.fn ideal(self,widths: &ColumnWidths,max_path_width: usize,commit_width: usize,- ) -> Option<ColumnIdeal> {+ ) -> Option<(usize, ColumnFormat)> {+ let text = |w: usize| (w > 0).then_some((w, ColumnFormat::Text));+ let diff = |dw: DiffWidths| -> Option<(usize, ColumnFormat)> {+ if dw.total == 0 {+ return None;+ }+ let display = self.diff_display_config()?;+ Some((+ dw.total,+ ColumnFormat::Diff(DiffColumnConfig {+ positive_digits: dw.positive_digits,+ negative_digits: dw.negative_digits,+ total_width: dw.total,+ display,+ }),+ ))+ };+match self {- ColumnKind::Gutter => ColumnIdeal::text(2), // Fixed width: symbol (1 char) + space (1 char)- ColumnKind::Branch => ColumnIdeal::text(widths.branch),- ColumnKind::Status => ColumnIdeal::text(widths.status),- ColumnKind::Path => ColumnIdeal::text(max_path_width),- ColumnKind::Time => ColumnIdeal::text(widths.time),- ColumnKind::Url => ColumnIdeal::text(widths.url),- ColumnKind::CiStatus => ColumnIdeal::text(widths.ci_status),- ColumnKind::Commit => ColumnIdeal::text(commit_width),+ ColumnKind::Gutter => text(2), // Fixed width: symbol (1 char) + space (1 char)+ ColumnKind::Branch => text(widths.branch),+ ColumnKind::Status => text(widths.status),+ ColumnKind::Path => text(max_path_width),+ ColumnKind::Time => text(widths.time),+ ColumnKind::Url => text(widths.url),+ ColumnKind::CiStatus => text(widths.ci_status),+ ColumnKind::Commit => text(commit_width),ColumnKind::Message => None,- ColumnKind::WorkingDiff => {- ColumnIdeal::diff(widths.working_diff, ColumnKind::WorkingDiff)- }- ColumnKind::AheadBehind => {- ColumnIdeal::diff(widths.ahead_behind, ColumnKind::AheadBehind)- }- ColumnKind::BranchDiff => ColumnIdeal::diff(widths.branch_diff, ColumnKind::BranchDiff),- ColumnKind::Upstream => ColumnIdeal::diff(widths.upstream, ColumnKind::Upstream),+ ColumnKind::WorkingDiff => diff(widths.working_diff),+ ColumnKind::AheadBehind => diff(widths.ahead_behind),+ ColumnKind::BranchDiff => diff(widths.branch_diff),+ ColumnKind::Upstream => diff(widths.upstream),}}}@@ -475,43 +489,6 @@ pub struct LayoutConfig {pub status_position_mask: super::model::PositionMask,}-#[derive(Clone, Copy, Debug)]-struct ColumnIdeal {- width: usize,- format: ColumnFormat,-}--impl ColumnIdeal {- fn text(width: usize) -> Option<Self> {- if width == 0 {- None- } else {- Some(Self {- width,- format: ColumnFormat::Text,- })- }- }-- fn diff(widths: DiffWidths, kind: ColumnKind) -> Option<Self> {- if widths.total == 0 {- return None;- }-- let display = kind.diff_display_config()?;-- Some(Self {- width: widths.total,- format: ColumnFormat::Diff(DiffColumnConfig {- positive_digits: widths.positive_digits,- negative_digits: widths.negative_digits,- total_width: widths.total,- display,- }),- })- }-}-#[derive(Clone, Copy)]struct ColumnCandidate<'a> {spec: &'a ColumnSpec,@@ -736,20 +713,20 @@ fn allocate_columns_with_priority(}// For non-message columns- let Some(ideal) = spec- .kind- .ideal(&metadata.widths, max_path_width, commit_width)+ let Some((ideal_width, format)) =+ spec.kind+ .ideal(&metadata.widths, max_path_width, commit_width)else {continue;};let skip_spacing = !needs_spacing(&pending);- let allocated = try_allocate(&mut remaining, ideal.width, spacing, skip_spacing);+ let allocated = try_allocate(&mut remaining, ideal_width, spacing, skip_spacing);if allocated > 0 {pending.push(PendingColumn {spec,width: allocated,- format: ideal.format,+ format,});}}@@ -1036,38 +1013,6 @@ mod tests {assert!(matches!(upstream.variant, DiffVariant::UpstreamArrows));}- #[test]- fn test_column_ideal_text() {- // Zero width returns None- assert!(ColumnIdeal::text(0).is_none());-- // Non-zero width returns Some with text format- let ideal = ColumnIdeal::text(10).unwrap();- assert_eq!(ideal.width, 10);- assert!(matches!(ideal.format, ColumnFormat::Text));- }-- #[test]- fn test_column_ideal_diff() {- // Zero total returns None- let zero_widths = DiffWidths {- total: 0,- positive_digits: 0,- negative_digits: 0,- };- assert!(ColumnIdeal::diff(zero_widths, ColumnKind::WorkingDiff).is_none());-- // Non-zero returns Some with diff format- let widths = DiffWidths {- total: 9,- positive_digits: 3,- negative_digits: 3,- };- let ideal = ColumnIdeal::diff(widths, ColumnKind::WorkingDiff).unwrap();- assert_eq!(ideal.width, 9);- assert!(matches!(ideal.format, ColumnFormat::Diff(_)));- }-#[test]fn test_column_kind_ideal() {let widths = ColumnWidths {@@ -1099,38 +1044,74 @@ mod tests {},};- // Text columns- assert_eq!(- ColumnKind::Gutter.ideal(&widths, 20, 8).map(|i| i.width),- Some(2)- );- assert_eq!(- ColumnKind::Branch.ideal(&widths, 20, 8).map(|i| i.width),- Some(15)- );- assert_eq!(- ColumnKind::Status.ideal(&widths, 20, 8).map(|i| i.width),- Some(8)- );- assert_eq!(- ColumnKind::Path.ideal(&widths, 20, 8).map(|i| i.width),- Some(20)- );- assert_eq!(- ColumnKind::Time.ideal(&widths, 20, 8).map(|i| i.width),- Some(4)- );- assert_eq!(- ColumnKind::Commit.ideal(&widths, 20, 8).map(|i| i.width),- Some(8)- );+ // Text columns return (width, ColumnFormat::Text)+ let (w, fmt) = ColumnKind::Gutter.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 2);+ assert!(matches!(fmt, ColumnFormat::Text));++ let (w, fmt) = ColumnKind::Branch.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 15);+ assert!(matches!(fmt, ColumnFormat::Text));++ let (w, fmt) = ColumnKind::Status.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 8);+ assert!(matches!(fmt, ColumnFormat::Text));++ let (w, fmt) = ColumnKind::Path.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 20);+ assert!(matches!(fmt, ColumnFormat::Text));++ let (w, fmt) = ColumnKind::Time.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 4);+ assert!(matches!(fmt, ColumnFormat::Text));++ let (w, fmt) = ColumnKind::Commit.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 8);+ assert!(matches!(fmt, ColumnFormat::Text));// Message returns None (handled specially)assert!(ColumnKind::Message.ideal(&widths, 20, 8).is_none());- // Diff columns- assert!(ColumnKind::WorkingDiff.ideal(&widths, 20, 8).is_some());- assert!(ColumnKind::AheadBehind.ideal(&widths, 20, 8).is_some());+ // Diff columns return (width, ColumnFormat::Diff(_))+ let (w, fmt) = ColumnKind::WorkingDiff.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 9);+ assert!(matches!(fmt, ColumnFormat::Diff(_)));++ let (w, fmt) = ColumnKind::AheadBehind.ideal(&widths, 20, 8).unwrap();+ assert_eq!(w, 7);+ assert!(matches!(fmt, ColumnFormat::Diff(_)));++ // Zero width returns None+ let zero_widths = ColumnWidths {+ branch: 0,+ status: 0,+ time: 0,+ url: 0,+ ci_status: 0,+ message: 0,+ ahead_behind: DiffWidths {+ total: 0,+ positive_digits: 0,+ negative_digits: 0,+ },+ working_diff: DiffWidths {+ total: 0,+ positive_digits: 0,+ negative_digits: 0,+ },+ branch_diff: DiffWidths {+ total: 0,+ positive_digits: 0,+ negative_digits: 0,+ },+ upstream: DiffWidths {+ total: 0,+ positive_digits: 0,+ negative_digits: 0,+ },+ };+ assert!(ColumnKind::Branch.ideal(&zero_widths, 0, 0).is_none());+ assert!(ColumnKind::WorkingDiff.ideal(&zero_widths, 0, 0).is_none());}#[test]diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 74b76b6d7..ae93b6708 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -423,10 +423,6 @@ impl ListItem {&self.head}- pub fn commit_details(&self) -> CommitDetails {- self.commit.clone().unwrap_or_default()- }-pub fn branch_diff(&self) -> Option<&BranchDiffTotals> {self.branch_diff.as_ref()}@@ -2019,14 +2015,6 @@ mod tests {assert_eq!(item.head(), "abc123def");}- #[test]- fn test_list_item_commit_details() {- let item = ListItem::new_branch("abc123".to_string(), "feature".to_string());- let details = item.commit_details();- assert_eq!(details.timestamp, 0);- assert_eq!(details.commit_message, "");- }-#[test]fn test_list_item_counts() {// New items have no counts computed yetdiff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex ff68cb586..b7a7787b2 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -8,10 +8,7 @@ use super::ci_status::PrStatus;use super::collect_progressive_impl::parse_port_from_url;use super::columns::{ColumnKind, DiffVariant};use super::layout::{ColumnFormat, ColumnLayout, DiffColumnConfig, LayoutConfig};-use super::model::{- AheadBehind, CommitDetails, ListItem, PositionMask, UpstreamStatus, WorktreeData,-};-use worktrunk::git::LineDiff;+use super::model::{ListItem, PositionMask};impl PrStatus {/// Render indicator as a StyledLine for table column rendering.@@ -248,20 +245,15 @@ impl LayoutConfig {})}- pub fn format_list_item_line(&self, item: &ListItem, previous_branch: Option<&str>) -> String {- self.render_list_item_line(item, previous_branch).render()+ pub fn format_list_item_line(&self, item: &ListItem) -> String {+ self.render_list_item_line(item).render()}/// Render list item line as StyledLine (for extracting both plain and styled text)- pub fn render_list_item_line(- &self,- item: &ListItem,- previous_branch: Option<&str>,- ) -> StyledLine {- let ctx = ListRowContext::new(item, previous_branch);+ pub fn render_list_item_line(&self, item: &ListItem) -> StyledLine {self.render_line(|column| {column.render_cell(- &ctx,+ item,&self.status_position_mask,&self.main_worktree_path,self.max_message_len,@@ -291,8 +283,8 @@ impl LayoutConfig {match col.kind {ColumnKind::Gutter => {- // Skeleton shows placeholder gutter - actual symbols appear when data loads.- // This allows deferring previous_branch lookup until after skeleton.+ // Skeleton shows placeholder gutter - actual symbols (including is_previous)+ // appear when WorktreeData is populated post-skeleton.let symbol = if wt_data.is_some() {"· " // Placeholder for worktrees} else {@@ -330,70 +322,18 @@ impl LayoutConfig {}}-struct ListRowContext<'a> {- item: &'a ListItem,- worktree_data: Option<&'a WorktreeData>,- /// None means not yet loaded (show `⋯`), Some means computed (may be zero)- counts: Option<AheadBehind>,- /// None means task was skipped (show `…`), Some means computed (may be zero)- branch_diff: Option<LineDiff>,- upstream: UpstreamStatus,- commit: CommitDetails,- head: &'a str,- text_style: Option<Style>,- is_current: bool,- is_previous: bool,-}--impl<'a> ListRowContext<'a> {- fn new(item: &'a ListItem, previous_branch: Option<&str>) -> Self {- let worktree_data = item.worktree_data();- let counts = item.counts;- let commit = item.commit_details();- let branch_diff = item.branch_diff().map(|bd| bd.diff);- let upstream = item.upstream();- let head = item.head();-- // Use stored values for worktrees, compute for branches- let is_current = worktree_data.is_some_and(|d| d.is_current);- let is_previous = worktree_data.map(|d| d.is_previous).unwrap_or_else(|| {- // Branches don't have WorktreeData, compute from previous_branch- previous_branch.is_some_and(|prev| item.branch.as_deref() == Some(prev))- });-- let mut ctx = Self {- item,- worktree_data,- counts,- branch_diff,- upstream,- commit,- head,- text_style: None,- is_current,- is_previous,- };-- ctx.text_style = ctx.compute_text_style();- ctx- }-- fn short_head(&self) -> &str {- &self.head[..8.min(self.head.len())]- }-- fn compute_text_style(&self) -> Option<Style> {- // No special styling for current worktree - gutter symbol (@) and top position- // already communicate it. Only dim removable worktrees.- if self.item.should_dim() {- Some(Style::new().dimmed())+impl ColumnLayout {+ /// Render a text cell with optional style, truncated to column width.+ fn render_text_cell(&self, text: &str, style: Option<Style>) -> StyledLine {+ let mut cell = StyledLine::new();+ if let Some(s) = style {+ cell.push_styled(text.to_string(), s);} else {- None+ cell.push_raw(text.to_string());}+ cell.truncate_to_width(self.width)}-}-impl ColumnLayout {fn render_diff_cell(&self, positive: usize, negative: usize) -> StyledLine {let ColumnFormat::Diff(config) = self.format else {return StyledLine::new();@@ -406,21 +346,25 @@ impl ColumnLayout {fn render_cell(&self,- ctx: &ListRowContext,+ item: &ListItem,status_mask: &PositionMask,main_worktree_path: &Path,max_message_len: usize,) -> StyledLine {+ // Compute derived values inline (avoids separate context struct)+ let worktree_data = item.worktree_data();+ let text_style = item.should_dim().then(|| Style::new().dimmed());+match self.kind {ColumnKind::Gutter => {let mut cell = StyledLine::new();- let symbol = if let Some(data) = ctx.worktree_data {+ let symbol = if let Some(data) = worktree_data {// Priority: @ (current) > ^ (main) > - (previous) > + (regular)- if ctx.is_current {+ if data.is_current {"@ " // Current worktree} else if data.is_main {"^ " // Main worktree- } else if ctx.is_previous {+ } else if data.is_previous {"- " // Previous worktree (wt switch -)} else {"+ " // Regular worktree@@ -432,20 +376,14 @@ impl ColumnLayout {cell}ColumnKind::Branch => {- let mut cell = StyledLine::new();- let text = ctx.item.branch.as_deref().unwrap_or("-");- if let Some(style) = ctx.text_style {- cell.push_styled(text.to_string(), style);- } else {- cell.push_raw(text.to_string());- }- cell.truncate_to_width(self.width)+ let text = item.branch.as_deref().unwrap_or("-");+ self.render_text_cell(text, text_style)}ColumnKind::Status => {let mut cell = StyledLine::new();// Render status symbols (works for both worktrees and branches)- if let Some(ref status_symbols) = ctx.item.status_symbols {+ if let Some(ref status_symbols) = item.status_symbols {cell.push_raw(status_symbols.render_with_mask(status_mask));} else {// Show spinner while status is being computed (both worktrees and branches)@@ -458,19 +396,17 @@ impl ColumnLayout {cell}ColumnKind::WorkingDiff => {- let Some(diff) = ctx- .worktree_data- .and_then(|data| data.working_tree_diff.as_ref())+ let Some(diff) = worktree_data.and_then(|data| data.working_tree_diff.as_ref())else {return StyledLine::new();};self.render_diff_cell(diff.added, diff.deleted)}ColumnKind::AheadBehind => {- if ctx.item.is_main() {+ if item.is_main() {return StyledLine::new();}- match ctx.counts {+ match item.counts {Some(counts) if counts.ahead == 0 && counts.behind == 0 => StyledLine::new(),Some(counts) => self.render_diff_cell(counts.ahead, counts.behind),None => {@@ -484,11 +420,11 @@ impl ColumnLayout {}}ColumnKind::BranchDiff => {- if ctx.item.is_main() {+ if item.is_main() {return StyledLine::new();}- match ctx.branch_diff {- Some(diff) => self.render_diff_cell(diff.added, diff.deleted),+ match item.branch_diff() {+ Some(bd) => self.render_diff_cell(bd.diff.added, bd.diff.deleted),None => {// Task was skipped — show ellipsis to indicate "not computed"let mut cell = StyledLine::new();@@ -500,20 +436,15 @@ impl ColumnLayout {}}ColumnKind::Path => {- let Some(data) = ctx.worktree_data else {+ let Some(data) = worktree_data else {return StyledLine::new();};- let mut cell = StyledLine::new();let path_str = shorten_path(&data.path, main_worktree_path);- if let Some(style) = ctx.text_style {- cell.push_styled(path_str, style);- } else {- cell.push_raw(path_str);- }- cell.truncate_to_width(self.width)+ self.render_text_cell(&path_str, text_style)}ColumnKind::Upstream => {- let Some(active) = ctx.upstream.active() else {+ let upstream = item.upstream();+ let Some(active) = upstream.active() else {return StyledLine::new();};// Show centered | when in sync instead of ⇡0 ⇣0@@ -533,11 +464,11 @@ impl ColumnLayout {let mut cell = StyledLine::new();// Show spinner if commit details haven't loaded yet (for both worktrees and branches)- if ctx.item.commit.is_none() {- cell.push_styled("⋯", Style::new().dimmed());- } else {- let time_str = format_relative_time_short(ctx.commit.timestamp);+ if let Some(ref commit) = item.commit {+ let time_str = format_relative_time_short(commit.timestamp);cell.push_styled(time_str, Style::new().dimmed());+ } else {+ cell.push_styled("⋯", Style::new().dimmed());}cell@@ -548,7 +479,7 @@ impl ColumnLayout {// - When hyperlinks not supported: show full URL// - dim if not available/active// - normal if available and active- match (&ctx.item.url, ctx.item.url_active) {+ match (&item.url, item.url_active) {(None, _) => StyledLine::new(), // No URL configured(Some(url), Some(true)) => {// Active: normal styling@@ -569,7 +500,7 @@ impl ColumnLayout {ColumnKind::CiStatus => {// Check display field first for pending indicators during progressive rendering// (works for both worktrees and branches)- if let Some(ref ci_display) = ctx.item.display.ci_status_display {+ if let Some(ref ci_display) = item.display.ci_status_display {let mut cell = StyledLine::new();// ci_status_display contains pre-formatted ANSI text (either actual status or "⋯")cell.push_raw(ci_display.clone());@@ -580,7 +511,7 @@ impl ColumnLayout {// - None = not loaded yet (show spinner)// - Some(None) = loaded, no CI (show nothing)// - Some(Some(status)) = loaded with CI (show status)- match &ctx.item.pr_status {+ match &item.pr_status {None => {// Not loaded yet - show spinnerlet mut cell = StyledLine::new();@@ -598,19 +529,21 @@ impl ColumnLayout {}}ColumnKind::Commit => {+ let head = item.head();+ let short_head = &head[..8.min(head.len())];let mut cell = StyledLine::new();- cell.push_styled(ctx.short_head().to_string(), Style::new().dimmed());+ cell.push_styled(short_head.to_string(), Style::new().dimmed());cell}ColumnKind::Message => {let mut cell = StyledLine::new();// Show spinner if commit details haven't loaded yet (for both worktrees and branches)- if ctx.item.commit.is_none() {- cell.push_styled("⋯", Style::new().dimmed());- } else {- let msg = truncate_to_width(&ctx.commit.commit_message, max_message_len);+ if let Some(ref commit) = item.commit {+ let msg = truncate_to_width(&commit.commit_message, max_message_len);cell.push_styled(msg, Style::new().dimmed());+ } else {+ cell.push_styled("⋯", Style::new().dimmed());}celldiff --git a/src/commands/select.rs b/src/commands/select.rsindex 47023d627..4727a8f5a 100644--- a/src/commands/select.rs+++ b/src/commands/select.rs@@ -1062,7 +1062,7 @@ pub fn handle_select(let branch_name = item.branch_name().to_string();// Use layout system to render the line - this handles all column alignment- let rendered_line = layout.render_list_item_line(&item, None);+ let rendered_line = layout.render_list_item_line(&item);let display_text_with_ansi = rendered_line.render();let display_text = rendered_line.plain_text();