Skip to content

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

feat: improve command execution and documentation

Maximilian Roos411861b9e842
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index aac97659f..94566ef81 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -7,9 +7,12 @@
//!
//! ## Unified Collection Architecture
//!
-//! Both progressive (with progress bars) and buffered (silent) modes use the same
-//! `collect_internal()` function. The only difference is whether progress bars are
-//! created and shown. This ensures a single canonical collection implementation.
+//! Progressive and buffered modes use the same collection and rendering code.
+//! The only difference is whether intermediate updates are shown during collection:
+//! - Progressive: shows progress bars with updates, then finalizes in place (TTY) or redraws (non-TTY)
+//! - Buffered: collects silently, then renders the final table
+//!
+//! Both modes render the final table in `collect()`, ensuring a single canonical rendering path.
//!
//! **Parallelism at two levels**:
//! - Across worktrees: Multiple worktrees collected concurrently via Rayon
@@ -373,7 +376,9 @@ fn get_branches_without_worktrees(
/// Collect worktree data with optional progressive rendering.
///
/// When `show_progress` is true, renders a skeleton immediately and updates as data arrives.
-/// When false, silently collects all data and returns it for external rendering.
+/// When false, behavior depends on `render_table`:
+/// - If `render_table` is true: renders final table (buffered mode)
+/// - If `render_table` is false: returns data without rendering (JSON mode)
pub fn collect(
repo: &Repository,
show_branches: bool,
@@ -381,6 +386,7 @@ pub fn collect(
fetch_ci: bool,
check_conflicts: bool,
show_progress: bool,
+ render_table: bool,
) -> Result<Option<super::model::ListData>, GitError> {
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::time::Duration;
@@ -708,15 +714,37 @@ pub fn collect(
})?;
}
} else {
+ // Buffered mode (no progress bars shown)
for pb in progress_bars {
pb.finish();
}
+
+ // Render final table if requested (table format), otherwise just return data (JSON format)
+ if render_table {
+ // Build final summary string
+ let final_msg = super::format_summary_message(
+ &all_items,
+ show_branches,
+ layout.hidden_nonempty_count,
+ );
+
+ // Render complete table
+ crate::output::raw_terminal(layout.format_header_line())?;
+ for item in &all_items {
+ crate::output::raw_terminal(
+ layout.format_list_item_line(item, current_worktree_path.as_ref()),
+ )?;
+ }
+ // Blank line + summary
+ crate::output::raw_terminal("")?;
+ crate::output::raw_terminal(final_msg)?;
+ }
}
// Status symbols are now computed during data collection (both modes), no fallback needed
- // 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
+ // Compute display fields for all items (used by JSON output)
+ // Table rendering uses raw data directly; these fields provide pre-formatted strings for JSON
for info in &mut all_items {
info.display = super::model::DisplayFields::from_common_fields(
&info.counts,
@@ -736,15 +764,13 @@ pub fn collect(
// all_items now contains both worktrees and branches (if requested)
let items = all_items;
- // Progressive mode: table already rendered via progress bars (finished in place for TTY,
- // or explicitly printed to stderr for non-TTY in the finalization code above)
- // Buffered mode: table will be rendered in mod.rs
- // Both modes: summary will be rendered in mod.rs
+ // Table rendering complete (when render_table=true):
+ // - Progressive + TTY: rows morphed in place, footer became summary
+ // - Progressive + Non-TTY: cleared progress bars, rendered final table
+ // - Buffered: rendered final table (no progress bars)
+ // JSON mode (render_table=false): no rendering, data returned for serialization
- Ok(Some(super::model::ListData {
- items,
- current_worktree_path,
- }))
+ Ok(Some(super::model::ListData { items }))
}
/// Sort worktrees for display (primary first, then current, then by timestamp descending).
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 91d46bcd5..61b91f72f 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -174,10 +174,7 @@ use std::path::{Path, PathBuf};
use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{ADDITION, DELETION};
-use super::{
- columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, DiffVariant},
- model::ListItem,
-};
+use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, DiffVariant};
/// Width of short commit hash display (first 8 hex characters)
const COMMIT_HASH_WIDTH: usize = 8;
@@ -512,8 +509,8 @@ fn build_estimated_widths(max_branch: usize, show_full: bool, fetch_ci: bool) ->
/// Allocate columns using priority-based allocation logic.
///
-/// This is the core allocation algorithm used by both `calculate_responsive_layout()`
-/// and `calculate_layout_from_basics()`. Both now use the same pre-allocated width estimates.
+/// This is the core allocation algorithm used by `calculate_layout_from_basics()`
+/// with pre-allocated width estimates for expensive-to-compute columns.
fn allocate_columns_with_priority(
metadata: &LayoutMetadata,
show_full: bool,
@@ -661,56 +658,6 @@ fn allocate_columns_with_priority(
}
}
-/// Calculate responsive layout based on terminal width
-pub fn calculate_responsive_layout(
- items: &[ListItem],
- show_full: bool,
- fetch_ci: bool,
-) -> LayoutConfig {
- let terminal_width = get_safe_list_width();
- let paths: Vec<&Path> = items
- .iter()
- .filter_map(|item| item.worktree_path().map(|path| path.as_path()))
- .collect();
- let common_prefix = find_common_prefix(&paths);
-
- // Calculate max branch width from actual data
- let max_branch = items
- .iter()
- .map(|item| item.branch_name().width())
- .max()
- .unwrap_or(0);
- let max_branch = fit_header(HEADER_BRANCH, max_branch);
-
- // Build pre-allocated width estimates (same as progressive mode)
- let metadata = build_estimated_widths(max_branch, show_full, fetch_ci);
-
- // Calculate actual maximum path width (after common prefix removal)
- let path_data_width = items
- .iter()
- .filter_map(|item| item.worktree_path())
- .map(|path| {
- use crate::display::shorten_path;
- use unicode_width::UnicodeWidthStr;
- shorten_path(path.as_path(), &common_prefix).width()
- })
- .max()
- .unwrap_or(0);
- let max_path_width = fit_header(HEADER_PATH, path_data_width);
-
- let commit_width = fit_header(HEADER_COMMIT, COMMIT_HASH_WIDTH);
-
- allocate_columns_with_priority(
- &metadata,
- show_full,
- fetch_ci,
- max_path_width,
- commit_width,
- terminal_width,
- common_prefix,
- )
-}
-
/// Calculate responsive layout from basic worktree info.
///
/// Uses pre-allocated width estimates for expensive-to-compute columns (status, diffs, time, CI).
@@ -860,12 +807,12 @@ mod tests {
#[test]
fn test_visible_columns_follow_gap_rule() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
- UpstreamStatus, WorktreeData,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, ListItem,
+ StatusSymbols, UpstreamStatus, WorktreeData,
};
// Create test data with specific widths to verify position calculation
- let item = super::ListItem {
+ let item = ListItem {
head: "abc12345".to_string(),
branch: Some("feature".to_string()),
commit: Some(CommitDetails {
@@ -902,7 +849,7 @@ mod tests {
};
let items = vec![item];
- let layout = calculate_responsive_layout(&items, false, false);
+ let layout = calculate_layout_from_basics(&items, false, false);
assert!(
!layout.columns.is_empty(),
@@ -939,12 +886,12 @@ mod tests {
#[test]
fn test_column_positions_with_empty_columns() {
use crate::commands::list::model::{
- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, StatusSymbols,
- UpstreamStatus, WorktreeData,
+ AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, ItemKind, ListItem,
+ StatusSymbols, UpstreamStatus, WorktreeData,
};
// Create minimal data - most columns will be empty
- let item = super::ListItem {
+ let item = ListItem {
head: "abc12345".to_string(),
branch: Some("main".to_string()),
commit: Some(CommitDetails {
@@ -981,7 +928,7 @@ mod tests {
};
let items = vec![item];
- let layout = calculate_responsive_layout(&items, false, false);
+ let layout = calculate_layout_from_basics(&items, false, false);
assert!(
layout
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 5c37f8405..f7b3f18a8 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -86,7 +86,7 @@ mod render;
#[cfg(test)]
mod spacing_test;
-use layout::{LayoutConfig, calculate_responsive_layout};
+// Layout is calculated in collect.rs
use model::{ListData, ListItem};
use progressive::RenderMode;
use worktrunk::git::{GitError, Repository};
@@ -108,6 +108,9 @@ pub fn handle_list(
crate::OutputFormat::Json => false, // JSON never shows progress
};
+ // Render table in collect() for all table modes (progressive + buffered)
+ let render_table = matches!(format, crate::OutputFormat::Table);
+
let list_data = collect::collect(
&repo,
show_branches,
@@ -115,13 +118,10 @@ pub fn handle_list(
fetch_ci,
check_conflicts,
show_progress,
+ render_table,
)?;
- let Some(ListData {
- items,
- current_worktree_path,
- }) = list_data
- else {
+ let Some(ListData { items }) = list_data else {
return Ok(());
};
@@ -134,25 +134,8 @@ pub fn handle_list(
crate::output::raw(json)?;
}
crate::OutputFormat::Table => {
- let layout = calculate_responsive_layout(&items, show_full, fetch_ci);
-
- // Progressive mode renders table during collection; buffered mode renders here
- if !show_progress {
- crate::output::raw_terminal(layout.format_header_line())?;
- for item in &items {
- crate::output::raw_terminal(
- layout.format_list_item_line(item, current_worktree_path.as_ref()),
- )?;
- }
- }
-
- // Summary:
- // - progressive + TTY: already shown via footer.finish_with_message
- // - progressive + non-TTY: already shown via multi.suspend() in collect.rs
- // - buffered: render here
- if !show_progress {
- layout.render_summary(&items, show_branches)?;
- }
+ // Table and summary already rendered in collect() for all modes
+ // Nothing to do here - collect() handles the complete table rendering
}
}
@@ -251,31 +234,3 @@ pub(crate) fn format_summary_message(
.join(", ");
format!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}")
}
-
-impl LayoutConfig {
- fn render_summary(&self, items: &[ListItem], include_branches: bool) -> Result<(), GitError> {
- use worktrunk::styling::{HINT, INFO_EMOJI};
-
- if items.is_empty() {
- crate::output::raw_terminal("")?;
- crate::output::hint(format!("{HINT}No worktrees found{HINT:#}"))?;
- crate::output::hint(format!(
- "{HINT}Create one with: wt switch --create <branch>{HINT:#}"
- ))?;
- return Ok(());
- }
-
- let metrics = SummaryMetrics::from_items(items);
-
- use anstyle::Style;
- let dim = Style::new().dimmed();
-
- let summary = metrics
- .summary_parts(include_branches, self.hidden_nonempty_count)
- .join(", ");
-
- crate::output::raw_terminal("")?;
- crate::output::raw_terminal(format!("{INFO_EMOJI} {dim}Showing {summary}{dim:#}"))?;
- Ok(())
- }
-}
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index eb94b63b3..d5a065919 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -205,7 +205,6 @@ pub struct ListItem {
pub struct ListData {
pub items: Vec<ListItem>,
- pub current_worktree_path: Option<PathBuf>,
}
impl ListItem {
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 5b0009ab0..0e9edded7 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -255,6 +255,7 @@ pub fn handle_select() -> Result<(), GitError> {
false, // fetch_ci (no CI with select command)
false, // check_conflicts (no conflict checking with select command)
false, // show_progress (no progress bars)
+ false, // render_table (select renders its own UI)
)?
else {
return Ok(());
diff --git a/tests/snapshots/integration__integration_tests__list__detached_head.snap b/tests/snapshots/integration__integration_tests__list__detached_head.snap
index ac1895f62..f75546d3f 100644
--- a/tests/snapshots/integration__integration_tests__list__detached_head.snap
+++ b/tests/snapshots/integration__integration_tests__list__detached_head.snap
@@ -15,14 +15,14 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmplX4XgD/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpKtHzGI/test-config.toml
---
success: true
exit_code: 0
----- stdout -----
----- stderr -----
-Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
-(detached) . b834638e 10 months ago Initial commit
+Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+(detached) . b834638e 10 months ago Initial commit
⚪ Showing 1 worktree