Skip to content

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

perf: switch diff stats from --numstat to --shortstat (#1917)

Maximilian Roos6326068b806a
diff --git a/CLAUDE.md b/CLAUDE.md
index 4d52b7939..20bdbb73f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -250,7 +250,7 @@ if msg.contains("no merge base") { return Ok(true); }
| Tool | Fragile | Structured |
|------|---------|------------|
-| `git diff` | `--shortstat` (localized) | `--numstat` |
+| `git diff` | `--stat` (localized) | `--numstat`, `--shortstat` (markers `(+)`/`(-)` are hardcoded) |
| `git status` | default | `--porcelain=v2` |
| `git merge-base` | error messages | exit codes |
| `gh` / `glab` | default | `--json` |
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index b4f014ee2..4ef2f2086 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -128,6 +128,7 @@ SELECT
WHEN name LIKE '%is-ancestor%' THEN 'is_ancestor'
WHEN name LIKE '%diff --name%' THEN 'file_changes'
WHEN name LIKE '%diff --numstat%' THEN 'diff_numstat'
+ WHEN name LIKE '%diff --shortstat%' THEN 'diff_shortstat'
WHEN name LIKE '%diff --cached%' THEN 'diff_cached'
WHEN name LIKE '% diff main...%' THEN 'diff_3dot'
WHEN name LIKE '% diff HEAD%' THEN 'diff_wt'
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index ecbe3d004..076652693 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -53,8 +53,8 @@
//! For each worktree, we execute:
//! - `git status --porcelain` - Working tree state (uses index cache)
//! - `git rev-list --count <base>..<head>` - Ahead/behind counts (uses commit graph)
-//! - `git diff --numstat HEAD` - Working tree line diffs (uses index + tree objects)
-//! - `git diff --numstat <base>...<head>` - Branch line diffs (uses tree objects)
+//! - `git diff --shortstat HEAD` - Working tree line diffs (uses index + tree objects)
+//! - `git diff --shortstat <base>...<head>` - Branch line diffs (uses tree objects)
//! - `git rev-parse <ref>` - Ref resolution (uses ref cache)
//!
//! Plus one global command:
@@ -111,7 +111,7 @@
//! Bottlenecks:
//! 1. `git status --porcelain` - Slowest when index is cold or many files changed
//! 2. `git rev-list --count` - Slow without commit graph in repos with deep history
-//! 3. `git diff --numstat` - Slow for large diffs or when pack files aren't cached
+//! 3. `git diff --shortstat` - Slow for large diffs or when pack files aren't cached
//!
//! Optimization tips:
//! - Run `git commit-graph write --reachable --changed-paths` to speed up commit counting
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 6dbfc6010..efb888f96 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -38,18 +38,17 @@ pub fn parse_numstat_line(line: &str) -> Option<(usize, usize)> {
}
impl LineDiff {
- /// Parse `git diff --numstat` output into aggregated line totals.
- pub fn from_numstat(output: &str) -> anyhow::Result<Self> {
- let mut totals = LineDiff::default();
-
- for line in output.lines() {
- if let Some((added, deleted)) = parse_numstat_line(line) {
- totals.added += added;
- totals.deleted += deleted;
- }
- }
-
- Ok(totals)
+ /// Parse `git diff --shortstat` output into line totals.
+ ///
+ /// Shortstat produces a single line like:
+ /// ` 3 files changed, 45 insertions(+), 12 deletions(-)`
+ /// with optional parts omitted when zero. Extracts numbers by position
+ /// relative to the `(+)` and `(-)` markers, which are locale-independent.
+ pub fn from_shortstat(output: &str) -> Self {
+ parse_shortstat(output).map_or(Self::default(), |(_, ins, del)| Self {
+ added: ins,
+ deleted: del,
+ })
}
pub fn is_empty(&self) -> bool {
@@ -80,21 +79,48 @@ pub(crate) struct DiffStats {
pub deletions: usize,
}
-impl DiffStats {
- /// Construct stats from `git diff --numstat` output.
- pub fn from_numstat(output: &str) -> Self {
- let mut stats = Self::default();
- for line in output.lines() {
- if let Some((added, deleted)) = parse_numstat_line(line) {
- stats.files += 1;
- stats.insertions += added;
- stats.deletions += deleted;
- } else if !line.trim().is_empty() {
- // Binary file (shows as "-\t-\tfilename") - count file but not lines
- stats.files += 1;
- }
+/// Parse `git diff --shortstat` output into (files, insertions, deletions).
+///
+/// The format is: ` N file(s) changed, N insertion(s)(+), N deletion(s)(-)`
+/// with optional parts omitted when zero. The `(+)` and `(-)` markers are
+/// hardcoded in git's C source (`diff.c`) and not subject to localization.
+fn parse_shortstat(output: &str) -> Option<(usize, usize, usize)> {
+ let line = output.trim();
+ if line.is_empty() {
+ return None;
+ }
+
+ let mut files = 0;
+ let mut insertions = 0;
+ let mut deletions = 0;
+
+ // Split on commas: "N file(s) changed", "N insertion(s)(+)", "N deletion(s)(-)"
+ for (i, part) in line.split(',').enumerate() {
+ let num = part
+ .split_whitespace()
+ .find_map(|w| w.parse::<usize>().ok())
+ .unwrap_or(0);
+
+ if i == 0 {
+ files = num;
+ } else if part.contains("(+)") {
+ insertions = num;
+ } else if part.contains("(-)") {
+ deletions = num;
}
- stats
+ }
+
+ Some((files, insertions, deletions))
+}
+
+impl DiffStats {
+ /// Construct stats from `git diff --shortstat` output.
+ pub fn from_shortstat(output: &str) -> Self {
+ parse_shortstat(output).map_or(Self::default(), |(files, ins, del)| Self {
+ files,
+ insertions: ins,
+ deletions: del,
+ })
}
/// Format stats as a summary string (e.g., "3 files, +45, -12").
@@ -160,74 +186,6 @@ mod tests {
assert_eq!(tuple, (10, 5));
}
- #[test]
- fn test_line_diff_from_numstat_empty() {
- let result = LineDiff::from_numstat("").unwrap();
- assert!(result.is_empty());
- }
-
- #[test]
- fn test_line_diff_from_numstat_single_file() {
- let output = "10\t5\tsrc/main.rs";
- let result = LineDiff::from_numstat(output).unwrap();
- assert_eq!(result.added, 10);
- assert_eq!(result.deleted, 5);
- }
-
- #[test]
- fn test_line_diff_from_numstat_multiple_files() {
- let output = "10\t5\tsrc/main.rs\n20\t3\tsrc/lib.rs\n1\t0\tCargo.toml";
- let result = LineDiff::from_numstat(output).unwrap();
- assert_eq!(result.added, 31); // 10 + 20 + 1
- assert_eq!(result.deleted, 8); // 5 + 3 + 0
- }
-
- #[test]
- fn test_line_diff_from_numstat_binary_file() {
- // Binary files show "-" for added/deleted
- let output = "-\t-\timage.png";
- let result = LineDiff::from_numstat(output).unwrap();
- assert!(result.is_empty());
- }
-
- #[test]
- fn test_line_diff_from_numstat_mixed_binary_and_text() {
- let output = "10\t5\tsrc/main.rs\n-\t-\timage.png\n3\t2\tREADME.md";
- let result = LineDiff::from_numstat(output).unwrap();
- assert_eq!(result.added, 13); // 10 + 3, skips binary
- assert_eq!(result.deleted, 7); // 5 + 2, skips binary
- }
-
- #[test]
- fn test_line_diff_from_numstat_empty_lines() {
- let output = "\n10\t5\tsrc/main.rs\n\n";
- let result = LineDiff::from_numstat(output).unwrap();
- assert_eq!(result.added, 10);
- assert_eq!(result.deleted, 5);
- }
-
- #[test]
- fn test_line_diff_from_numstat_malformed_line_missing_deleted() {
- // Line with only added count (missing tab and deleted)
- let output = "10";
- let result = LineDiff::from_numstat(output).unwrap();
- assert!(result.is_empty()); // Should skip malformed line
- }
-
- #[test]
- fn test_line_diff_from_numstat_non_numeric_added() {
- let output = "abc\t5\tsrc/main.rs";
- let result = LineDiff::from_numstat(output).unwrap();
- assert!(result.is_empty()); // Should skip non-numeric
- }
-
- #[test]
- fn test_line_diff_from_numstat_non_numeric_deleted() {
- let output = "10\tabc\tsrc/main.rs";
- let result = LineDiff::from_numstat(output).unwrap();
- assert!(result.is_empty()); // Should skip non-numeric
- }
-
// ============================================================================
// parse_numstat_line Tests
// ============================================================================
@@ -319,49 +277,80 @@ mod tests {
}
// ============================================================================
- // DiffStats::from_numstat Tests
+ // parse_shortstat / from_shortstat Tests
// ============================================================================
#[test]
- fn test_diff_stats_from_numstat_empty() {
- let stats = DiffStats::from_numstat("");
- assert_eq!(stats.files, 0);
- assert_eq!(stats.insertions, 0);
- assert_eq!(stats.deletions, 0);
+ fn test_parse_shortstat_all_parts() {
+ let output = " 23 files changed, 624 insertions(+), 160 deletions(-)";
+ let (files, ins, del) = parse_shortstat(output).unwrap();
+ assert_eq!(files, 23);
+ assert_eq!(ins, 624);
+ assert_eq!(del, 160);
}
#[test]
- fn test_diff_stats_from_numstat_single_file() {
- let stats = DiffStats::from_numstat("45\t12\tpath/to/file.rs");
- assert_eq!(stats.files, 1);
- assert_eq!(stats.insertions, 45);
- assert_eq!(stats.deletions, 12);
+ fn test_parse_shortstat_insertions_only() {
+ let output = " 1 file changed, 6 insertions(+)";
+ let (files, ins, del) = parse_shortstat(output).unwrap();
+ assert_eq!(files, 1);
+ assert_eq!(ins, 6);
+ assert_eq!(del, 0);
+ }
+
+ #[test]
+ fn test_parse_shortstat_deletions_only() {
+ let output = " 2 files changed, 10 deletions(-)";
+ let (files, ins, del) = parse_shortstat(output).unwrap();
+ assert_eq!(files, 2);
+ assert_eq!(ins, 0);
+ assert_eq!(del, 10);
}
#[test]
- fn test_diff_stats_from_numstat_multiple_files() {
- let output = "10\t5\tsrc/main.rs\n20\t3\tsrc/lib.rs\n15\t4\ttests/test.rs";
- let stats = DiffStats::from_numstat(output);
+ fn test_parse_shortstat_empty() {
+ assert_eq!(parse_shortstat(""), None);
+ assert_eq!(parse_shortstat(" "), None);
+ assert_eq!(parse_shortstat("\n"), None);
+ }
+
+ #[test]
+ fn test_parse_shortstat_single_file_singular() {
+ let output = " 1 file changed, 1 insertion(+), 1 deletion(-)";
+ let (files, ins, del) = parse_shortstat(output).unwrap();
+ assert_eq!(files, 1);
+ assert_eq!(ins, 1);
+ assert_eq!(del, 1);
+ }
+
+ #[test]
+ fn test_line_diff_from_shortstat() {
+ let output = " 5 files changed, 100 insertions(+), 50 deletions(-)";
+ let diff = LineDiff::from_shortstat(output);
+ assert_eq!(diff.added, 100);
+ assert_eq!(diff.deleted, 50);
+ }
+
+ #[test]
+ fn test_line_diff_from_shortstat_empty() {
+ let diff = LineDiff::from_shortstat("");
+ assert!(diff.is_empty());
+ }
+
+ #[test]
+ fn test_diff_stats_from_shortstat() {
+ let output = " 3 files changed, 45 insertions(+), 12 deletions(-)";
+ let stats = DiffStats::from_shortstat(output);
assert_eq!(stats.files, 3);
assert_eq!(stats.insertions, 45);
assert_eq!(stats.deletions, 12);
}
#[test]
- fn test_diff_stats_from_numstat_binary_file() {
- // Binary files show as "-" for both counts - file counted, no line stats
- let stats = DiffStats::from_numstat("-\t-\timage.png");
- assert_eq!(stats.files, 1);
+ fn test_diff_stats_from_shortstat_empty() {
+ let stats = DiffStats::from_shortstat("");
+ assert_eq!(stats.files, 0);
assert_eq!(stats.insertions, 0);
assert_eq!(stats.deletions, 0);
}
-
- #[test]
- fn test_diff_stats_from_numstat_mixed_binary_and_text() {
- let output = "10\t5\tsrc/main.rs\n-\t-\tassets/logo.png\n20\t0\tsrc/lib.rs";
- let stats = DiffStats::from_numstat(output);
- assert_eq!(stats.files, 3);
- assert_eq!(stats.insertions, 30);
- assert_eq!(stats.deletions, 5);
- }
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 6ea3eb06d..a83dc6107 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -25,7 +25,7 @@ mod test;
//
// Heavy operations protected:
// - git rev-list --count (accesses commit-graph via mmap)
-// - git diff --numstat (accesses pack files and indexes via mmap)
+// - git diff --shortstat (accesses pack files and indexes via mmap)
use crate::sync::Semaphore;
use std::sync::LazyLock;
static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index b725695e1..4429d8dfb 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -296,7 +296,7 @@ impl Repository {
// Use two-dot syntax with the cached merge-base
let range = format!("{}..{}", merge_base, head);
- let mut args = vec!["diff", "--numstat", &range];
+ let mut args = vec!["diff", "--shortstat", &range];
let sparse_paths = self.sparse_checkout_paths();
if !sparse_paths.is_empty() {
@@ -305,7 +305,7 @@ impl Repository {
}
let stdout = self.run_command(&args)?;
- LineDiff::from_numstat(&stdout)
+ Ok(LineDiff::from_shortstat(&stdout))
}
/// Get formatted diff stats summary for display.
@@ -313,24 +313,11 @@ impl Repository {
/// Returns a vector of formatted strings like ["3 files", "+45", "-12"].
/// Returns empty vector if diff command fails or produces no output.
///
- /// Callers should pass `--shortstat` in args for compatibility; this method
- /// internally replaces it with `--numstat` for locale-independent parsing.
+ /// Callers pass args including `--shortstat` which produces a single summary line.
pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {
- // Replace --shortstat with --numstat for locale-independent parsing
- let args: Vec<&str> = args
- .iter()
- .map(|&arg| {
- if arg == "--shortstat" {
- "--numstat"
- } else {
- arg
- }
- })
- .collect();
-
- self.run_command(&args)
+ self.run_command(args)
.ok()
- .map(|output| DiffStats::from_numstat(&output).format_summary())
+ .map(|output| DiffStats::from_shortstat(&output).format_summary())
.unwrap_or_default()
}
}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 2939da08d..fc3865497 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -250,8 +250,8 @@ impl<'a> WorkingTree<'a> {
/// Get line diff statistics for working tree changes (unstaged + staged).
pub fn working_tree_diff_stats(&self) -> anyhow::Result<LineDiff> {
- let stdout = self.run_command(&["diff", "--numstat", "HEAD"])?;
- LineDiff::from_numstat(&stdout)
+ let stdout = self.run_command(&["diff", "--shortstat", "HEAD"])?;
+ Ok(LineDiff::from_shortstat(&stdout))
}
/// Determine whether there are staged changes in the index.
diff --git a/src/git/test.rs b/src/git/test.rs
index 37017ef77..5c8ff4259 100644
--- a/src/git/test.rs
+++ b/src/git/test.rs
@@ -174,30 +174,23 @@ fn test_parse_local_default_branch_empty_remote() {
assert_eq!(result.unwrap(), "weird/branch");
}
-// Tests for LineDiff::from_numstat
+// Tests for LineDiff::from_shortstat
#[rstest]
-#[case::normal("10\t5\tfile1.rs\n3\t2\tfile2.rs\n", 13, 7)]
+#[case::all_parts(" 23 files changed, 624 insertions(+), 160 deletions(-)", 624, 160)]
+#[case::insertions_only(" 1 file changed, 6 insertions(+)", 6, 0)]
+#[case::deletions_only(" 2 files changed, 10 deletions(-)", 0, 10)]
#[case::empty("", 0, 0)]
-#[case::binary_files("10\t5\tfile1.rs\n-\t-\timage.png\n3\t2\tfile2.rs\n", 13, 7)]
-#[case::mixed_binary("10\t-\tfile1.rs\n-\t5\tfile2.rs\n", 0, 0)]
-#[case::empty_lines("10\t5\tfile1.rs\n\n3\t2\tfile2.rs\n\n", 13, 7)]
-#[case::missing_deleted("10\tfile.rs\n", 0, 0)]
-#[case::no_tabs("file.rs\n", 0, 0)]
-#[case::non_numeric_added("abc\t5\tfile.rs\n", 0, 0)]
-#[case::non_numeric_deleted("5\txyz\tfile.rs\n", 0, 0)]
-#[case::zero_values("0\t0\tfile.rs\n", 0, 0)]
-fn test_line_diff_from_numstat(
+#[case::whitespace(" \n ", 0, 0)]
+#[case::singular(" 1 file changed, 1 insertion(+), 1 deletion(-)", 1, 1)]
+fn test_line_diff_from_shortstat(
#[case] input: &str,
#[case] expected_added: usize,
#[case] expected_deleted: usize,
) {
- let result = LineDiff::from_numstat(input);
-
- assert!(result.is_ok());
- let (added, deleted): (usize, usize) = result.unwrap().into();
- assert_eq!(added, expected_added);
- assert_eq!(deleted, expected_deleted);
+ let diff = LineDiff::from_shortstat(input);
+ assert_eq!(diff.added, expected_added);
+ assert_eq!(diff.deleted, expected_deleted);
}
#[test]