Skip to content

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

Refactor: Consolidate styling into `worktrunk::styling`

Maximilian Roosd8bd1400861a
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index 11abb8f63..a209ca929 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -1,5 +1,8 @@
-use crate::display::{StyledLine, format_relative_time, shorten_path, truncate_at_word_boundary};
-use worktrunk::theme::Theme;
+use crate::display::{format_relative_time, shorten_path, truncate_at_word_boundary};
+use worktrunk::styling::{
+ StyledLine, addition_style, current_style, deletion_style, dim_style, neutral_style,
+ primary_style,
+};
use super::WorktreeInfo;
use super::layout::LayoutConfig;
@@ -39,20 +42,18 @@ pub fn format_all_states(info: &WorktreeInfo) -> String {
pub fn format_header_line(layout: &LayoutConfig) {
let widths = &layout.widths;
- let theme = Theme::new();
- let dim_style = theme.dim;
-
let mut line = StyledLine::new();
+ let dim = dim_style();
// Branch
let header = format!("{:width$}", "Branch", width = widths.branch);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
// Age (Time)
if widths.time > 0 {
let header = format!("{:width$}", "Age", width = widths.time);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
@@ -63,7 +64,7 @@ pub fn format_header_line(layout: &LayoutConfig) {
"Cmts",
width = layout.ideal_widths.ahead_behind
);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
@@ -74,7 +75,7 @@ pub fn format_header_line(layout: &LayoutConfig) {
"Cmt +/-",
width = layout.ideal_widths.branch_diff
);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
@@ -85,37 +86,37 @@ pub fn format_header_line(layout: &LayoutConfig) {
"WT +/-",
width = layout.ideal_widths.working_diff
);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
// Upstream
if layout.ideal_widths.upstream > 0 {
let header = format!("{:width$}", "Remote", width = layout.ideal_widths.upstream);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
// Commit (fixed width: 8 chars)
- line.push_styled("Commit ", dim_style);
+ line.push_styled("Commit ", dim);
line.push_raw(" ");
// Message
if widths.message > 0 {
let header = format!("{:width$}", "Message", width = widths.message);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
// States
if layout.ideal_widths.states > 0 {
let header = format!("{:width$}", "State", width = layout.ideal_widths.states);
- line.push_styled(header, dim_style);
+ line.push_styled(header, dim);
line.push_raw(" ");
}
// Path
- line.push_styled("Path", dim_style);
+ line.push_styled("Path", dim);
println!("{}", line.render());
}
@@ -126,13 +127,12 @@ pub fn format_worktree_line(
current_worktree_path: Option<&std::path::PathBuf>,
) {
let widths = &layout.widths;
- let theme = Theme::new();
- let primary_style = theme.primary;
- let current_style = theme.current;
- let green_style = theme.addition;
- let red_style = theme.deletion;
- let yellow_style = theme.neutral;
- let dim_style = theme.dim;
+ let primary = primary_style();
+ let current = current_style();
+ let green = addition_style();
+ let red = deletion_style();
+ let yellow = neutral_style();
+ let dim = dim_style();
let branch_display = info.worktree.branch.as_deref().unwrap_or("(detached)");
let short_head = &info.worktree.head[..8.min(info.worktree.head.len())];
@@ -142,8 +142,8 @@ pub fn format_worktree_line(
.map(|p| p == &info.worktree.path)
.unwrap_or(false);
let text_style = match (is_current, info.is_primary) {
- (true, _) => Some(current_style),
- (_, true) => Some(primary_style),
+ (true, _) => Some(current),
+ (_, true) => Some(primary),
_ => None,
};
@@ -166,7 +166,7 @@ pub fn format_worktree_line(
format_relative_time(info.timestamp),
width = widths.time
);
- line.push_styled(time_str, dim_style);
+ line.push_styled(time_str, dim);
line.push_raw(" ");
}
@@ -178,7 +178,7 @@ pub fn format_worktree_line(
format!("↑{} ↓{}", info.ahead, info.behind),
width = layout.ideal_widths.ahead_behind
);
- line.push_styled(ahead_behind_text, yellow_style);
+ line.push_styled(ahead_behind_text, yellow);
} else {
// No data for this row: pad with spaces
line.push_raw(" ".repeat(layout.ideal_widths.ahead_behind));
@@ -193,9 +193,9 @@ pub fn format_worktree_line(
if br_added > 0 || br_deleted > 0 {
// Build the diff as a mini styled line
let mut diff_segment = StyledLine::new();
- diff_segment.push_styled(format!("+{}", br_added), green_style);
+ diff_segment.push_styled(format!("+{}", br_added), green);
diff_segment.push_raw(" ");
- diff_segment.push_styled(format!("-{}", br_deleted), red_style);
+ diff_segment.push_styled(format!("-{}", br_deleted), red);
diff_segment.pad_to(layout.ideal_widths.branch_diff);
// Append all segments from diff_segment to main line
for segment in diff_segment.segments {
@@ -218,9 +218,9 @@ pub fn format_worktree_line(
if wt_added > 0 || wt_deleted > 0 {
// Build the diff as a mini styled line
let mut diff_segment = StyledLine::new();
- diff_segment.push_styled(format!("+{}", wt_added), green_style);
+ diff_segment.push_styled(format!("+{}", wt_added), green);
diff_segment.push_raw(" ");
- diff_segment.push_styled(format!("-{}", wt_deleted), red_style);
+ diff_segment.push_styled(format!("-{}", wt_deleted), red);
diff_segment.pad_to(layout.ideal_widths.working_diff);
// Append all segments from diff_segment to main line
for segment in diff_segment.segments {
@@ -239,11 +239,11 @@ pub fn format_worktree_line(
let remote_name = info.upstream_remote.as_deref().unwrap_or("origin");
// Build the upstream as a mini styled line
let mut upstream_segment = StyledLine::new();
- upstream_segment.push_styled(remote_name, dim_style);
+ upstream_segment.push_styled(remote_name, dim);
upstream_segment.push_raw(" ");
- upstream_segment.push_styled(format!("↑{}", info.upstream_ahead), green_style);
+ upstream_segment.push_styled(format!("↑{}", info.upstream_ahead), green);
upstream_segment.push_raw(" ");
- upstream_segment.push_styled(format!("↓{}", info.upstream_behind), red_style);
+ upstream_segment.push_styled(format!("↓{}", info.upstream_behind), red);
upstream_segment.pad_to(layout.ideal_widths.upstream);
// Append all segments from upstream_segment to main line
for segment in upstream_segment.segments {
@@ -271,7 +271,7 @@ pub fn format_worktree_line(
truncate_at_word_boundary(&info.commit_message, layout.max_message_len),
width = widths.message
);
- line.push_styled(msg, dim_style);
+ line.push_styled(msg, dim);
line.push_raw(" ");
}
@@ -304,8 +304,9 @@ mod tests {
use super::*;
use crate::commands::list::WorktreeInfo;
use crate::commands::list::layout::{ColumnWidths, LayoutConfig};
- use crate::display::{StyledLine, shorten_path};
+ use crate::display::shorten_path;
use std::path::PathBuf;
+ use worktrunk::styling::StyledLine;
#[test]
fn test_column_alignment_with_all_columns() {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index b51450f89..0efbb9638 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,6 +1,6 @@
use worktrunk::config::WorktrunkConfig;
-use worktrunk::error_format::format_error;
use worktrunk::git::{GitError, Repository};
+use worktrunk::styling::format_error;
use super::worktree::handle_push;
use super::worktree::handle_remove;
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 11e2cbc12..e898c6819 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -1,7 +1,7 @@
use std::process;
use worktrunk::config::WorktrunkConfig;
-use worktrunk::error_format::{format_error, format_error_with_bold, format_hint};
use worktrunk::git::{GitError, Repository};
+use worktrunk::styling::{format_error, format_error_with_bold, format_hint};
pub fn handle_switch(
branch: &str,
@@ -291,7 +291,7 @@ fn print_worktree_info(path: &std::path::Path, command: &str) {
}
fn format_warning(msg: &str) -> String {
- worktrunk::error_format::format_warning(msg)
+ worktrunk::styling::format_warning(msg)
}
/// Output message with optional CD directive for internal mode.
diff --git a/src/display.rs b/src/display.rs
index 974da8434..1450f8eea 100644
--- a/src/display.rs
+++ b/src/display.rs
@@ -1,90 +1,13 @@
-use anstyle::Style;
+//! Display utilities for terminal output.
+//!
+//! This module provides utility functions for:
+//! - Relative time formatting
+//! - Path manipulation and shortening
+//! - Text truncation with word boundaries
+//! - Terminal width detection
+
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
-use unicode_width::UnicodeWidthStr;
-
-/// A piece of text with an optional style
-#[derive(Clone, Debug)]
-pub struct StyledString {
- pub text: String,
- pub style: Option<Style>,
-}
-
-impl StyledString {
- pub fn new(text: impl Into<String>, style: Option<Style>) -> Self {
- Self {
- text: text.into(),
- style,
- }
- }
-
- pub fn raw(text: impl Into<String>) -> Self {
- Self::new(text, None)
- }
-
- pub fn styled(text: impl Into<String>, style: Style) -> Self {
- Self::new(text, Some(style))
- }
-
- /// Returns the visual width (unicode-aware, no ANSI codes)
- pub fn width(&self) -> usize {
- self.text.width()
- }
-
- /// Renders to a string with ANSI escape codes
- pub fn render(&self) -> String {
- if let Some(style) = &self.style {
- format!("{}{}{}", style.render(), self.text, style.render_reset())
- } else {
- self.text.clone()
- }
- }
-}
-
-/// A line composed of multiple styled strings
-#[derive(Clone, Debug, Default)]
-pub struct StyledLine {
- pub segments: Vec<StyledString>,
-}
-
-impl StyledLine {
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Add a raw (unstyled) segment
- pub fn push_raw(&mut self, text: impl Into<String>) {
- self.segments.push(StyledString::raw(text));
- }
-
- /// Add a styled segment
- pub fn push_styled(&mut self, text: impl Into<String>, style: Style) {
- self.segments.push(StyledString::styled(text, style));
- }
-
- /// Add a segment (StyledString)
- pub fn push(&mut self, segment: StyledString) {
- self.segments.push(segment);
- }
-
- /// Pad with spaces to reach a specific width
- pub fn pad_to(&mut self, target_width: usize) {
- let current_width = self.width();
- if current_width < target_width {
- self.push_raw(" ".repeat(target_width - current_width));
- }
- }
-
- /// Returns the total visual width
- pub fn width(&self) -> usize {
- self.segments.iter().map(|s| s.width()).sum()
- }
-
- /// Renders the entire line with ANSI escape codes
- pub fn render(&self) -> String {
- self.segments.iter().map(|s| s.render()).collect()
- }
-}
pub fn format_relative_time(timestamp: i64) -> String {
let now = SystemTime::now()
@@ -193,82 +116,3 @@ pub fn get_terminal_width() -> usize {
.map(|(terminal_size::Width(w), _)| w as usize)
.unwrap_or(80)
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_styled_string_width() {
- // ASCII strings
- let s = StyledString::raw("hello");
- assert_eq!(s.width(), 5);
-
- // Unicode arrows
- let s = StyledString::raw("↑3 ↓2");
- assert_eq!(
- s.width(),
- 5,
- "↑3 ↓2 should have width 5, not {}",
- s.text.len()
- );
-
- // Mixed Unicode
- let s = StyledString::raw("日本語");
- assert_eq!(s.width(), 6); // CJK characters are typically width 2
-
- // Emoji
- let s = StyledString::raw("🎉");
- assert_eq!(s.width(), 2); // Emoji are typically width 2
- }
-
- #[test]
- fn test_styled_line_width() {
- let mut line = StyledLine::new();
- line.push_raw("Branch");
- line.push_raw(" ");
- line.push_raw("↑3 ↓2");
-
- // "Branch" (6) + " " (2) + "↑3 ↓2" (5) = 13
- assert_eq!(line.width(), 13, "Line width should be 13");
- }
-
- #[test]
- fn test_styled_line_padding() {
- let mut line = StyledLine::new();
- line.push_raw("test");
- assert_eq!(line.width(), 4);
-
- line.pad_to(10);
- assert_eq!(line.width(), 10, "After padding to 10, width should be 10");
-
- // Padding when already at target should not change width
- line.pad_to(10);
- assert_eq!(line.width(), 10, "Padding again should not change width");
- }
-
- #[test]
- fn test_sparse_column_padding() {
- // Build simplified lines to test sparse column padding
- let mut line1 = StyledLine::new();
- line1.push_raw(format!("{:8}", "branch-a"));
- line1.push_raw(" ");
- // Has ahead/behind
- line1.push_raw(format!("{:5}", "↑3 ↓2"));
- line1.push_raw(" ");
-
- let mut line2 = StyledLine::new();
- line2.push_raw(format!("{:8}", "branch-b"));
- line2.push_raw(" ");
- // No ahead/behind, should pad with spaces
- line2.push_raw(" ".repeat(5));
- line2.push_raw(" ");
-
- // Both lines should have same width up to this point
- assert_eq!(
- line1.width(),
- line2.width(),
- "Rows with and without sparse column data should have same width"
- );
- }
-}
diff --git a/src/error_format.rs b/src/error_format.rs
deleted file mode 100644
index eff0e926b..000000000
--- a/src/error_format.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-use crate::theme::Theme;
-use std::io::IsTerminal;
-
-/// Determines if colored output should be used based on environment
-fn should_use_color_with_env(no_color: bool, force_color: bool, is_terminal: bool) -> bool {
- if force_color {
- return true;
- }
- if no_color {
- return false;
- }
- is_terminal
-}
-
-/// Determines if colored output should be used
-fn should_use_color() -> bool {
- should_use_color_with_env(
- std::env::var("NO_COLOR").is_ok(),
- std::env::var("CLICOLOR_FORCE").is_ok() || std::env::var("FORCE_COLOR").is_ok(),
- std::io::stderr().is_terminal(),
- )
-}
-
-/// Format an error message with red color and ❌ emoji
-pub fn format_error(msg: &str) -> String {
- if should_use_color() {
- let theme = Theme::new();
- format!(
- "{}❌ {}{}",
- theme.error.render(),
- msg,
- theme.error.render_reset()
- )
- } else {
- format!("❌ {}", msg)
- }
-}
-
-/// Format a warning message with yellow color and 🟡 emoji
-pub fn format_warning(msg: &str) -> String {
- if should_use_color() {
- let theme = Theme::new();
- format!(
- "{}🟡 {}{}",
- theme.warning.render(),
- msg,
- theme.warning.render_reset()
- )
- } else {
- format!("🟡 {}", msg)
- }
-}
-
-/// Format a hint message with dim color and 💡 emoji
-pub fn format_hint(msg: &str) -> String {
- if should_use_color() {
- let theme = Theme::new();
- format!(
- "{}💡 {}{}",
- theme.hint.render(),
- msg,
- theme.hint.render_reset()
- )
- } else {
- format!("💡 {}", msg)
- }
-}
-
-/// Format text with bold styling
-pub fn bold(text: &str) -> String {
- if should_use_color() {
- let theme = Theme::new();
- format!(
- "{}{}{}",
- theme.bold.render(),
- text,
- theme.bold.render_reset()
- )
- } else {
- text.to_string()
- }
-}
-
-/// Format an error message with bold emphasis on specific parts
-///
-/// Example: `format_error_with_bold("Branch '", "feature-x", "' already exists")`
-pub fn format_error_with_bold(prefix: &str, emphasized: &str, suffix: &str) -> String {
- if should_use_color() {
- let theme = Theme::new();
- format!(
- "{}❌ {}{}{}{}{}{}",
- theme.error.render(),
- prefix,
- theme.error_bold.render(),
- emphasized,
- theme.error.render(), // Back to regular red
- suffix,
- theme.error.render_reset()
- )
- } else {
- format!("❌ {}{}{}", prefix, emphasized, suffix)
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_should_use_color_force_color() {
- assert!(should_use_color_with_env(false, true, false));
- assert!(should_use_color_with_env(true, true, false));
- }
-
- #[test]
- fn test_should_use_color_no_color() {
- assert!(!should_use_color_with_env(true, false, true));
- assert!(!should_use_color_with_env(true, false, false));
- }
-
- #[test]
- fn test_should_use_color_terminal() {
- assert!(should_use_color_with_env(false, false, true));
- assert!(!should_use_color_with_env(false, false, false));
- }
-}
diff --git a/src/git.rs b/src/git.rs
index 07a334886..9258633b4 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -25,7 +25,7 @@ impl std::fmt::Display for GitError {
GitError::CommandFailed(msg) => write!(f, "{}", msg),
// ParseError messages need formatting
GitError::ParseError(msg) => {
- use crate::error_format::format_error;
+ use crate::styling::format_error;
write!(f, "{}", format_error(msg))
}
}
@@ -183,7 +183,7 @@ impl Repository {
/// Returns an error if there are uncommitted changes.
pub fn ensure_clean_working_tree(&self) -> Result<(), GitError> {
if self.is_dirty()? {
- return Err(GitError::CommandFailed(crate::error_format::format_error(
+ return Err(GitError::CommandFailed(crate::styling::format_error(
"Working tree has uncommitted changes. Commit or stash them first.",
)));
}
diff --git a/src/lib.rs b/src/lib.rs
index 56a9d540e..3691aa452 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,7 +1,6 @@
pub mod config;
-pub mod error_format;
pub mod git;
pub mod shell;
-pub mod theme;
+pub mod styling;
// Note: display, commands, and llm modules are used by main.rs but not exposed as public API
diff --git a/src/styling.rs b/src/styling.rs
new file mode 100644
index 000000000..cecb94d46
--- /dev/null
+++ b/src/styling.rs
@@ -0,0 +1,359 @@
+//! Consolidated styling module for terminal output.
+//!
+//! This module provides:
+//! - Color/style detection based on environment variables
+//! - Formatted message functions (error, warning, hint, etc.)
+//! - Styled string/line types for building complex output
+
+use anstyle::{AnsiColor, Color, Style};
+use std::io::IsTerminal;
+use unicode_width::UnicodeWidthStr;
+
+// ============================================================================
+// Style Definitions (as constant functions to avoid repeated allocation)
+// ============================================================================
+
+/// Get error style (red)
+pub fn error_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)))
+}
+
+/// Get warning style (yellow)
+pub fn warning_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))
+}
+
+/// Get hint style (dimmed)
+pub fn hint_style() -> Style {
+ Style::new().dimmed()
+}
+
+/// Get success style (green)
+pub fn success_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)))
+}
+
+/// Get bold style
+pub fn bold_style() -> Style {
+ Style::new().bold()
+}
+
+/// Get dim style
+pub fn dim_style() -> Style {
+ Style::new().dimmed()
+}
+
+/// Get error bold style (red + bold)
+pub fn error_bold_style() -> Style {
+ Style::new()
+ .fg_color(Some(Color::Ansi(AnsiColor::Red)))
+ .bold()
+}
+
+/// Get primary style for worktrees (cyan)
+pub fn primary_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))
+}
+
+/// Get current style for worktrees (magenta + bold)
+pub fn current_style() -> Style {
+ Style::new()
+ .bold()
+ .fg_color(Some(Color::Ansi(AnsiColor::Magenta)))
+}
+
+/// Get addition style for diffs (green)
+pub fn addition_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green)))
+}
+
+/// Get deletion style for diffs (red)
+pub fn deletion_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)))
+}
+
+/// Get neutral style for diffs (yellow)
+pub fn neutral_style() -> Style {
+ Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)))
+}
+
+// ============================================================================
+// Color Detection
+// ============================================================================
+
+/// Determines if colored output should be used based on environment
+fn should_use_color_with_env(no_color: bool, force_color: bool, is_terminal: bool) -> bool {
+ if force_color {
+ return true;
+ }
+ if no_color {
+ return false;
+ }
+ is_terminal
+}
+
+/// Determines if colored output should be used
+pub fn should_use_color() -> bool {
+ should_use_color_with_env(
+ std::env::var("NO_COLOR").is_ok(),
+ std::env::var("CLICOLOR_FORCE").is_ok() || std::env::var("FORCE_COLOR").is_ok(),
+ std::io::stderr().is_terminal(),
+ )
+}
+
+// ============================================================================
+// Formatted Message Functions
+// ============================================================================
+
+/// Format an error message with red color and ❌ emoji
+pub fn format_error(msg: &str) -> String {
+ if should_use_color() {
+ let style = error_style();
+ format!("{}❌ {}{}", style.render(), msg, style.render_reset())
+ } else {
+ format!("❌ {}", msg)
+ }
+}
+
+/// Format a warning message with yellow color and 🟡 emoji
+pub fn format_warning(msg: &str) -> String {
+ if should_use_color() {
+ let style = warning_style();
+ format!("{}🟡 {}{}", style.render(), msg, style.render_reset())
+ } else {
+ format!("🟡 {}", msg)
+ }
+}
+
+/// Format a hint message with dim color and 💡 emoji
+pub fn format_hint(msg: &str) -> String {
+ if should_use_color() {
+ let style = hint_style();
+ format!("{}💡 {}{}", style.render(), msg, style.render_reset())
+ } else {
+ format!("💡 {}", msg)
+ }
+}
+
+/// Format text with bold styling
+pub fn bold(text: &str) -> String {
+ if should_use_color() {
+ let style = bold_style();
+ format!("{}{}{}", style.render(), text, style.render_reset())
+ } else {
+ text.to_string()
+ }
+}
+
+/// Format an error message with bold emphasis on specific parts
+///
+/// Example: `format_error_with_bold("Branch '", "feature-x", "' already exists")`
+pub fn format_error_with_bold(prefix: &str, emphasized: &str, suffix: &str) -> String {
+ if should_use_color() {
+ let error = error_style();
+ let error_bold = error_bold_style();
+ format!(
+ "{}❌ {}{}{}{}{}{}",
+ error.render(),
+ prefix,
+ error_bold.render(),
+ emphasized,
+ error.render(), // Back to regular red
+ suffix,
+ error.render_reset()
+ )
+ } else {
+ format!("❌ {}{}{}", prefix, emphasized, suffix)
+ }
+}
+
+// ============================================================================
+// Styled Output Types
+// ============================================================================
+
+/// A piece of text with an optional style
+#[derive(Clone, Debug)]
+pub struct StyledString {
+ pub text: String,
+ pub style: Option<Style>,
+}
+
+impl StyledString {
+ pub fn new(text: impl Into<String>, style: Option<Style>) -> Self {
+ Self {
+ text: text.into(),
+ style,
+ }
+ }
+
+ pub fn raw(text: impl Into<String>) -> Self {
+ Self::new(text, None)
+ }
+
+ pub fn styled(text: impl Into<String>, style: Style) -> Self {
+ Self::new(text, Some(style))
+ }
+
+ /// Returns the visual width (unicode-aware, no ANSI codes)
+ pub fn width(&self) -> usize {
+ self.text.width()
+ }
+
+ /// Renders to a string with ANSI escape codes
+ pub fn render(&self) -> String {
+ if let Some(style) = &self.style {
+ format!("{}{}{}", style.render(), self.text, style.render_reset())
+ } else {
+ self.text.clone()
+ }
+ }
+}
+
+/// A line composed of multiple styled strings
+#[derive(Clone, Debug, Default)]
+pub struct StyledLine {
+ pub segments: Vec<StyledString>,
+}
+
+impl StyledLine {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a raw (unstyled) segment
+ pub fn push_raw(&mut self, text: impl Into<String>) {
+ self.segments.push(StyledString::raw(text));
+ }
+
+ /// Add a styled segment
+ pub fn push_styled(&mut self, text: impl Into<String>, style: Style) {
+ self.segments.push(StyledString::styled(text, style));
+ }
+
+ /// Add a segment (StyledString)
+ pub fn push(&mut self, segment: StyledString) {
+ self.segments.push(segment);
+ }
+
+ /// Pad with spaces to reach a specific width
+ pub fn pad_to(&mut self, target_width: usize) {
+ let current_width = self.width();
+ if current_width < target_width {
+ self.push_raw(" ".repeat(target_width - current_width));
+ }
+ }
+
+ /// Returns the total visual width
+ pub fn width(&self) -> usize {
+ self.segments.iter().map(|s| s.width()).sum()
+ }
+
+ /// Renders the entire line with ANSI escape codes
+ pub fn render(&self) -> String {
+ self.segments.iter().map(|s| s.render()).collect()
+ }
+}
+
+// ============================================================================
+// Tests
+// ============================================================================
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Color detection tests
+ #[test]
+ fn test_should_use_color_force_color() {
+ assert!(should_use_color_with_env(false, true, false));
+ assert!(should_use_color_with_env(true, true, false));
+ }
+
+ #[test]
+ fn test_should_use_color_no_color() {
+ assert!(!should_use_color_with_env(true, false, true));
+ assert!(!should_use_color_with_env(true, false, false));
+ }
+
+ #[test]
+ fn test_should_use_color_terminal() {
+ assert!(should_use_color_with_env(false, false, true));
+ assert!(!should_use_color_with_env(false, false, false));
+ }
+
+ // StyledString tests
+ #[test]
+ fn test_styled_string_width() {
+ // ASCII strings
+ let s = StyledString::raw("hello");
+ assert_eq!(s.width(), 5);
+
+ // Unicode arrows
+ let s = StyledString::raw("↑3 ↓2");
+ assert_eq!(
+ s.width(),
+ 5,
+ "↑3 ↓2 should have width 5, not {}",
+ s.text.len()
+ );
+
+ // Mixed Unicode
+ let s = StyledString::raw("日本語");
+ assert_eq!(s.width(), 6); // CJK characters are typically width 2
+
+ // Emoji
+ let s = StyledString::raw("🎉");
+ assert_eq!(s.width(), 2); // Emoji are typically width 2
+ }
+
+ // StyledLine tests
+ #[test]
+ fn test_styled_line_width() {
+ let mut line = StyledLine::new();
+ line.push_raw("Branch");
+ line.push_raw(" ");
+ line.push_raw("↑3 ↓2");
+
+ // "Branch" (6) + " " (2) + "↑3 ↓2" (5) = 13
+ assert_eq!(line.width(), 13, "Line width should be 13");
+ }
+
+ #[test]
+ fn test_styled_line_padding() {
+ let mut line = StyledLine::new();
+ line.push_raw("test");
+ assert_eq!(line.width(), 4);
+
+ line.pad_to(10);
+ assert_eq!(line.width(), 10, "After padding to 10, width should be 10");
+
+ // Padding when already at target should not change width
+ line.pad_to(10);
+ assert_eq!(line.width(), 10, "Padding again should not change width");
+ }
+
+ #[test]
+ fn test_sparse_column_padding() {
+ // Build simplified lines to test sparse column padding
+ let mut line1 = StyledLine::new();
+ line1.push_raw(format!("{:8}", "branch-a"));
+ line1.push_raw(" ");
+ // Has ahead/behind
+ line1.push_raw(format!("{:5}", "↑3 ↓2"));
+ line1.push_raw(" ");
+
+ let mut line2 = StyledLine::new();
+ line2.push_raw(format!("{:8}", "branch-b"));
+ line2.push_raw(" ");
+ // No ahead/behind, should pad with spaces
+ line2.push_raw(" ".repeat(5));
+ line2.push_raw(" ");
+
+ // Both lines should have same width up to this point
+ assert_eq!(
+ line1.width(),
+ line2.width(),
+ "Rows with and without sparse column data should have same width"
+ );
+ }
+}
diff --git a/src/theme.rs b/src/theme.rs
deleted file mode 100644
index f6e243d5e..000000000
--- a/src/theme.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-use anstyle::{AnsiColor, Color, Style};
-
-/// Centralized theme for terminal output styling.
-///
-/// Provides consistent colors and styles across the application.
-/// All style definitions are in one place for easy customization.
-#[derive(Debug, Clone)]
-pub struct Theme {
- // Status/message styles
- pub error: Style,
- pub warning: Style,
- pub hint: Style,
- pub success: Style,
-
- // Emphasis styles
- pub bold: Style,
- pub dim: Style,
- pub error_bold: Style,
-
- // Worktree-specific styles
- pub primary: Style,
- pub current: Style,
-
- // Diff/stat styles
- pub addition: Style,
- pub deletion: Style,
- pub neutral: Style,
-}
-
-impl Theme {
- /// Create a new theme with default colors.
- pub fn new() -> Self {
- Self {
- // Status/message styles
- error: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
- warning: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
- hint: Style::new().dimmed(),
- success: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green))),
-
- // Emphasis styles
- bold: Style::new().bold(),
- dim: Style::new().dimmed(),
- error_bold: Style::new()
- .fg_color(Some(Color::Ansi(AnsiColor::Red)))
- .bold(),
-
- // Worktree-specific styles
- primary: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan))),
- current: Style::new()
- .bold()
- .fg_color(Some(Color::Ansi(AnsiColor::Magenta))),
-
- // Diff/stat styles
- addition: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green))),
- deletion: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red))),
- neutral: Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow))),
- }
- }
-}
-
-impl Default for Theme {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_theme_creation() {
- let theme = Theme::new();
- // Just verify it doesn't panic
- let _ = theme.error;
- let _ = theme.primary;
- }
-
- #[test]
- fn test_theme_default() {
- let theme = Theme::default();
- let _ = theme.warning;
- }
-}