1mod commit;
2mod diff;
3mod log;
4mod parser;
5mod status;
6
7use parser::extract_git_subcommand;
8
9macro_rules! static_regex {
10 ($pattern:expr_2021) => {{
11 static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
12 RE.get_or_init(|| {
13 regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
14 })
15 }};
16}
17
18fn status_branch_re() -> &'static regex::Regex {
19 static_regex!(r"On branch (\S+)")
20}
21fn ahead_re() -> &'static regex::Regex {
22 static_regex!(r"ahead of .+ by (\d+) commit")
23}
24fn commit_hash_re() -> &'static regex::Regex {
25 static_regex!(r"\[([\w/.:-]+)\s+([a-f0-9]+)\]")
26}
27fn insertions_re() -> &'static regex::Regex {
28 static_regex!(r"(\d+) insertions?\(\+\)")
29}
30fn deletions_re() -> &'static regex::Regex {
31 static_regex!(r"(\d+) deletions?\(-\)")
32}
33fn files_changed_re() -> &'static regex::Regex {
34 static_regex!(r"(\d+) files? changed")
35}
36fn shortstat_line_re() -> &'static regex::Regex {
39 static_regex!(
40 r"^ \d+ files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?\s*$"
41 )
42}
43fn numstat_row_re() -> &'static regex::Regex {
45 static_regex!(r"^(\d+|-)\t(\d+|-)\t")
46}
47fn clone_objects_re() -> &'static regex::Regex {
48 static_regex!(r"Receiving objects:.*?(\d+)")
49}
50fn stash_re() -> &'static regex::Regex {
51 static_regex!(r"stash@\{(\d+)\}:\s*(.+)")
52}
53
54fn is_diff_or_stat_line(line: &str) -> bool {
55 let t = line.trim();
56 t.starts_with("diff --git")
57 || t.starts_with("index ")
58 || t.starts_with("--- a/")
59 || t.starts_with("+++ b/")
60 || t.starts_with("@@ ")
61 || t.starts_with("Binary files")
62 || t.starts_with("new file mode")
63 || t.starts_with("deleted file mode")
64 || t.starts_with("old mode")
65 || t.starts_with("new mode")
66 || t.starts_with("similarity index")
67 || t.starts_with("rename from")
68 || t.starts_with("rename to")
69 || t.starts_with("copy from")
70 || t.starts_with("copy to")
71 || (t.starts_with('+') && !t.starts_with("+++"))
72 || (t.starts_with('-') && !t.starts_with("---"))
73 || (t.contains(" | ") && t.chars().any(|c| c == '+' || c == '-'))
74}
75
76fn extract_change_stats(output: &str) -> String {
77 let files = files_changed_re()
78 .captures(output)
79 .and_then(|c| c[1].parse::<u32>().ok())
80 .unwrap_or(0);
81 let ins = insertions_re()
82 .captures(output)
83 .and_then(|c| c[1].parse::<u32>().ok())
84 .unwrap_or(0);
85 let del = deletions_re()
86 .captures(output)
87 .and_then(|c| c[1].parse::<u32>().ok())
88 .unwrap_or(0);
89
90 if files > 0 || ins > 0 || del > 0 {
91 format!("{files} files, +{ins}/-{del}")
92 } else {
93 String::new()
94 }
95}
96
97fn compact_lines(text: &str, max: usize) -> String {
98 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
99 if lines.len() <= max {
100 return lines.join("\n");
101 }
102 format!(
103 "{}\n... ({} more lines)",
104 lines[..max].join("\n"),
105 lines.len() - max
106 )
107}
108
109fn show_requests_blob(command: &str) -> bool {
115 command.split_whitespace().any(|arg| {
116 let arg = arg.trim_matches(['\'', '"']);
117 !arg.starts_with('-')
118 && arg
119 .split_once(':')
120 .is_some_and(|(revision, path)| !revision.is_empty() && !path.is_empty())
121 })
122}
123
124pub fn compress(command: &str, output: &str) -> Option<String> {
125 let sub = extract_git_subcommand(command)?;
126 match sub {
127 "status" => Some(status::compress_status(output)),
128 "log" => Some(log::compress_log(command, output)),
129 "diff" => Some(diff::compress_diff(output)),
130 "add" => Some(commit::compress_add(output)),
131 "commit" => Some(commit::compress_commit(output)),
132 "push" => Some(commit::compress_push(output)),
133 "pull" => Some(commit::compress_pull(output)),
134 "fetch" => Some(commit::compress_fetch(output)),
135 "clone" => Some(commit::compress_clone(output)),
136 "branch" => Some(commit::compress_branch(output)),
137 "checkout" | "switch" => Some(commit::compress_checkout(output)),
138 "merge" => Some(commit::compress_merge(output)),
139 "stash" => {
140 if command.contains("stash show") || command.contains("show stash") {
141 return Some(commit::compress_show(output));
142 }
143 Some(commit::compress_stash(output))
144 }
145 "tag" => Some(commit::compress_tag(output)),
146 "reset" => Some(commit::compress_reset(output)),
147 "remote" => {
148 if command.contains("remote add") {
149 return Some(commit::compress_add(output));
150 }
151 Some(commit::compress_remote(output))
152 }
153 "blame" => Some(commit::compress_blame(output)),
154 "cherry-pick" => Some(commit::compress_cherry_pick(output)),
155 "show" if show_requests_blob(command) => Some(output.to_string()),
156 "show" => Some(commit::compress_show(output)),
157 "rebase" => Some(commit::compress_rebase(output)),
158 "submodule" => Some(commit::compress_submodule(output)),
159 "worktree" => Some(commit::compress_worktree(output)),
160 "bisect" => Some(commit::compress_bisect(output)),
161 _ => None,
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn git_status_compresses() {
171 let output = "On branch main\nYour branch is up to date with 'origin/main'.\n\nChanges not staged for commit:\n (use \"git add <file>...\" to update what will be committed)\n\n\tmodified: src/main.rs\n\tmodified: src/lib.rs\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\n";
172 let result = compress("git status", output).unwrap();
173 assert!(result.contains("main"), "should contain branch name");
174 assert!(result.contains("main.rs"), "should list modified files");
175 assert!(result.len() < output.len(), "should be shorter than input");
176 }
177
178 #[test]
179 fn git_add_compresses_to_ok() {
180 let result = compress("git add .", "").unwrap();
181 assert!(result.contains("ok"), "git add should compress to 'ok'");
182 }
183
184 #[test]
189 fn git_add_does_not_label_line_count_as_files() {
190 let output = "[main abc1234] fix: x\n 1 file changed, 1 insertion(+)\nhook line\nanother\nmore\nlines\nseven\n";
191 let result = compress("git add . && git commit -m 'x'", output).unwrap();
192 assert!(
193 !result.contains("files)"),
194 "line count must not be presented as a file count: {result}"
195 );
196 }
197
198 #[test]
199 fn git_add_verbose_counts_real_added_files() {
200 let output = "add 'a.rs'\nadd 'b.rs'\nadd 'c.rs'\nadd 'd.rs'\n";
201 let result = compress("git add -v .", output).unwrap();
202 assert!(
203 result.contains("+4 files"),
204 "verbose add lines are the real file count: {result}"
205 );
206 }
207
208 #[test]
209 fn git_commit_extracts_hash() {
210 let output =
211 "[main abc1234] fix: resolve bug\n 2 files changed, 10 insertions(+), 3 deletions(-)\n";
212 let result = compress("git commit -m 'fix'", output).unwrap();
213 assert!(result.contains("abc1234"), "should extract commit hash");
214 }
215
216 #[test]
217 fn git_push_compresses() {
218 let output = "Enumerating objects: 5, done.\nCounting objects: 100% (5/5), done.\nDelta compression using up to 8 threads\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 1.2 KiB | 1.2 MiB/s, done.\nTotal 3 (delta 2), reused 0 (delta 0)\nTo github.com:user/repo.git\n abc1234..def5678 main -> main\n";
219 let result = compress("git push", output).unwrap();
220 assert!(result.len() < output.len(), "should compress push output");
221 }
222
223 #[test]
224 fn git_log_compresses() {
225 let output = "commit abc1234567890\nAuthor: User <user@email.com>\nDate: Mon Mar 25 10:00:00 2026 +0100\n\n feat: add feature\n\ncommit def4567890abc\nAuthor: User <user@email.com>\nDate: Sun Mar 24 09:00:00 2026 +0100\n\n fix: resolve issue\n";
226 let result = compress("git log", output).unwrap();
227 assert!(result.len() < output.len(), "should compress log output");
228 }
229
230 #[test]
231 fn git_log_oneline_truncates_long() {
232 let lines: Vec<String> = (0..150)
233 .map(|i| format!("abc{i:04} feat: commit number {i}"))
234 .collect();
235 let output = lines.join("\n");
236 let result = compress("git log --oneline", &output).unwrap();
237 assert!(
238 result.contains("... (50 more commits"),
239 "should truncate to 100 entries"
240 );
241 assert!(
242 result.lines().count() <= 102,
243 "should have at most 101 lines (100 + summary)"
244 );
245 }
246
247 #[test]
248 fn git_log_oneline_short_unchanged() {
249 let output = "abc1234 feat: one\ndef5678 fix: two\nghi9012 docs: three";
250 let result = compress("git log --oneline", output).unwrap();
251 assert_eq!(result, output, "short oneline should pass through");
252 }
253
254 #[test]
255 fn git_log_standard_truncates_long() {
256 let mut output = String::new();
257 for i in 0..130 {
258 output.push_str(&format!(
259 "commit {i:07}abc1234\nAuthor: U <u@e.com>\nDate: Mon\n\n msg {i}\n\n"
260 ));
261 }
262 let result = compress("git log", &output).unwrap();
263 assert!(
264 result.contains("... (30 more commits"),
265 "should truncate standard log at 100"
266 );
267 }
268
269 #[test]
270 fn git_diff_compresses() {
271 let output = "diff --git a/src/main.rs b/src/main.rs\nindex abc1234..def5678 100644\n--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,4 @@\n fn main() {\n+ println!(\"hello\");\n let x = 1;\n }";
272 let result = compress("git diff", output).unwrap();
273 assert!(result.contains("main.rs"), "should reference changed file");
274 }
275
276 #[test]
277 fn git_diff_stat_preserves_all_files() {
278 let output = " website/src/i18n/locales/en.json | 3 +-\n website/src/page-templates/DocsToolsCorePage.astro | 37 ++------\n .../page-templates/DocsToolsIntelligencePage.astro | 105 +++++----------------\n .../src/page-templates/DocsToolsMemoryPage.astro | 29 ++----\n .../src/page-templates/DocsToolsSessionPage.astro | 43 ++-------\n 5 files changed, 45 insertions(+), 172 deletions(-)\n";
279 let result = compress("git diff --stat", output).unwrap();
280 assert!(
281 result.contains("en.json"),
282 "must keep en.json, got: {result}"
283 );
284 assert!(
285 result.contains("DocsToolsCorePage"),
286 "must keep CorePage, got: {result}"
287 );
288 assert!(
289 result.contains("DocsToolsIntelligencePage"),
290 "must keep IntelligencePage, got: {result}"
291 );
292 assert!(
293 result.contains("DocsToolsMemoryPage"),
294 "must keep MemoryPage, got: {result}"
295 );
296 assert!(
297 result.contains("DocsToolsSessionPage"),
298 "must keep SessionPage, got: {result}"
299 );
300 assert!(
301 result.contains("5 files changed"),
302 "must keep summary line, got: {result}"
303 );
304 }
305
306 #[test]
307 fn git_diff_cached_stat_preserves_all_files() {
308 let output = " src/a.rs | 10 ++++------\n src/b.rs | 3 ++-\n src/c.rs | 7 +++----\n src/d.rs | 1 +\n 4 files changed, 9 insertions(+), 12 deletions(-)\n";
309 let result = compress("git diff --cached --stat", output).unwrap();
310 assert!(result.contains("a.rs"), "must keep a.rs, got: {result}");
311 assert!(result.contains("d.rs"), "must keep d.rs, got: {result}");
312 assert!(
313 result.contains("4 files changed"),
314 "must keep summary, got: {result}"
315 );
316 }
317
318 #[test]
319 fn git_diff_shortstat_preserved() {
320 let output = " 5 files changed, 45 insertions(+), 172 deletions(-)\n";
321 let result = compress("git diff --shortstat", output).unwrap();
322 assert!(
323 result.contains("5 files changed"),
324 "shortstat must pass through, got: {result}"
325 );
326 }
327
328 #[test]
329 fn git_push_preserves_pipeline_url() {
330 let output = "Enumerating objects: 5, done.\nCounting objects: 100% (5/5), done.\nDelta compression using up to 8 threads\nCompressing objects: 100% (3/3), done.\nWriting objects: 100% (3/3), 1.2 KiB | 1.2 MiB/s, done.\nTotal 3 (delta 2), reused 0 (delta 0)\nremote:\nremote: To create a merge request for main, visit:\nremote: https://gitlab.com/user/repo/-/merge_requests/new?source=main\nremote:\nremote: View pipeline for this push:\nremote: https://gitlab.com/user/repo/-/pipelines/12345\nremote:\nTo gitlab.com:user/repo.git\n abc1234..def5678 main -> main\n";
331 let result = compress("git push", output).unwrap();
332 assert!(
333 result.contains("pipeline"),
334 "should preserve pipeline URL, got: {result}"
335 );
336 assert!(
337 result.contains("merge_request"),
338 "should preserve merge request URL"
339 );
340 assert!(result.contains("->"), "should contain ref update line");
341 }
342
343 #[test]
344 fn git_push_preserves_github_pr_url() {
345 let output = "Enumerating objects: 5, done.\nremote:\nremote: Create a pull request for 'feature' on GitHub by visiting:\nremote: https://github.com/user/repo/pull/new/feature\nremote:\nTo github.com:user/repo.git\n abc1234..def5678 feature -> feature\n";
346 let result = compress("git push", output).unwrap();
347 assert!(
348 result.contains("pull/"),
349 "should preserve GitHub PR URL, got: {result}"
350 );
351 }
352
353 #[test]
354 fn git_commit_preserves_hook_output() {
355 let output = "Running pre-commit hooks...\ncheck-yaml..........passed\ncheck-json..........passed\nruff.................failed\nfixing src/app.py\n[main abc1234] fix: resolve bug\n 2 files changed, 10 insertions(+), 3 deletions(-)\n";
356 let result = compress("git commit -m 'fix'", output).unwrap();
357 assert!(
358 result.contains("ruff"),
359 "should preserve hook output, got: {result}"
360 );
361 assert!(
362 result.contains("abc1234"),
363 "should still extract commit hash"
364 );
365 }
366
367 #[test]
368 fn git_commit_no_hooks() {
369 let output =
370 "[main abc1234] fix: resolve bug\n 2 files changed, 10 insertions(+), 3 deletions(-)\n";
371 let result = compress("git commit -m 'fix'", output).unwrap();
372 assert!(result.contains("abc1234"), "should extract commit hash");
373 assert!(
374 !result.contains("hook"),
375 "should not mention hooks when none present"
376 );
377 }
378
379 #[test]
380 fn git_log_with_patch_keeps_hunks_for_few_commits() {
381 let output = "commit abc1234567890\nAuthor: User <user@email.com>\nDate: Mon Mar 25 10:00:00 2026 +0100\n\n feat: add feature\n\ndiff --git a/src/main.rs b/src/main.rs\nindex abc1234..def5678 100644\n--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,4 @@\n fn main() {\n+ println!(\"hello\");\n let x = 1;\n }\n\ncommit def4567890abc\nAuthor: User <user@email.com>\nDate: Sun Mar 24 09:00:00 2026 +0100\n\n fix: resolve issue\n\ndiff --git a/src/lib.rs b/src/lib.rs\nindex 111..222 100644\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1 +1,2 @@\n+pub fn helper() {}\n";
382 let result = compress("git log -p", output).unwrap();
383 assert!(
384 result.contains("println"),
385 "1-3 commits with -p should KEEP diff hunks, got: {result}"
386 );
387 assert!(result.contains("abc1234"), "should contain commit hash");
388 assert!(
389 result.contains("feat: add feature"),
390 "should contain commit message"
391 );
392 }
393
394 #[test]
395 fn git_log_with_patch_summarizes_many_commits() {
396 let mut output = String::new();
397 for i in 0..10 {
398 output.push_str(&format!(
399 "commit {i:07}abc1234\nAuthor: U <u@e.com>\nDate: Mon\n\n msg {i}\n\ndiff --git a/src/f{i}.rs b/src/f{i}.rs\nindex 111..222 100644\n--- a/src/f{i}.rs\n+++ b/src/f{i}.rs\n@@ -1 +1,2 @@\n+line {i}\n\n"
400 ));
401 }
402 let result = compress("git log -p", &output).unwrap();
403 assert!(
404 result.contains("msg 0"),
405 "newest commit message should be present"
406 );
407 assert!(
408 result.contains("+line 0"),
409 "newest commit should have hunks preserved"
410 );
411 assert!(
412 result.len() < output.len(),
413 "should be compressed ({} vs {})",
414 result.len(),
415 output.len()
416 );
417 }
418
419 #[test]
420 fn git_log_with_stat_filters_stat_content() {
421 let mut output = String::new();
422 for i in 0..5 {
423 output.push_str(&format!(
424 "commit {i:07}abc1234\nAuthor: U <u@e.com>\nDate: Mon\n\n msg {i}\n\n src/file{i}.rs | 10 ++++------\n 1 file changed, 4 insertions(+), 6 deletions(-)\n\n"
425 ));
426 }
427 let result = compress("git log --stat", &output).unwrap();
428 assert!(
429 result.len() < output.len() / 2,
430 "stat output should be compressed ({} vs {})",
431 result.len(),
432 output.len()
433 );
434 }
435
436 #[test]
437 fn git_commit_with_feature_branch() {
438 let output = "[feature/my-branch abc1234] feat: add new thing\n 3 files changed, 20 insertions(+), 5 deletions(-)\n";
439 let result = compress("git commit -m 'feat'", output).unwrap();
440 assert!(
441 result.contains("abc1234"),
442 "should extract hash from feature branch, got: {result}"
443 );
444 assert!(
445 result.contains("feature/my-branch"),
446 "should preserve branch name, got: {result}"
447 );
448 }
449
450 #[test]
451 fn git_commit_many_hooks_compressed() {
452 let mut output = String::new();
453 for i in 0..30 {
454 output.push_str(&format!("check-{i}..........passed\n"));
455 }
456 output.push_str("[main abc1234] fix: resolve bug\n 1 file changed, 1 insertion(+)\n");
457 let result = compress("git commit -m 'fix'", &output).unwrap();
458 assert!(result.contains("abc1234"), "should contain commit hash");
459 assert!(
460 result.contains("hooks passed"),
461 "should summarize passed hooks, got: {result}"
462 );
463 assert!(
464 result.len() < output.len() / 2,
465 "should compress verbose hook output ({} vs {})",
466 result.len(),
467 output.len()
468 );
469 }
470
471 #[test]
472 fn stash_push_preserves_short_message() {
473 let output = "Saved working directory and index state WIP on main: abc1234 fix stuff\n";
474 let result = compress("git stash", output).unwrap();
475 assert!(
476 result.contains("Saved working directory"),
477 "short stash messages must be preserved, got: {result}"
478 );
479 }
480
481 #[test]
482 fn stash_drop_preserves_short_message() {
483 let output = "Dropped refs/stash@{0} (abc123def456)\n";
484 let result = compress("git stash drop", output).unwrap();
485 assert!(
486 result.contains("Dropped"),
487 "short drop messages must be preserved, got: {result}"
488 );
489 }
490
491 #[test]
492 fn stash_list_short_preserved() {
493 let output = "stash@{0}: WIP on main: abc1234 fix\nstash@{1}: On feature: def5678 add\n";
494 let result = compress("git stash list", output).unwrap();
495 assert!(
496 result.contains("stash@{0}"),
497 "short stash list must be preserved, got: {result}"
498 );
499 }
500
501 #[test]
502 fn stash_list_long_reformats() {
503 let lines: Vec<String> = (0..10)
504 .map(|i| format!("stash@{{{i}}}: WIP on main: abc{i:04} commit {i}"))
505 .collect();
506 let output = lines.join("\n");
507 let result = compress("git stash list", &output).unwrap();
508 assert!(result.contains("@0:"), "should reformat @0, got: {result}");
509 assert!(result.contains("@9:"), "should reformat @9, got: {result}");
510 }
511
512 #[test]
513 fn stash_show_routes_to_show_compressor() {
514 let output = " src/main.rs | 10 +++++-----\n src/lib.rs | 3 ++-\n 2 files changed, 7 insertions(+), 6 deletions(-)\n";
515 let result = compress("git stash show", output).unwrap();
516 assert!(
517 result.contains("main.rs"),
518 "stash show should preserve file names, got: {result}"
519 );
520 }
521
522 #[test]
523 fn stash_show_patch_not_over_compressed() {
524 let lines: Vec<String> = (0..40)
525 .map(|i| format!("+line {i}: some content here"))
526 .collect();
527 let output = format!(
528 "diff --git a/file.rs b/file.rs\n--- a/file.rs\n+++ b/file.rs\n{}",
529 lines.join("\n")
530 );
531 let result = compress("git stash show -p", &output).unwrap();
532 let result_lines = result.lines().count();
533 assert!(
534 result_lines >= 10,
535 "stash show -p must not over-compress to 3 lines, got {result_lines} lines"
536 );
537 }
538
539 #[test]
540 fn show_stash_ref_routes_correctly() {
541 let output = "commit abc1234\nAuthor: User <u@e.com>\nDate: Mon Jan 1\n\n WIP on main\n\ndiff --git a/f.rs b/f.rs\n";
542 let result = compress("git show stash@{0}", output).unwrap();
543 assert!(
544 result.len() > 10,
545 "git show stash@{{0}} must not be over-compressed, got: {result}"
546 );
547 }
548
549 #[test]
550 fn show_source_blob_is_preserved_verbatim() {
551 let output = (0..40).fold(String::new(), |mut acc, i| {
552 use std::fmt::Write;
553 let _ = writeln!(acc, "pub const VALUE_{i}: usize = {i};");
554 acc
555 });
556
557 let result = compress("git show HEAD:src/generated.rs", &output).unwrap();
558
559 assert_eq!(result, output);
560 assert!(!result.contains("more lines"));
561 }
562
563 #[test]
564 fn show_format_colon_is_not_mistaken_for_blob_selector() {
565 assert!(!show_requests_blob("git show --format=%H:%s HEAD"));
566 }
567
568 #[test]
569 fn extract_subcommand_basic() {
570 assert_eq!(extract_git_subcommand("git status"), Some("status"));
571 assert_eq!(extract_git_subcommand("git log --oneline"), Some("log"));
572 assert_eq!(extract_git_subcommand("git diff HEAD~1"), Some("diff"));
573 assert_eq!(
574 extract_git_subcommand("git -C /tmp commit -m 'x'"),
575 Some("commit")
576 );
577 }
578
579 #[test]
580 fn extract_subcommand_avoids_filename_ambiguity() {
581 assert_eq!(
582 extract_git_subcommand("git log status.txt"),
583 Some("log"),
584 "should NOT match 'status' in filename"
585 );
586 assert_eq!(
587 extract_git_subcommand("git add commit.rs"),
588 Some("add"),
589 "should NOT match 'commit' in filename"
590 );
591 }
592
593 #[test]
594 fn extract_subcommand_full_path() {
595 assert_eq!(
596 extract_git_subcommand("/usr/bin/git status"),
597 Some("status")
598 );
599 }
600
601 #[test]
602 fn extract_subcommand_no_git() {
603 assert_eq!(extract_git_subcommand("cargo build"), None);
604 }
605
606 #[test]
607 fn filename_not_treated_as_subcommand() {
608 let output = "On branch main\nnothing to commit\n";
609 assert!(
610 compress("git log status.txt", output).is_some(),
611 "should route to log, not status"
612 );
613 }
614}