Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(styling): return Option<usize> from terminal_width() (#3043)
Maximilian Roosddf550a21c2c
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex f04b1a252..d9d8568a0 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -1055,13 +1055,16 @@ pub fn collect(let layout = super::layout::calculate_layout_with_width(&all_items,&effective_skip_tasks,- list_width.unwrap_or_else(crate::display::terminal_width),+ list_width+ .or_else(crate::display::terminal_width)+ .unwrap_or(usize::MAX),&main_worktree.path,url_template.as_deref(),);- // Single-line invariant: use safe width to prevent line wrapping- let max_width = crate::display::terminal_width();+ // Single-line invariant: with no detectable width, an unlimited width+ // keeps rows untruncated rather than wrapping at a guessed width+ let max_width = crate::display::terminal_width().unwrap_or(usize::MAX);// Create collection options from skip set. `integration_targets` is// patched in after the parallel phase below extracts it — at thisdiff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex 102f9e404..5845b8002 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -1344,7 +1344,7 @@ mod tests {let layout = calculate_layout_with_width(&items,&skip_tasks,- terminal_width(),+ terminal_width().expect("COLUMNS=80 is set in .cargo/config.toml"),&main_worktree_path,None,);@@ -1455,7 +1455,7 @@ mod tests {let layout = calculate_layout_with_width(&items,&skip_tasks,- terminal_width(),+ terminal_width().expect("COLUMNS=80 is set in .cargo/config.toml"),&main_worktree_path,None,);diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 78ef8fc5a..f0fc3fa5e 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -177,13 +177,10 @@ pub(crate) fn force_serial_concurrent() -> bool {/// * `repo` - The repository to query/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {- let term_width = crate::display::terminal_width();let mut args = vec!["diff", "--color=always", "--stat"];- // `terminal_width()` returns a `usize::MAX` sentinel when no width is- // detectable (no TTY, no COLUMNS); git mangles a sentinel-sized- // `--stat-width`, so omit the flag and let git use its default width.+ // With no detectable width, omit the flag and let git use its default width.let stat_width_arg;- if term_width != usize::MAX {+ if let Some(term_width) = crate::display::terminal_width() {let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);stat_width_arg = format!("--stat-width={stat_width}");args.push(&stat_width_arg);diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 31908b0c7..be9be1add 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -540,7 +540,9 @@ pub fn handle_picker(// List width depends on the preview position. Right splits the terminal// ~50/50; Down gives the list the full width. Passed to `collect` so// the skeleton layout matches the picker's actual render width.- let terminal_width = crate::display::terminal_width();+ // The picker requires a TTY, so detection essentially always succeeds;+ // the unlimited-width fallback just keeps the math total.+ let terminal_width = crate::display::terminal_width().unwrap_or(usize::MAX);let skim_list_width = match state.initial_layout {PreviewLayout::Right => terminal_width / 2,PreviewLayout::Down => terminal_width,diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 877a610fc..ade6cf08a 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -647,8 +647,9 @@ pub fn run(format: OutputFormat) -> Result<()> {return Ok(());}- // Fit segments to terminal width using priority-based dropping- let max_width = terminal_width_for_statusline();+ // Fit segments to terminal width using priority-based dropping; with no+ // detectable width (even via the parent-TTY walk), render everything+ let max_width = terminal_width_for_statusline().unwrap_or(usize::MAX);// Reserve 1 char for leading space (ellipsis handled by truncate_visible fallback)let content_budget = max_width.saturating_sub(1);let fitted_segments = StatuslineSegment::fit_to_width(segments, content_budget);diff --git a/src/help.rs b/src/help.rsindex bd37fa797..e47084b8c 100644--- a/src/help.rs+++ b/src/help.rs@@ -239,14 +239,9 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::// Render markdown sections (tables, code blocks, prose) with proper wrapping.// Since we disabled clap's wrapping above, our renderer controls all line breaks.- // `terminal_width()` returns a `usize::MAX` sentinel when no- // width is detectable (no TTY, no COLUMNS); map it to `None`- // so the renderer uses its own defaults instead of e.g.- // repeating a rule character `usize::MAX` times.- let width = worktrunk::styling::terminal_width();let help = crate::md_help::render_markdown_in_help_with_width(&clap_output,- (width != usize::MAX).then_some(width),+ worktrunk::styling::terminal_width(),);// show_help_in_pager checks if stdout or stderr is a TTY.diff --git a/src/styling/format.rs b/src/styling/format.rsindex d6ba6ce23..3d6ccb387 100644--- a/src/styling/format.rs+++ b/src/styling/format.rs@@ -113,8 +113,9 @@ pub(super) fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {pub fn format_with_gutter(content: &str, max_width: Option<usize>) -> String {let gutter = super::GUTTER;- // Use provided width or detect terminal width (respects COLUMNS env var)- let term_width = max_width.unwrap_or_else(terminal_width);+ // Use provided width or detect terminal width (respects COLUMNS env var);+ // with no detectable width, wrap nothing+ let term_width = max_width.or_else(terminal_width).unwrap_or(usize::MAX);// Account for gutter (1) + space (1)let available_width = term_width.saturating_sub(2);@@ -278,8 +279,8 @@ fn format_bash_with_gutter_impl(content: &str, width_override: Option<usize>) ->let dim = anstyle::Style::new().dimmed();let string_style = bash_token_style("string").unwrap_or(dim);- // Calculate available width for content- let term_width = width_override.unwrap_or_else(terminal_width);+ // Calculate available width for content; with no detectable width, wrap nothing+ let term_width = width_override.or_else(terminal_width).unwrap_or(usize::MAX);let available_width = term_width.saturating_sub(2);// Set up tree-sitter bash highlightingdiff --git a/src/styling/mod.rs b/src/styling/mod.rsindex 1004bdf9d..91d831a6a 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -63,53 +63,42 @@ pub fn verbosity() -> u8 {VERBOSITY.load(Ordering::Relaxed)}-/// Get terminal width, or `usize::MAX` if detection fails.+/// Get terminal width, or `None` if detection fails (piped context, no TTY).////// Prefers direct terminal size detection over COLUMNS environment variable,/// because tools like cargo may set COLUMNS incorrectly.////// Checks stderr first (for status messages), then stdout (for table output).///-/// When detection fails (piped context, no TTY), returns `usize::MAX` rather than-/// an arbitrary default. Callers that need width-based formatting will produce-/// full output, letting the consumer handle truncation.-////// Does **not** probe the parent process tree — that fallback is expensive/// (spawns `ps` up to 10 times plus `stty`) and only useful for `wt statusline`/// under Claude Code, where no TTY is inherited. Statusline calls/// [`terminal_width_for_statusline`] instead.-pub fn terminal_width() -> usize {+pub fn terminal_width() -> Option<usize> {// Prefer direct terminal detection (more accurate than COLUMNS which may be stale/wrong)// Check stderr first (status messages), then stdout (table output)if let Some((terminal_size::Width(w), _)) =terminal_size::terminal_size_of(std::io::stderr()).or_else(terminal_size::terminal_size){- return w as usize;+ return Some(w as usize);}// Fall back to COLUMNS env var (for scripts, piped contexts, or when detection fails)- if let Ok(cols) = std::env::var("COLUMNS")- && let Ok(width) = cols.parse::<usize>()- {- return width;- }-- // Can't detect width — don't truncate, let the consumer handle it- usize::MAX+ std::env::var("COLUMNS").ok()?.parse::<usize>().ok()}/// Terminal width for `wt statusline`, including a subprocess-compat fallback.////// Claude Code invokes `wt statusline` as a subprocess with pipes for stdin,-/// stdout, and stderr — so [`terminal_width`] always falls through to its-/// `usize::MAX` sentinel, and the statusline output would overflow the bar.+/// stdout, and stderr — so [`terminal_width`] always returns `None`, and the+/// statusline output would overflow the bar./// As a last resort, this walks up to 10 parent processes looking for a TTY/// and asks `stty size` for its dimensions, reserving 5 columns for Claude/// Code's own UI messages.////// Every other caller should use [`terminal_width`] — the parent-TTY walk is/// a statusline-specific workaround, not a general fallback.-pub fn terminal_width_for_statusline() -> usize {+pub fn terminal_width_for_statusline() -> Option<usize> {statusline_width_fallback(terminal_width())}@@ -117,12 +106,10 @@ pub fn terminal_width_for_statusline() -> usize {////// Split from [`terminal_width_for_statusline`] so tests can exercise the/// fallback path without racing the process-wide `COLUMNS` env var.-fn statusline_width_fallback(base: usize) -> usize {+fn statusline_width_fallback(base: Option<usize>) -> Option<usize> {#[cfg(unix)]- if base == usize::MAX- && let Some(width) = detect_parent_tty_width()- {- return width;+ if base.is_none() {+ return detect_parent_tty_width();}base}@@ -213,24 +200,24 @@ mod tests {#[test]fn statusline_width_fallback_returns_base_when_known() {// Fast path: if `terminal_width()` found a real width, use it as-is.- assert_eq!(statusline_width_fallback(80), 80);- assert_eq!(statusline_width_fallback(1), 1);+ assert_eq!(statusline_width_fallback(Some(80)), Some(80));+ assert_eq!(statusline_width_fallback(Some(1)), Some(1));}#[test]fn statusline_width_fallback_probes_parent_tty_when_unknown() {- // Slow path: `usize::MAX` signals "direct detection failed" — the- // helper then walks the process tree. Whether a TTY is found depends- // on the test environment, so only assert the return type.- let _ = statusline_width_fallback(usize::MAX);+ // Slow path: `None` signals "direct detection failed" — the helper+ // then walks the process tree. Whether a TTY is found depends on the+ // test environment, so only assert the return type.+ let _ = statusline_width_fallback(None);}#[test]fn terminal_width_for_statusline_returns_a_width() {// End-to-end smoke test. Under cargo test, `COLUMNS=80` is set in- // `.cargo/config.toml`, so the fast path returns 80.+ // `.cargo/config.toml`, so the fast path always finds a width.let width = terminal_width_for_statusline();- assert!(width > 0);+ assert!(width.expect("COLUMNS=80 is set in .cargo/config.toml") > 0);}#[cfg(unix)]diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rsindex b2621d2b3..01eb6a117 100644--- a/tests/integration_tests/help.rs+++ b/tests/integration_tests/help.rs@@ -228,10 +228,9 @@ fn test_help_list_narrow_terminal() {}/// With no detectable width (piped output, no COLUMNS), `terminal_width()`-/// returns its `usize::MAX` "don't truncate" sentinel. Help rendering must-/// map that to "no width" rather than treating it as a real width —-/// `wt list --help` used to panic with a capacity overflow trying to render-/// a `---` rule `usize::MAX` characters wide.+/// returns `None` and the markdown renderer falls back to its own defaults.+/// Back when "no width" was a `usize::MAX` sentinel, `wt list --help` panicked+/// with a capacity overflow trying to render a `---` rule that wide.#[test]fn test_help_without_detectable_width() {let mut cmd = wt_command();diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rsindex d15d71d7b..8aa3e5e3c 100644--- a/tests/integration_tests/push.rs+++ b/tests/integration_tests/push.rs@@ -31,8 +31,9 @@ fn test_push_fast_forward(mut repo: TestRepo) {}/// With no detectable width (piped output, no COLUMNS), the diffstat omits-/// `--stat-width` instead of passing `terminal_width()`'s `usize::MAX`-/// sentinel to git, which used to make git truncate filenames to ~10 chars.+/// `--stat-width` and lets git pick its default. Back when "no width" was a+/// `usize::MAX` sentinel, it reached git as a real `--stat-width` and made+/// git truncate filenames to ~10 chars.#[rstest]fn test_push_diffstat_without_detectable_width(mut repo: TestRepo) {repo.add_main_worktree();