Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Use `ansi-str` for robust ANSI code handling
Maximilian Roosc74d9277dd48
diff --git a/Cargo.lock b/Cargo.lockindex 911bb2b22..770c4094b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2186,15 +2186,6 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f42444fea5b87a39db4218d9422087e66a85d0e7a0963a439b07bcdf91804006"-[[package]]-name = "strip-ansi-escapes"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025"-dependencies = [- "vte 0.14.1",-]-[[package]]name = "strsim"version = "0.11.1"@@ -3072,7 +3063,6 @@ dependencies = ["shell-escape","shellexpand","skim",- "strip-ansi-escapes","strum","synoptic","tempfile",diff --git a/Cargo.toml b/Cargo.tomlindex 0fe5c6483..9ea5eb079 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -57,7 +57,6 @@ serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"shell-escape = "0.1"shellexpand = "3.1"-strip-ansi-escapes = "0.2"strum = { version = "0.27", features = ["derive"] }synoptic = "2"terminal_size = "0.4"diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex 694515e7c..872e3f435 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -525,13 +525,8 @@ pub fn collect(let max_width = super::layout::get_safe_list_width();// Clamp helper to keep progress output single-line in narrow terminals.- let clamp = |s: &str| -> String {- if crate::display::visible_width(s) > max_width {- crate::display::truncate_visible(s, max_width, "…")- } else {- s.to_owned()- }- };+ // truncate_visible already returns early if no truncation needed, avoiding redundant work.+ let clamp = |s: &str| -> String { crate::display::truncate_visible(s, max_width, "…") };// Create MultiProgress with explicit draw target and cursor mode// Use stderr for progress bars so they don't interfere with stdout directivesdiff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 0adfd92c9..605962a5c 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -565,13 +565,13 @@ impl ColumnLayout {}ColumnKind::Branch => {let mut cell = StyledLine::new();- let text = ctx.item.branch.as_deref().unwrap_or("(detached)");+ 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+ cell.truncate_to_width(self.width)}ColumnKind::Status => {let mut cell = StyledLine::new();@@ -584,12 +584,12 @@ impl ColumnLayout {cell.push_styled("⋯", Style::new().dimmed());}- // Pad to column width+ // Truncate if exceeds column width, then pad+ let mut cell = cell.truncate_to_width(self.width);let status_width = cell.width();if status_width < self.width {cell.push_raw(" ".repeat(self.width - status_width));}-cell}ColumnKind::WorkingDiff => {@@ -629,7 +629,7 @@ impl ColumnLayout {} else {cell.push_raw(path_str);}- cell+ cell.truncate_to_width(self.width)}ColumnKind::Upstream => {let Some((_, ahead, behind)) = ctx.upstream.active() else {@@ -837,7 +837,7 @@ mod tests {let rendered = result.render();// Strip ANSI codes to check alignment- let clean = strip_ansi_escapes::strip_str(&rendered);+ let clean = worktrunk::styling::strip_ansi_codes(&rendered);// Should be " +1 -1" (with leading space for right-alignment)assert_eq!(clean, " +1 -1", "Diff should be right-aligned");@@ -876,7 +876,7 @@ mod tests {// The rendered output should have correct spacinglet rendered = line.render();- let clean = strip_ansi_escapes::strip_str(&rendered);+ let clean = worktrunk::styling::strip_ansi_codes(&rendered);assert_eq!(clean.width(),24,@@ -1052,7 +1052,7 @@ mod tests {);assert_eq!(without.width(), total);let rendered_without = without.render();- let clean_without = strip_ansi_escapes::strip_str(&rendered_without);+ let clean_without = worktrunk::styling::strip_ansi_codes(&rendered_without);assert_eq!(clean_without, " ", "Should render as blank");// With always_show_zeros=true, (0, 0) renders as "↑0 ↓0"@@ -1073,7 +1073,7 @@ mod tests {);assert_eq!(with.width(), total);let rendered_with = with.render();- let clean_with = strip_ansi_escapes::strip_str(&rendered_with);+ let clean_with = worktrunk::styling::strip_ansi_codes(&rendered_with);assert_eq!(clean_with, " ↑0 ↓0","Should render ↑0 ↓0 with padding (right-aligned)"@@ -1166,7 +1166,7 @@ mod tests {},);let rendered1 = result1.render();- let clean1 = strip_ansi_escapes::strip_str(&rendered1);+ let clean1 = worktrunk::styling::strip_ansi_codes(&rendered1);assert_eq!(clean1, " +53 -7", "Should be ' +53 -7'");// Test case 2: (33, 23) - both medium@@ -1186,7 +1186,7 @@ mod tests {},);let rendered2 = result2.render();- let clean2 = strip_ansi_escapes::strip_str(&rendered2);+ let clean2 = worktrunk::styling::strip_ansi_codes(&rendered2);assert_eq!(clean2, " +33 -23", "Should be ' +33 -23'");// Test case 3: (2, 2) - both small (needs padding)@@ -1206,7 +1206,7 @@ mod tests {},);let rendered3 = result3.render();- let clean3 = strip_ansi_escapes::strip_str(&rendered3);+ let clean3 = worktrunk::styling::strip_ansi_codes(&rendered3);assert_eq!(clean3, " +2 -2", "Should be ' +2 -2'");// Verify vertical alignment: the ones digits should be in the same columndiff --git a/src/display.rs b/src/display.rsindex f2ab2a2ce..79b51d13d 100644--- a/src/display.rs+++ b/src/display.rs@@ -6,10 +6,8 @@//! - Text truncation with word boundaries//! - Terminal width detection-use ansi_str::AnsiStr;use std::path::{Path, PathBuf};use std::time::{SystemTime, UNIX_EPOCH};-use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};use worktrunk::path::format_path_for_display;pub fn format_relative_time(timestamp: i64) -> String {@@ -120,10 +118,10 @@ pub fn truncate_at_word_boundary(text: &str, max_width: usize) -> String {// Use last space if found, otherwise truncate at last character that fitslet truncate_at = last_space_idx.unwrap_or(last_idx);- // Truncate decisively and add ellipsis marker- // Note: Can produce "...…" if original text has ellipsis at truncation point,- // but this is rare and acceptable - we're making a clear truncation decision.- format!("{}…", &text[..truncate_at])+ // Truncate and trim trailing whitespace before adding ellipsis+ // This prevents "text …" with space before ellipsis+ let truncated = text[..truncate_at].trim_end();+ format!("{}…", truncated)}/// Get terminal width, defaulting to 80 if detection fails@@ -141,50 +139,8 @@ pub fn get_terminal_width() -> usize {.unwrap_or(80)}-/// Compute visible width of a styled string by stripping ANSI/OSC first.-pub fn visible_width(rendered: &str) -> usize {- UnicodeWidthStr::width(rendered.ansi_strip().as_ref())-}--/// Truncate a styled string to a visible width budget, preserving escapes.-/// Escape sequences (ANSI/OSC) are zero-width; ellipsis is added when truncating.-/// Appends ESC[0m on truncation to avoid style bleed.-pub fn truncate_visible(rendered: &str, max_width: usize, ellipsis: &str) -> String {- if max_width == 0 {- return String::new();- }-- let plain = rendered.ansi_strip();- let plain_str = plain.as_ref();- if UnicodeWidthStr::width(plain_str) <= max_width {- return rendered.to_owned();- }-- let ellipsis_width = UnicodeWidthStr::width(ellipsis);- let budget = max_width.saturating_sub(ellipsis_width);- if budget == 0 {- let mut out = String::new();- out.push_str(ellipsis);- out.push_str("\u{1b}[0m");- return out;- }-- let mut cut_at = 0;- let mut width = 0;- for (i, ch) in plain_str.char_indices() {- let w = UnicodeWidthChar::width(ch).unwrap_or(0);- if width + w > budget {- break;- }- width += w;- cut_at = i + ch.len_utf8();- }-- let mut out = rendered.ansi_cut(..cut_at).into_owned();- out.push_str(ellipsis);- out.push_str("\u{1b}[0m");- out-}+// Re-export truncate_visible from styling for convenience+pub use worktrunk::styling::truncate_visible;#[cfg(test)]mod tests {@@ -268,26 +224,4 @@ mod tests {assert!(result.width() <= 20, "Width should be <= 20");assert!(result.ends_with('…'), "Should end with ellipsis");}-- #[test]- fn visible_width_strips_osc8() {- let s = "\u{1b}]8;;https://example.com\u{1b}\\A\u{1b}]8;;\u{1b}\\";- assert_eq!(visible_width(s), 1, "OSC-8 should be zero-width");- }-- #[test]- fn truncate_visible_preserves_budget_and_resets() {- let colored = "\u{1b}[31mhello\u{1b}[0m";- let out = truncate_visible(colored, 3, "…");- assert_eq!(visible_width(&out), 3);- assert!(out.ends_with("\u{1b}[0m"));- }-- #[test]- fn truncate_visible_handles_wide_emoji() {- let rocket = "🚀";- let out = truncate_visible(rocket, 1, "…");- assert_eq!(visible_width(&out), 1);- assert!(out.ends_with("\u{1b}[0m"));- }}diff --git a/src/styling/format.rs b/src/styling/format.rsindex b6895cb62..deeab7087 100644--- a/src/styling/format.rs+++ b/src/styling/format.rs@@ -2,6 +2,7 @@//!//! Provides functions for formatting commands and configuration with visual gutters.+use ansi_str::AnsiStr;use anstyle::{AnsiColor, Color, Style};use unicode_width::UnicodeWidthStr;@@ -23,9 +24,9 @@ const DEFAULT_TERMINAL_WIDTH: usize = 80;/// so the final output (content + gutter) fits within the terminal width.pub const GUTTER_OVERHEAD: usize = 3;-/// Strip ANSI escape codes from a string using strip-ansi-escapes+/// Strip ANSI escape codes from a stringpub fn strip_ansi_codes(s: &str) -> String {- strip_ansi_escapes::strip_str(s)+ s.ansi_strip().into_owned()}/// Calculate visual width of a string, ignoring ANSI escape codesdiff --git a/src/styling/line.rs b/src/styling/line.rsindex e520531ed..5590defd1 100644--- a/src/styling/line.rs+++ b/src/styling/line.rs@@ -2,12 +2,48 @@//!//! Provides types for building complex styled output with proper width calculation.+use ansi_str::AnsiStr;use anstyle::Style;-use unicode_width::UnicodeWidthStr;+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};-/// Strip ANSI escape codes (SGR and OSC) to get visual text for width calculation-fn strip_ansi_codes(text: &str) -> String {- String::from_utf8_lossy(&strip_ansi_escapes::strip(text)).to_string()+/// Truncate a styled string to a visible width budget, preserving escapes.+/// Escape sequences (ANSI/OSC) are zero-width; ellipsis is added when truncating.+/// Appends ESC[0m on truncation to avoid style bleed.+pub fn truncate_visible(rendered: &str, max_width: usize, ellipsis: &str) -> String {+ if max_width == 0 {+ return String::new();+ }++ let plain = rendered.ansi_strip();+ let plain_str = plain.as_ref();+ if UnicodeWidthStr::width(plain_str) <= max_width {+ return rendered.to_owned();+ }++ let ellipsis_width = UnicodeWidthStr::width(ellipsis);+ let budget = max_width.saturating_sub(ellipsis_width);+ if budget == 0 {+ let mut out = String::new();+ out.push_str(ellipsis);+ out.push_str("\u{1b}[0m");+ return out;+ }++ let mut cut_at = 0;+ let mut width = 0;+ for (i, ch) in plain_str.char_indices() {+ let w = UnicodeWidthChar::width(ch).unwrap_or(0);+ if width + w > budget {+ break;+ }+ width += w;+ cut_at = i + ch.len_utf8();+ }++ let mut out = rendered.ansi_cut(..cut_at).into_owned();+ out.push_str(ellipsis);+ out.push_str("\u{1b}[0m");+ out}/// A piece of text with an optional style@@ -35,8 +71,7 @@ impl StyledString {/// Returns the visual width (unicode-aware, ANSI codes stripped)pub fn width(&self) -> usize {- let clean_text = strip_ansi_codes(&self.text);- clean_text.width()+ self.text.ansi_strip().width()}/// Renders to a string with ANSI escape codes@@ -97,6 +132,19 @@ impl StyledLine {pub fn render(&self) -> String {self.segments.iter().map(|s| s.render()).collect()}++ /// Truncate if the line exceeds the given width, preserving ANSI codes.+ /// Returns a new StyledLine with truncated content and ellipsis.+ pub fn truncate_to_width(self, max_width: usize) -> StyledLine {+ if self.width() <= max_width {+ return self;+ }+ let rendered = self.render();+ let truncated = truncate_visible(&rendered, max_width, "…");+ let mut new_line = StyledLine::new();+ new_line.push_raw(truncated);+ new_line+ }}#[cfg(test)]@@ -163,4 +211,31 @@ mod tests {styled_str.width());}++ /// Helper to compute visible width for tests+ fn visible_width(rendered: &str) -> usize {+ UnicodeWidthStr::width(rendered.ansi_strip().as_ref())+ }++ #[test]+ fn test_visible_width_strips_osc8() {+ let s = "\u{1b}]8;;https://example.com\u{1b}\\A\u{1b}]8;;\u{1b}\\";+ assert_eq!(visible_width(s), 1, "OSC-8 should be zero-width");+ }++ #[test]+ fn test_truncate_visible_preserves_budget_and_resets() {+ let colored = "\u{1b}[31mhello\u{1b}[0m";+ let out = truncate_visible(colored, 3, "…");+ assert_eq!(visible_width(&out), 3);+ assert!(out.ends_with("\u{1b}[0m"));+ }++ #[test]+ fn test_truncate_visible_handles_wide_emoji() {+ let rocket = "🚀";+ let out = truncate_visible(rocket, 1, "…");+ assert_eq!(visible_width(&out), 1);+ assert!(out.ends_with("\u{1b}[0m"));+ }}diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex ff57c239b..31e9ed9a9 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -28,7 +28,7 @@ pub use anstyle::Style as AnstyleStyle;pub use constants::*;pub use format::{GUTTER_OVERHEAD, format_bash_with_gutter, format_with_gutter, strip_ansi_codes};pub use highlighting::format_toml;-pub use line::{StyledLine, StyledString};+pub use line::{StyledLine, StyledString, truncate_visible};/// Wrap text with an OSC 8 hyperlink///diff --git a/tests/integration_tests/column_alignment_verification.rs b/tests/integration_tests/column_alignment_verification.rsindex 2c14ddfea..46758b31e 100644--- a/tests/integration_tests/column_alignment_verification.rs+++ b/tests/integration_tests/column_alignment_verification.rs@@ -13,11 +13,7 @@use crate::common::{TestRepo, wt_command};use unicode_width::UnicodeWidthStr;--/// Strip ANSI escape codes from a string-fn strip_ansi_codes(s: &str) -> String {- strip_ansi_escapes::strip_str(s)-}+use worktrunk::styling::strip_ansi_codes;/// Represents the start position of each column in a table row#[derive(Debug, Clone)]diff --git a/tests/integration_tests/list_pty.rs b/tests/integration_tests/list_pty.rsindex 4eaa508b5..0c2fd9a05 100644--- a/tests/integration_tests/list_pty.rs+++ b/tests/integration_tests/list_pty.rs@@ -114,7 +114,7 @@ fn exec_wt_list_in_pty(/// Normalize PTY output for snapshot testingfn normalize_pty_output(output: &str) -> String {// Strip ANSI codes for easier snapshot reading- let output = strip_ansi_escapes::strip_str(output);+ let output = worktrunk::styling::strip_ansi_codes(output);// Normalize line endingsoutput.replace("\r\n", "\n").replace('\r', "\n")diff --git a/tests/snapshots/integration__integration_tests__list__detached_head.snap b/tests/snapshots/integration__integration_tests__list__detached_head.snapindex b537c93fd..5843523cb 100644--- a/tests/snapshots/integration__integration_tests__list__detached_head.snap+++ b/tests/snapshots/integration__integration_tests__list__detached_head.snap@@ -26,6 +26,6 @@ exit_code: 0----- stderr -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage[0m-@ [1m[35m(detached)[0m [1m[35m.[0m [2mb834638e[0m [2m10 months ago[0m [2mInitial commit[0m+@ [1m[35m-[0m [1m[35m.[0m [2mb834638e[0m [2m10 months ago[0m [2mInitial commit[0m⚪ [2mShowing 1 worktree[0mdiff --git a/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap b/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snapindex aa5a02468..22d19223d 100644--- a/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap+++ b/tests/snapshots/integration__integration_tests__list__task_dag_detached_head.snap@@ -27,6 +27,6 @@ exit_code: 0----- stderr -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage[0m-@ [1m[35m(detached)[0m [1m[35m.[0m [2mb834638e[0m [2m10 months ago[0m [2mInitial commit[0m+@ [1m[35m-[0m [1m[35m.[0m [2mb834638e[0m [2m10 months ago[0m [2mInitial commit[0m⚪ [2mShowing 1 worktree[0m