Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Migrate to ansi-str crate for ANSI handling
Maximilian Roosea6af0345b32
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 53247fc8d..a3a17ec83 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -89,11 +89,12 @@ impl PrStatus {let (indicator, style) = self.indicator_and_style();if let Some(ref url) = self.url {- use worktrunk::styling::hyperlink;let styled_indicator = format!(- "{}{}{}",+ "{}{}{}{}{}",style,- hyperlink(indicator, url),+ osc8::Hyperlink::new(url),+ indicator,+ osc8::Hyperlink::END,style.render_reset());segment.push_raw(styled_indicator);@@ -694,6 +695,7 @@ impl ColumnLayout {mod tests {use super::*;use crate::commands::list::layout::DiffDisplayConfig;+ use ansi_str::AnsiStr;use worktrunk::styling::{ADDITION, DELETION, StyledLine};fn format_diff_like_column(@@ -822,7 +824,7 @@ mod tests {let rendered = result.render();// Strip ANSI codes to check alignment- let clean = worktrunk::styling::strip_ansi_codes(&rendered);+ let clean = rendered.ansi_strip().into_owned();// Should be " +1 -1" (with leading space for right-alignment)assert_eq!(clean, " +1 -1", "Diff should be right-aligned");@@ -861,7 +863,7 @@ mod tests {// The rendered output should have correct spacinglet rendered = line.render();- let clean = worktrunk::styling::strip_ansi_codes(&rendered);+ let clean = rendered.ansi_strip().into_owned();assert_eq!(clean.width(),24,@@ -1031,7 +1033,7 @@ mod tests {);assert_eq!(without.width(), total);let rendered_without = without.render();- let clean_without = worktrunk::styling::strip_ansi_codes(&rendered_without);+ let clean_without = rendered_without.ansi_strip().into_owned();assert_eq!(clean_without, " ", "Should render as blank");// With always_show_zeros=true, (0, 0) renders as "↑0 ↓0"@@ -1052,7 +1054,7 @@ mod tests {);assert_eq!(with.width(), total);let rendered_with = with.render();- let clean_with = worktrunk::styling::strip_ansi_codes(&rendered_with);+ let clean_with = rendered_with.ansi_strip().into_owned();assert_eq!(clean_with, " ↑0 ↓0","Should render ↑0 ↓0 with padding (right-aligned)"@@ -1145,7 +1147,7 @@ mod tests {},);let rendered1 = result1.render();- let clean1 = worktrunk::styling::strip_ansi_codes(&rendered1);+ let clean1 = rendered1.ansi_strip().into_owned();assert_eq!(clean1, " +53 -7", "Should be ' +53 -7'");// Test case 2: (33, 23) - both medium@@ -1165,7 +1167,7 @@ mod tests {},);let rendered2 = result2.render();- let clean2 = worktrunk::styling::strip_ansi_codes(&rendered2);+ let clean2 = rendered2.ansi_strip().into_owned();assert_eq!(clean2, " +33 -23", "Should be ' +33 -23'");// Test case 3: (2, 2) - both small (needs padding)@@ -1185,7 +1187,7 @@ mod tests {},);let rendered3 = result3.render();- let clean3 = worktrunk::styling::strip_ansi_codes(&rendered3);+ let clean3 = rendered3.ansi_strip().into_owned();assert_eq!(clean3, " +2 -2", "Should be ' +2 -2'");// Verify vertical alignment: the ones digits should be in the same columndiff --git a/src/output/handlers.rs b/src/output/handlers.rsindex c82c99f93..0bd36d793 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -1,6 +1,7 @@//! Output handlers for worktree operations using the global output contextuse color_print::cformat;+use std::path::Path;use crate::commands::process::spawn_detached;use crate::commands::worktree::{RemoveResult, SwitchResult};@@ -10,6 +11,40 @@ use worktrunk::path::format_path_for_display;use worktrunk::shell::Shell;use worktrunk::styling::format_with_gutter;+/// Format a switch success message with a consistent location phrase+///+/// Both interactive and directive modes now use the human-friendly+/// `"Created new worktree for {branch} from {base} at {path}"` wording so+/// users see the same message regardless of how worktrunk is invoked.+fn format_switch_success_message(+ branch: &str,+ path: &Path,+ created_branch: bool,+ base_branch: Option<&str>,+ from_remote: Option<&str>,+) -> String {+ // Determine action and source based on how the worktree was created+ // Priority: explicit --create > DWIM from remote > existing local branch+ let (action, source) = if created_branch {+ ("Created new worktree for", base_branch)+ } else if let Some(remote) = from_remote {+ ("Created worktree for", Some(remote))+ } else {+ ("Switched to worktree for", None)+ };++ match source {+ Some(src) => cformat!(+ "<green>{action} <bold>{branch}</> from <bold>{src}</> at <bold>{}</></>",+ format_path_for_display(path)+ ),+ None => cformat!(+ "<green>{action} <bold>{branch}</> at <bold>{}</></>",+ format_path_for_display(path)+ ),+ }+}+/// Check if a branch's content has been integrated into the target.////// Returns true if the branch is safe to delete because either:@@ -169,7 +204,7 @@ pub fn handle_switch_output(if is_directive_mode || has_execute_command || is_configured {// Shell integration active, --execute provided, or configured - show success- super::success(super::format_switch_success_message(+ super::success(format_switch_success_message(branch, path, false, None, None,))?;} else {@@ -188,7 +223,7 @@ pub fn handle_switch_output(from_remote,} => {// Creation succeeded - show success- super::success(super::format_switch_success_message(+ super::success(format_switch_success_message(branch,path,*created_branch,diff --git a/src/output/mod.rs b/src/output/mod.rsindex a127932ce..769a681d2 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -71,41 +71,3 @@ pub use global::{pub use handlers::{execute_command_in_worktree, execute_user_command, handle_remove_output, handle_switch_output,};--use color_print::cformat;-use std::path::Path;-use worktrunk::path::format_path_for_display;--/// Format a switch success message with a consistent location phrase-///-/// Both interactive and directive modes now use the human-friendly-/// `"Created new worktree for {branch} from {base} at {path}"` wording so-/// users see the same message regardless of how worktrunk is invoked.-pub(crate) fn format_switch_success_message(- branch: &str,- path: &Path,- created_branch: bool,- base_branch: Option<&str>,- from_remote: Option<&str>,-) -> String {- // Determine action and source based on how the worktree was created- // Priority: explicit --create > DWIM from remote > existing local branch- let (action, source) = if created_branch {- ("Created new worktree for", base_branch)- } else if let Some(remote) = from_remote {- ("Created worktree for", Some(remote))- } else {- ("Switched to worktree for", None)- };-- match source {- Some(src) => cformat!(- "<green>{action} <bold>{branch}</> from <bold>{src}</> at <bold>{}</></>",- format_path_for_display(path)- ),- None => cformat!(- "<green>{action} <bold>{branch}</> at <bold>{}</></>",- format_path_for_display(path)- ),- }-}diff --git a/src/styling/format.rs b/src/styling/format.rsindex 4de50fd6f..6ae5d3244 100644--- a/src/styling/format.rs+++ b/src/styling/format.rs@@ -2,7 +2,6 @@//!//! Provides functions for formatting commands and configuration with visual gutters.-use ansi_str::AnsiStr;use unicode_width::UnicodeWidthStr;#[cfg(feature = "syntax-highlighting")]@@ -23,11 +22,6 @@ use super::{get_terminal_width, visual_width};/// so the final output (content + gutter) fits within the terminal width.pub const GUTTER_OVERHEAD: usize = 3;-/// Strip ANSI escape codes from a string-pub fn strip_ansi_codes(s: &str) -> String {- s.ansi_strip().into_owned()-}-/// Wraps text at word boundaries to fit within the specified width////// # Argumentsdiff --git a/src/styling/line.rs b/src/styling/line.rsindex 826970159..b9eadadc5 100644--- a/src/styling/line.rs+++ b/src/styling/line.rs@@ -54,7 +54,7 @@ pub struct StyledString {}impl StyledString {- pub fn new(text: impl Into<String>, style: Option<Style>) -> Self {+ fn new(text: impl Into<String>, style: Option<Style>) -> Self {Self {text: text.into(),style,diff --git a/src/styling/mod.rs b/src/styling/mod.rsindex 96d7613d5..150f347c2 100644--- a/src/styling/mod.rs+++ b/src/styling/mod.rs@@ -26,7 +26,7 @@ pub use anstyle::Style as AnstyleStyle;// Re-export our public typespub use constants::*;-pub use format::{GUTTER_OVERHEAD, format_bash_with_gutter, format_with_gutter, strip_ansi_codes};+pub use format::{GUTTER_OVERHEAD, format_bash_with_gutter, format_with_gutter};pub use highlighting::format_toml;pub use line::{StyledLine, StyledString, truncate_visible};@@ -60,18 +60,6 @@ pub fn visual_width(s: &str) -> usize {s.ansi_strip().width()}-/// Wrap text with an OSC 8 hyperlink-///-/// See: <https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda>-pub fn hyperlink(text: &str, url: &str) -> String {- format!(- "{}{}{}",- osc8::Hyperlink::new(url),- text,- osc8::Hyperlink::END- )-}-// Re-export for tests#[cfg(test)]use format::wrap_styled_text;@@ -427,28 +415,6 @@ command = "npm install");}- #[test]- fn test_hyperlink() {- let text = "Click me";- let url = "https://github.com/user/repo/pull/123";- let result = super::hyperlink(text, url);-- // Should match osc8 library output- let expected = format!(- "{}{}{}",- osc8::Hyperlink::new(url),- text,- osc8::Hyperlink::END- );- assert_eq!(result, expected);-- // Verify structure- assert!(result.starts_with("\x1b]8;;"));- assert!(result.contains(url));- assert!(result.contains(text));- assert!(result.ends_with("\x1b]8;;\x1b\\"));- }-// wrap_styled_text tests#[test]fn test_wrap_styled_text_no_wrapping_needed() {diff --git a/tests/integration_tests/column_alignment_verification.rs b/tests/integration_tests/column_alignment_verification.rsindex d4a381138..562802aec 100644--- a/tests/integration_tests/column_alignment_verification.rs+++ b/tests/integration_tests/column_alignment_verification.rs@@ -12,8 +12,8 @@//! The detailed verification logic here catches alignment bugs that would slip through snapshot review.use crate::common::{TestRepo, wt_command};+use ansi_str::AnsiStr;use unicode_width::UnicodeWidthStr;-use worktrunk::styling::strip_ansi_codes;/// Represents the start position of each column in a table row#[derive(Debug, Clone)]@@ -161,7 +161,7 @@ fn verify_table_alignment(output: &str) -> Result<(), String> {}// Strip ANSI codes from all lines- let stripped_lines: Vec<String> = lines.iter().map(|l| strip_ansi_codes(l)).collect();+ let stripped_lines: Vec<String> = lines.iter().map(|l| l.ansi_strip().into_owned()).collect();if stripped_lines.is_empty() {return Err("No lines after stripping ANSI codes".to_string());diff --git a/tests/integration_tests/list_pty.rs b/tests/integration_tests/list_pty.rsindex 73dd392b8..f09366966 100644--- a/tests/integration_tests/list_pty.rs+++ b/tests/integration_tests/list_pty.rs@@ -107,8 +107,10 @@ fn exec_wt_list_in_pty(/// Normalize PTY output for snapshot testingfn normalize_pty_output(output: &str) -> String {+ use ansi_str::AnsiStr;+// Strip ANSI codes for easier snapshot reading- let output = worktrunk::styling::strip_ansi_codes(output);+ let output = output.ansi_strip();// Normalize line endingsoutput.replace("\r\n", "\n").replace('\r', "\n")