Skip to content

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

Add diffstat to wt select log preview (Tab 2) (#179)

Maximilian Roosf41642777b9b
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index 337a822bd..eb2f11dbe 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -165,7 +165,10 @@ use unicode_width::UnicodeWidthStr;
use worktrunk::styling::{ADDITION, DELETION};
use super::collect::TaskKind;
-use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec, DiffVariant};
+use super::columns::{COLUMN_SPECS, ColumnKind, ColumnSpec};
+
+// Re-export DiffVariant for external use (e.g., select command)
+pub use super::columns::DiffVariant;
/// Width of short commit hash display (first 8 hex characters)
const COMMIT_HASH_WIDTH: usize = 8;
diff --git a/src/commands/list/render.rs b/src/commands/list/render.rs
index dd34e6eb3..aa6475dbf 100644
--- a/src/commands/list/render.rs
+++ b/src/commands/list/render.rs
@@ -27,7 +27,38 @@ fn position_style(is_current: bool, default: Style) -> Style {
}
impl DiffDisplayConfig {
- fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {
+ /// Format diff values with fixed-width alignment for tabular display.
+ ///
+ /// Numbers are right-aligned within their allocated digit width.
+ /// Returns empty spaces if both values are zero (unless `always_show_zeros` is set).
+ ///
+ /// # Arguments
+ /// * `positive` - The positive (added) value
+ /// * `negative` - The negative (deleted) value
+ /// * `digits` - Number of digits to allocate for each column (e.g., 3 for values up to 999)
+ #[cfg(unix)] // Only used by select command which is unix-only
+ pub fn format_aligned(&self, positive: usize, negative: usize, digits: usize) -> String {
+ use super::layout::DiffColumnConfig;
+
+ let positive_width = 1 + digits; // symbol + digits
+ let negative_width = 1 + digits;
+ let total_width = positive_width + 1 + negative_width; // with separator
+
+ let config = DiffColumnConfig {
+ positive_digits: digits,
+ negative_digits: digits,
+ total_width,
+ display: *self,
+ };
+
+ config.render_segment(positive, negative).render()
+ }
+
+ /// Format diff values as plain text with ANSI colors (no fixed-width alignment).
+ ///
+ /// Returns `None` if both values are zero (unless `always_show_zeros` is set).
+ /// Format: `+N -M` with appropriate colors for each component.
+ pub fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {
if !self.always_show_zeros && positive == 0 && negative == 0 {
return None;
}
@@ -213,7 +244,11 @@ impl DiffColumnConfig {
}
}
- fn render_segment(&self, positive: usize, negative: usize) -> StyledLine {
+ /// Render diff values as a StyledLine with fixed-width alignment.
+ ///
+ /// Numbers are right-aligned within their allocated digit width.
+ /// Use this for tabular display where columns must align vertically.
+ pub fn render_segment(&self, positive: usize, negative: usize) -> StyledLine {
let symbols = self.display.variant.symbols();
let mut segment = StyledLine::new();
@@ -707,6 +742,90 @@ mod tests {
config.render_segment(positive, negative)
}
+ #[test]
+ #[cfg(unix)] // format_aligned is unix-only
+ fn test_format_aligned_produces_fixed_width_output() {
+ use super::super::columns::DiffVariant;
+
+ let config = DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ };
+
+ // Test various values with 3-digit columns
+ let result1 = config.format_aligned(310, 112, 3);
+ let result2 = config.format_aligned(54, 63, 3);
+ let result3 = config.format_aligned(9, 3, 3);
+
+ // All should have the same width (3 + 1 + 3 + 1 + 3 = 9 chars for "+NNN -NNN")
+ let clean1 = result1.ansi_strip().into_owned();
+ let clean2 = result2.ansi_strip().into_owned();
+ let clean3 = result3.ansi_strip().into_owned();
+
+ assert_eq!(
+ clean1.len(),
+ clean2.len(),
+ "All aligned outputs should have same width"
+ );
+ assert_eq!(
+ clean2.len(),
+ clean3.len(),
+ "All aligned outputs should have same width"
+ );
+
+ // Verify right-alignment: smaller numbers have leading spaces
+ assert!(
+ clean2.starts_with(' '),
+ "54 should have leading space: '{}'",
+ clean2
+ );
+ assert!(
+ clean3.starts_with(' '),
+ "9 should have leading spaces: '{}'",
+ clean3
+ );
+ }
+
+ #[test]
+ #[cfg(unix)] // format_aligned is unix-only
+ fn test_format_aligned_handles_single_side() {
+ use super::super::columns::DiffVariant;
+
+ let config = DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ };
+
+ // Insertions only
+ let ins_only = config.format_aligned(447, 0, 3);
+ let clean_ins = ins_only.ansi_strip().into_owned();
+ assert!(
+ clean_ins.contains("+447"),
+ "Should contain +447: '{}'",
+ clean_ins
+ );
+
+ // Deletions only
+ let del_only = config.format_aligned(0, 5, 3);
+ let clean_del = del_only.ansi_strip().into_owned();
+ assert!(
+ clean_del.contains("-5"),
+ "Should contain -5: '{}'",
+ clean_del
+ );
+
+ // Both should have same total width
+ assert_eq!(
+ clean_ins.len(),
+ clean_del.len(),
+ "Single-side outputs should match width"
+ );
+ }
+
#[test]
fn test_format_diff_column_pads_to_total_width() {
use super::super::columns::DiffVariant;
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 13d5d6091..046634899 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -10,6 +10,7 @@ use worktrunk::config::WorktrunkConfig;
use worktrunk::git::Repository;
use super::list::collect;
+use super::list::layout::{DiffDisplayConfig, DiffVariant};
use super::list::model::ListItem;
use super::worktree::handle_switch;
use crate::output::handle_switch_output;
@@ -449,7 +450,6 @@ impl WorktreeSkimItem {
&& !stat.trim().is_empty()
{
output.push_str(&stat);
- output.push_str("\n\n");
// Build diff args with color
let mut diff_args = args.to_vec();
@@ -560,53 +560,92 @@ impl WorktreeSkimItem {
let no_timestamp_format = "--format=%C(auto)%h%C(auto)%d%C(reset) %s";
let dim_no_timestamp_format = "--format=%C(dim)%h%C(reset) %s";
- // With timestamps, we use \x1f (unit separator) as delimiter to separate fields
- // Format: hash \x1f unix_timestamp \x1f rest
- // We compute terse relative time (e.g., "2h", "3d") from unix timestamp
- // Note: \x00 doesn't work as git strips null bytes from format output
+ // With timestamps and diffstat, we use field delimiter and --numstat for predictable parsing:
+ // - \x1f (unit separator) separates fields within a commit line
+ // - --numstat gives tab-separated "added\tdeleted\tfilename" lines we sum
+ // Format: graph + hash \x1f timestamp \x1f message (followed by numstat lines)
const TIMESTAMP_WIDTH: usize = 4; // "12mo" is the longest
- const DELIM: char = '\x1f';
+ const FIELD_DELIM: char = '\x1f';
let timestamp_format = "--format=%C(auto)%h\x1f%ct\x1f%C(auto)%d%C(reset) %s";
- // Dim format: hash is dimmed, timestamp will also be dimmed by format_timestamps
+ // Dim format: hash is dimmed, timestamp will also be dimmed
let dim_timestamp_format = "--format=%C(dim)%h%C(reset)\x1f%ct\x1f %s";
- // Helper to format timestamps in git log output
- // Parses delimiter-separated fields and inserts padded relative time
- let format_timestamps = |log_output: &str| -> String {
+ // Helper to format log output with timestamps and diffstat
+ // Parses --numstat output: commit lines have \x1f, stat lines have tabs
+ let format_log_output = |log_output: &str| -> String {
use crate::display::format_relative_time_short;
+ use worktrunk::styling::{ADDITION, DELETION};
+
let dim_style = anstyle::Style::new().dimmed();
let reset = anstyle::Reset;
- log_output
- .lines()
- .map(|line| {
- // Line format: "* hash{DELIM}timestamp{DELIM}rest"
- // Split on first delimiter to get graph+hash, then on second for timestamp
- if let Some(first_delim) = line.find(DELIM)
- && let Some(second_delim) = line[first_delim + 1..].find(DELIM)
+
+ // State machine: accumulate stats for each commit
+ let mut pending_commit: Option<&str> = None;
+ let mut pending_stats: (usize, usize) = (0, 0);
+ let mut result = Vec::new();
+
+ // Format a commit line with stats
+ let format_commit =
+ |commit_line: &str, (insertions, deletions): (usize, usize)| -> String {
+ if let Some(first_delim) = commit_line.find(FIELD_DELIM)
+ && let Some(second_delim) = commit_line[first_delim + 1..].find(FIELD_DELIM)
{
- let graph_hash = &line[..first_delim];
- let timestamp_str = &line[first_delim + 1..first_delim + 1 + second_delim];
- let rest = &line[first_delim + 1 + second_delim + 1..];
- // Parse unix timestamp and format as terse relative time
+ let graph_hash = &commit_line[..first_delim];
+ let timestamp_str =
+ &commit_line[first_delim + 1..first_delim + 1 + second_delim];
+ let rest = &commit_line[first_delim + 1 + second_delim + 1..];
+
let time = timestamp_str
.parse::<i64>()
.map(format_relative_time_short)
.unwrap_or_default();
- // Timestamp is always dimmed (secondary info)
- // Format: hash + timestamp (right-aligned) + rest
- // rest includes leading space from %d (decoration) or ` %s` (no decoration)
- return format!(
- "{}{dim_style}{:>width$}{reset}{}",
+
+ // Use the same diff formatting as wt list (aligned columns)
+ let diff_config = DiffDisplayConfig {
+ variant: DiffVariant::Signs,
+ positive_style: ADDITION,
+ negative_style: DELETION,
+ always_show_zeros: false,
+ };
+ // 3 digits handles values up to 999; overflow uses K notation
+ let stat_str =
+ format!(" {}", diff_config.format_aligned(insertions, deletions, 3));
+
+ format!(
+ "{}{} {dim_style}{:>width$}{reset}{}",
graph_hash,
+ stat_str,
time,
rest,
width = TIMESTAMP_WIDTH
- );
+ )
+ } else {
+ commit_line.to_string()
}
- line.to_string()
- })
- .collect::<Vec<_>>()
- .join("\n")
+ };
+
+ for line in log_output.lines() {
+ if line.contains(FIELD_DELIM) {
+ // This is a commit line - emit any pending commit first
+ if let Some(prev) = pending_commit.take() {
+ result.push(format_commit(prev, pending_stats));
+ }
+ pending_commit = Some(line);
+ pending_stats = (0, 0);
+ } else if let Some((ins, del)) = Self::parse_numstat_line(line) {
+ // Accumulate stats for pending commit
+ pending_stats.0 += ins;
+ pending_stats.1 += del;
+ }
+ // Skip empty/graph-only lines
+ }
+
+ // Don't forget final commit
+ if let Some(last) = pending_commit {
+ result.push(format_commit(last, pending_stats));
+ }
+
+ result.join("\n")
};
let log_limit_str = log_limit.to_string();
@@ -617,17 +656,14 @@ impl WorktreeSkimItem {
} else {
no_timestamp_format
};
- if let Ok(log_output) = repo.run_command(&[
- "log",
- "--graph",
- format,
- "--color=always",
- "-n",
- &log_limit_str,
- head,
- ]) {
+ let mut args = vec!["log", "--graph", format, "--color=always"];
+ if show_timestamps {
+ args.push("--numstat");
+ }
+ args.extend_from_slice(&["-n", &log_limit_str, head]);
+ if let Ok(log_output) = repo.run_command(&args) {
if show_timestamps {
- output.push_str(&format_timestamps(&log_output));
+ output.push_str(&format_log_output(&log_output));
} else {
output.push_str(&log_output);
}
@@ -643,14 +679,19 @@ impl WorktreeSkimItem {
} else {
no_timestamp_format
};
+ let mut args = vec!["log", "--graph", format, "--color=always"];
+ if show_timestamps {
+ args.push("--numstat");
+ }
+ args.push(&range);
let mut bright_count = 0;
- if let Ok(log_output) =
- repo.run_command(&["log", "--graph", format, "--color=always", &range])
+ if let Ok(log_output) = repo.run_command(&args)
&& !log_output.is_empty()
{
- bright_count = log_output.lines().count();
+ // Count commit lines (those with field delimiter, not numstat lines)
+ bright_count = log_output.lines().filter(|l| l.contains('\x1f')).count();
if show_timestamps {
- output.push_str(&format_timestamps(&log_output));
+ output.push_str(&format_log_output(&log_output));
} else {
output.push_str(&log_output);
}
@@ -669,17 +710,15 @@ impl WorktreeSkimItem {
} else {
dim_no_timestamp_format
};
- if let Ok(log_output) = repo.run_command(&[
- "log",
- "--graph",
- format,
- "--color=always",
- "-n",
- &dim_limit.to_string(),
- merge_base,
- ]) {
+ let dim_limit_str = dim_limit.to_string();
+ let mut args = vec!["log", "--graph", format, "--color=always"];
+ if show_timestamps {
+ args.push("--numstat");
+ }
+ args.extend_from_slice(&["-n", &dim_limit_str, merge_base]);
+ if let Ok(log_output) = repo.run_command(&args) {
if show_timestamps {
- output.push_str(&format_timestamps(&log_output));
+ output.push_str(&format_log_output(&log_output));
} else {
output.push_str(&log_output);
}
@@ -689,6 +728,42 @@ impl WorktreeSkimItem {
output
}
+
+ /// Parse a git numstat line and extract insertions/deletions
+ ///
+ /// Numstat format: `added<TAB>deleted<TAB>filename`
+ /// With --graph --color=always, lines have ANSI-colored graph prefix like `ESC[31m|ESC[m `.
+ /// Binary files show "-" instead of numbers.
+ ///
+ /// Returns Some((insertions, deletions)) for valid numstat lines.
+ fn parse_numstat_line(line: &str) -> Option<(usize, usize)> {
+ use ansi_str::AnsiStr;
+
+ // First strip ANSI escape sequences (graph coloring contains digits that confuse parsing)
+ let stripped = line.ansi_strip();
+
+ // Strip graph prefix (e.g., "| ") and find tab-separated values
+ let trimmed = stripped.trim_start_matches(|c: char| !c.is_ascii_digit() && c != '-');
+
+ // Must have at least two tab-separated fields
+ let mut parts = trimmed.split('\t');
+ let added_str = parts.next()?;
+ let deleted_str = parts.next()?;
+
+ // "-" means binary file, treat as 0
+ let added = if added_str == "-" {
+ 0
+ } else {
+ added_str.parse().ok()?
+ };
+ let deleted = if deleted_str == "-" {
+ 0
+ } else {
+ deleted_str.parse().ok()?
+ };
+
+ Some((added, deleted))
+ }
}
pub fn handle_select(is_directive_mode: bool) -> anyhow::Result<()> {
@@ -1046,4 +1121,63 @@ mod tests {
assert!(output.contains("2: log"));
assert!(output.contains("3: main…±"));
}
+
+ #[test]
+ fn test_parse_numstat_line_basic() {
+ // Tab-separated: added<TAB>deleted<TAB>filename
+ let result = WorktreeSkimItem::parse_numstat_line("10\t5\tfile.rs");
+ assert_eq!(result, Some((10, 5)));
+ }
+
+ #[test]
+ fn test_parse_numstat_line_insertions_only() {
+ let result = WorktreeSkimItem::parse_numstat_line("15\t0\tfile.rs");
+ assert_eq!(result, Some((15, 0)));
+ }
+
+ #[test]
+ fn test_parse_numstat_line_deletions_only() {
+ let result = WorktreeSkimItem::parse_numstat_line("0\t8\tfile.rs");
+ assert_eq!(result, Some((0, 8)));
+ }
+
+ #[test]
+ fn test_parse_numstat_line_binary_file() {
+ // Binary files show "-" instead of numbers
+ let result = WorktreeSkimItem::parse_numstat_line("-\t-\timage.png");
+ assert_eq!(result, Some((0, 0)));
+ }
+
+ #[test]
+ fn test_parse_numstat_line_with_graph_prefix() {
+ // Git graph prefixes the numstat line with graph characters
+ let result = WorktreeSkimItem::parse_numstat_line("| 10\t5\tfile.rs");
+ assert_eq!(result, Some((10, 5)));
+
+ // First numstat line after commit has "* | " prefix
+ let result = WorktreeSkimItem::parse_numstat_line("* | 11\t0\tCargo.toml");
+ assert_eq!(result, Some((11, 0)));
+
+ // Subsequent numstat lines have "| " prefix
+ let result = WorktreeSkimItem::parse_numstat_line("| 17\t3\tsrc/main.rs");
+ assert_eq!(result, Some((17, 3)));
+
+ // With ANSI colors (--color=always adds escape codes to graph)
+ // ESC[31m = red, ESC[m = reset
+ let esc = '\x1b';
+ let ansi_colored = format!("{esc}[31m|{esc}[m 11\t0\tCargo.toml");
+ let result = WorktreeSkimItem::parse_numstat_line(&ansi_colored);
+ assert_eq!(result, Some((11, 0)));
+ }
+
+ #[test]
+ fn test_parse_numstat_line_not_numstat() {
+ // Not a numstat line
+ assert_eq!(
+ WorktreeSkimItem::parse_numstat_line("* abc1234 Fix bug"),
+ None
+ );
+ assert_eq!(WorktreeSkimItem::parse_numstat_line(""), None);
+ assert_eq!(WorktreeSkimItem::parse_numstat_line("regular text"), None);
+ }
}
diff --git a/tests/integration_tests/select.rs b/tests/integration_tests/select.rs
index 8c467771f..9b7f08fc9 100644
--- a/tests/integration_tests/select.rs
+++ b/tests/integration_tests/select.rs
@@ -482,7 +482,7 @@ fn test_select_preview_panel_log(mut repo: TestRepo) {
feature_path.to_str().unwrap(),
"commit",
"-m",
- &format!("Add file {i} with important changes"),
+ &format!("Add file {i} with content"),
])
.output()
.unwrap();
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_log.snap b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_log.snap
index 67e6e5cde..804f919b5 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_log.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_log.snap
@@ -5,12 +5,12 @@ expression: normalized
> [QUERY] │[PREVIEW_HEADER]
Branch Status HEAD± main↕ Path R│Enter: switch | Esc: cancel | ctrl-u/d: scroll | alt-p: tog
> + feature ↑ ↑5 ./repo.feature ..│
- │* 4ac610b 1d (feature) Add file 5 with important changes
- │* f68805a 1d Add file 4 with important changes
- │* ae793ef 1d Add file 3 with important changes
- │* 258fa75 1d Add file 2 with important changes
- │* d3b6cb8 1d Add file 1 with important changes
- │* a1e809f 1d Initial commit
+ │* a7f9ebb +1 1d (feature) Add file 5 with content
+ │* cd19d36 +1 1d Add file 4 with content
+ │* 17c13c5 +1 1d Add file 3 with content
+ │* fad018c +1 1d Add file 2 with content
+ │* 8df4920 +1 1d Add file 1 with content
+ │* a1e809f +3 1d Initial commit
│
│
│
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_main_diff.snap b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_main_diff.snap
index d32114f93..163918e36 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_main_diff.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_main_diff.snap
@@ -8,8 +8,6 @@ expression: normalized
│ feature_code.rs | 6 ++++++
│ tests.rs | 4 ++++
│ 2 files changed, 10 insertions(+)
- │
- │
│diff --git a/feature_code.rs b/feature_code.rs
│new file mode 100644
│index 0000000..b8bd34c
@@ -29,3 +27,5 @@ expression: normalized
│+++ b/tests.rs
│@@ -0,0 +1,4 @@
│+#[test]
+ │+fn test_new_feature() {
+ │+ assert_eq!(42 * 2, 84);
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_uncommitted.snap b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_uncommitted.snap
index ea8d2cfd3..52438832b 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_uncommitted.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__select__select_preview_uncommitted.snap
@@ -7,8 +7,6 @@ expression: normalized
> + feature ! ↑ +3 -1 ↑1 ./repo.feature ..│
│ tracked.txt | 4 +++-
│ 1 file changed, 3 insertions(+), 1 deletion(-)
- │
- │
│diff --git a/tracked.txt b/tracked.txt
│index 9415d49..1142e4d 100644
│--- a/tracked.txt
@@ -29,3 +27,5 @@ expression: normalized
│
│
│
+ │
+ │