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