1mod commit;
4mod diff;
5mod log;
6mod parser;
7mod status;
8
9use parser::extract_git_subcommand;
10
11macro_rules! static_regex {
12 ($pattern:expr_2021) => {{
13 static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
14 RE.get_or_init(|| {
15 regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
16 })
17 }};
18}
19
20fn status_branch_re() -> &'static regex::Regex {
21 static_regex!(r"On branch (\S+)")
22}
23fn ahead_re() -> &'static regex::Regex {
24 static_regex!(r"ahead of .+ by (\d+) commit")
25}
26fn commit_hash_re() -> &'static regex::Regex {
27 static_regex!(r"\[([\w/.:-]+)\s+([a-f0-9]+)\]")
28}
29fn insertions_re() -> &'static regex::Regex {
30 static_regex!(r"(\d+) insertions?\(\+\)")
31}
32fn deletions_re() -> &'static regex::Regex {
33 static_regex!(r"(\d+) deletions?\(-\)")
34}
35fn files_changed_re() -> &'static regex::Regex {
36 static_regex!(r"(\d+) files? changed")
37}
38fn shortstat_line_re() -> &'static regex::Regex {
41 static_regex!(
42 r"^ \d+ files? changed(?:, (\d+) insertions?\(\+\))?(?:, (\d+) deletions?\(-\))?\s*$"
43 )
44}
45fn numstat_row_re() -> &'static regex::Regex {
47 static_regex!(r"^(\d+|-)\t(\d+|-)\t")
48}
49fn clone_objects_re() -> &'static regex::Regex {
50 static_regex!(r"Receiving objects:.*?(\d+)")
51}
52fn stash_re() -> &'static regex::Regex {
53 static_regex!(r"stash@\{(\d+)\}:\s*(.+)")
54}
55
56fn is_diff_or_stat_line(line: &str) -> bool {
57 let t = line.trim();
58 t.starts_with("diff --git")
59 || t.starts_with("index ")
60 || t.starts_with("--- a/")
61 || t.starts_with("+++ b/")
62 || t.starts_with("@@ ")
63 || t.starts_with("Binary files")
64 || t.starts_with("new file mode")
65 || t.starts_with("deleted file mode")
66 || t.starts_with("old mode")
67 || t.starts_with("new mode")
68 || t.starts_with("similarity index")
69 || t.starts_with("rename from")
70 || t.starts_with("rename to")
71 || t.starts_with("copy from")
72 || t.starts_with("copy to")
73 || (t.starts_with('+') && !t.starts_with("+++"))
74 || (t.starts_with('-') && !t.starts_with("---"))
75 || (t.contains(" | ") && t.chars().any(|c| c == '+' || c == '-'))
76}
77
78fn extract_change_stats(output: &str) -> String {
79 let files = files_changed_re()
80 .captures(output)
81 .and_then(|c| c[1].parse::<u32>().ok())
82 .unwrap_or(0);
83 let ins = insertions_re()
84 .captures(output)
85 .and_then(|c| c[1].parse::<u32>().ok())
86 .unwrap_or(0);
87 let del = deletions_re()
88 .captures(output)
89 .and_then(|c| c[1].parse::<u32>().ok())
90 .unwrap_or(0);
91
92 if files > 0 || ins > 0 || del > 0 {
93 format!("{files} files, +{ins}/-{del}")
94 } else {
95 String::new()
96 }
97}
98
99fn compact_lines(text: &str, max: usize) -> String {
100 let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
101 if lines.len() <= max {
102 return lines.join("\n");
103 }
104 format!(
105 "{}\n... ({} more lines)",
106 lines[..max].join("\n"),
107 lines.len() - max
108 )
109}
110
111fn show_requests_blob(command: &str) -> bool {
117 command.split_whitespace().any(|arg| {
118 let arg = arg.trim_matches(['\'', '"']);
119 !arg.starts_with('-')
120 && arg
121 .split_once(':')
122 .is_some_and(|(revision, path)| !revision.is_empty() && !path.is_empty())
123 })
124}
125
126fn requests_file_lists(command: &str) -> bool {
133 command.split_whitespace().any(|arg| {
134 let arg = arg.trim_matches(['\'', '"']);
135 matches!(
136 arg,
137 "--stat" | "--numstat" | "--name-only" | "--name-status"
138 ) || arg.starts_with("--stat=")
139 || arg.starts_with("--dirstat")
140 })
141}
142
143fn requests_patch(command: &str) -> bool {
145 command.split_whitespace().any(|arg| {
146 let arg = arg.trim_matches(['\'', '"']);
147 matches!(
148 arg,
149 "-p" | "-u" | "--patch" | "--patch-with-stat" | "--patch-with-raw"
150 )
151 })
152}
153
154fn is_commit_header_line(line: &str) -> bool {
159 const HEADERS: [&str; 14] = [
160 "Author:",
161 "AuthorDate:",
162 "Commit:",
163 "CommitDate:",
164 "Date:",
165 "Merge:",
166 "Reflog:",
167 "tree ",
168 "parent ",
169 "author ",
170 "committer ",
171 "encoding ",
172 "gpgsig ",
173 "mergetag ",
174 ];
175 HEADERS.iter().any(|h| line.starts_with(h))
176 || (line.starts_with(' ') && !line.starts_with(" ") && !line.trim().is_empty())
177}
178
179pub fn compress(command: &str, output: &str) -> Option<String> {
180 let sub = extract_git_subcommand(command)?;
181 match sub {
182 "status" => Some(status::compress_status(output)),
183 "log" => Some(log::compress_log(command, output)),
184 "diff" => Some(diff::compress_diff(output)),
185 "add" => Some(commit::compress_add(output)),
186 "commit" => Some(commit::compress_commit(output)),
187 "push" => Some(commit::compress_push(output)),
188 "pull" => Some(commit::compress_pull(output)),
189 "fetch" => Some(commit::compress_fetch(output)),
190 "clone" => Some(commit::compress_clone(output)),
191 "branch" => Some(commit::compress_branch(output)),
192 "checkout" | "switch" => Some(commit::compress_checkout(output)),
193 "merge" => Some(commit::compress_merge(output)),
194 "stash" => {
195 if command.contains("stash show") || command.contains("show stash") {
196 let keep_files = requests_file_lists(command) || !requests_patch(command);
198 return Some(commit::compress_show(output, keep_files));
199 }
200 Some(commit::compress_stash(output))
201 }
202 "tag" => Some(commit::compress_tag(output)),
203 "reset" => Some(commit::compress_reset(output)),
204 "remote" => {
205 if command.contains("remote add") {
206 return Some(commit::compress_add(output));
207 }
208 Some(commit::compress_remote(output))
209 }
210 "blame" => Some(commit::compress_blame(output)),
211 "cherry-pick" => Some(commit::compress_cherry_pick(output)),
212 "show" if show_requests_blob(command) => Some(output.to_string()),
213 "show" => Some(commit::compress_show(output, requests_file_lists(command))),
214 "rebase" => Some(commit::compress_rebase(output)),
215 "submodule" => Some(commit::compress_submodule(output)),
216 "worktree" => Some(commit::compress_worktree(output)),
217 "bisect" => Some(commit::compress_bisect(output)),
218 _ => None,
219 }
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225
226 #[test]
227 fn git_status_compresses() {
228 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";
229 let result = compress("git status", output).unwrap();
230 assert!(result.contains("main"), "should contain branch name");
231 assert!(result.contains("main.rs"), "should list modified files");
232 assert!(result.len() < output.len(), "should be shorter than input");
233 }
234
235 #[test]
236 fn git_add_compresses_to_ok() {
237 let result = compress("git add .", "").unwrap();
238 assert!(result.contains("ok"), "git add should compress to 'ok'");
239 }
240
241 #[test]
246 fn git_add_does_not_label_line_count_as_files() {
247 let output = "[main abc1234] fix: x\n 1 file changed, 1 insertion(+)\nhook line\nanother\nmore\nlines\nseven\n";
248 let result = compress("git add . && git commit -m 'x'", output).unwrap();
249 assert!(
250 !result.contains("files)"),
251 "line count must not be presented as a file count: {result}"
252 );
253 }
254
255 #[test]
256 fn git_add_verbose_counts_real_added_files() {
257 let output = "add 'a.rs'\nadd 'b.rs'\nadd 'c.rs'\nadd 'd.rs'\n";
258 let result = compress("git add -v .", output).unwrap();
259 assert!(
260 result.contains("+4 files"),
261 "verbose add lines are the real file count: {result}"
262 );
263 }
264
265 #[test]
266 fn git_commit_extracts_hash() {
267 let output =
268 "[main abc1234] fix: resolve bug\n 2 files changed, 10 insertions(+), 3 deletions(-)\n";
269 let result = compress("git commit -m 'fix'", output).unwrap();
270 assert!(result.contains("abc1234"), "should extract commit hash");
271 }
272
273 #[test]
274 fn git_push_compresses() {
275 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";
276 let result = compress("git push", output).unwrap();
277 assert!(result.len() < output.len(), "should compress push output");
278 }
279
280 #[test]
281 fn git_log_compresses() {
282 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";
283 let result = compress("git log", output).unwrap();
284 assert!(result.len() < output.len(), "should compress log output");
285 }
286
287 #[test]
288 fn git_log_oneline_truncates_long() {
289 let lines: Vec<String> = (0..150)
290 .map(|i| format!("abc{i:04} feat: commit number {i}"))
291 .collect();
292 let output = lines.join("\n");
293 let result = compress("git log --oneline", &output).unwrap();
294 assert!(
295 result.contains("... (50 more commits"),
296 "should truncate to 100 entries"
297 );
298 assert!(
299 result.lines().count() <= 102,
300 "should have at most 101 lines (100 + summary)"
301 );
302 }
303
304 #[test]
305 fn git_log_oneline_short_unchanged() {
306 let output = "abc1234 feat: one\ndef5678 fix: two\nghi9012 docs: three";
307 let result = compress("git log --oneline", output).unwrap();
308 assert_eq!(result, output, "short oneline should pass through");
309 }
310
311 #[test]
312 fn git_log_standard_truncates_long() {
313 let mut output = String::new();
314 for i in 0..130 {
315 output.push_str(&format!(
316 "commit {i:07}abc1234\nAuthor: U <u@e.com>\nDate: Mon\n\n msg {i}\n\n"
317 ));
318 }
319 let result = compress("git log", &output).unwrap();
320 assert!(
321 result.contains("... (30 more commits"),
322 "should truncate standard log at 100"
323 );
324 }
325
326 #[test]
327 fn git_diff_compresses() {
328 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 }";
329 let result = compress("git diff", output).unwrap();
330 assert!(result.contains("main.rs"), "should reference changed file");
331 }
332
333 #[test]
334 fn git_diff_stat_preserves_all_files() {
335 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";
336 let result = compress("git diff --stat", output).unwrap();
337 assert!(
338 result.contains("en.json"),
339 "must keep en.json, got: {result}"
340 );
341 assert!(
342 result.contains("DocsToolsCorePage"),
343 "must keep CorePage, got: {result}"
344 );
345 assert!(
346 result.contains("DocsToolsIntelligencePage"),
347 "must keep IntelligencePage, got: {result}"
348 );
349 assert!(
350 result.contains("DocsToolsMemoryPage"),
351 "must keep MemoryPage, got: {result}"
352 );
353 assert!(
354 result.contains("DocsToolsSessionPage"),
355 "must keep SessionPage, got: {result}"
356 );
357 assert!(
358 result.contains("5 files changed"),
359 "must keep summary line, got: {result}"
360 );
361 }
362
363 #[test]
364 fn git_diff_cached_stat_preserves_all_files() {
365 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";
366 let result = compress("git diff --cached --stat", output).unwrap();
367 assert!(result.contains("a.rs"), "must keep a.rs, got: {result}");
368 assert!(result.contains("d.rs"), "must keep d.rs, got: {result}");
369 assert!(
370 result.contains("4 files changed"),
371 "must keep summary, got: {result}"
372 );
373 }
374
375 #[test]
376 fn git_diff_shortstat_preserved() {
377 let output = " 5 files changed, 45 insertions(+), 172 deletions(-)\n";
378 let result = compress("git diff --shortstat", output).unwrap();
379 assert!(
380 result.contains("5 files changed"),
381 "shortstat must pass through, got: {result}"
382 );
383 }
384
385 #[test]
386 fn git_push_preserves_pipeline_url() {
387 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";
388 let result = compress("git push", output).unwrap();
389 assert!(
390 result.contains("pipeline"),
391 "should preserve pipeline URL, got: {result}"
392 );
393 assert!(
394 result.contains("merge_request"),
395 "should preserve merge request URL"
396 );
397 assert!(result.contains("->"), "should contain ref update line");
398 }
399
400 #[test]
401 fn git_push_preserves_github_pr_url() {
402 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";
403 let result = compress("git push", output).unwrap();
404 assert!(
405 result.contains("pull/"),
406 "should preserve GitHub PR URL, got: {result}"
407 );
408 }
409
410 #[test]
411 fn git_commit_preserves_hook_output() {
412 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";
413 let result = compress("git commit -m 'fix'", output).unwrap();
414 assert!(
415 result.contains("ruff"),
416 "should preserve hook output, got: {result}"
417 );
418 assert!(
419 result.contains("abc1234"),
420 "should still extract commit hash"
421 );
422 }
423
424 #[test]
425 fn git_commit_no_hooks() {
426 let output =
427 "[main abc1234] fix: resolve bug\n 2 files changed, 10 insertions(+), 3 deletions(-)\n";
428 let result = compress("git commit -m 'fix'", output).unwrap();
429 assert!(result.contains("abc1234"), "should extract commit hash");
430 assert!(
431 !result.contains("hook"),
432 "should not mention hooks when none present"
433 );
434 }
435
436 #[test]
437 fn git_log_with_patch_keeps_hunks_for_few_commits() {
438 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";
439 let result = compress("git log -p", output).unwrap();
440 assert!(
441 result.contains("println"),
442 "1-3 commits with -p should KEEP diff hunks, got: {result}"
443 );
444 assert!(result.contains("abc1234"), "should contain commit hash");
445 assert!(
446 result.contains("feat: add feature"),
447 "should contain commit message"
448 );
449 }
450
451 #[test]
452 fn git_log_with_patch_summarizes_many_commits() {
453 let mut output = String::new();
454 for i in 0..10 {
455 output.push_str(&format!(
456 "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"
457 ));
458 }
459 let result = compress("git log -p", &output).unwrap();
460 assert!(
461 result.contains("msg 0"),
462 "newest commit message should be present"
463 );
464 assert!(
465 result.contains("+line 0"),
466 "newest commit should have hunks preserved"
467 );
468 assert!(
469 result.len() < output.len(),
470 "should be compressed ({} vs {})",
471 result.len(),
472 output.len()
473 );
474 }
475
476 #[test]
477 fn git_log_with_stat_filters_stat_content() {
478 let mut output = String::new();
479 for i in 0..5 {
480 output.push_str(&format!(
481 "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"
482 ));
483 }
484 let result = compress("git log --stat", &output).unwrap();
485 assert!(
486 result.len() < output.len(),
487 "headers should still be dropped ({} vs {})",
488 result.len(),
489 output.len()
490 );
491 assert!(!result.contains("Author:"), "{result}");
492 for i in 0..5 {
493 assert!(
494 result.contains(&format!(" src/file{i}.rs | 10 ++++------")),
495 "--stat asked for the file lines (#2298): {result}"
496 );
497 }
498 }
499
500 fn issue_2298_log(kind: &str) -> String {
502 use std::fmt::Write;
503 let mut out = String::new();
504 for i in (1..=6).rev() {
505 let _ = write!(
506 out,
507 "commit {i}{i}{i}{i}{i}{i}{i}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\
508 Author: t <t@example.com>\n\
509 Date: Fri Dec 4 19:30:5{i} 2026 +0700\n\n feat: change module {i}\n\n"
510 );
511 for f in ["a", "b", "c", "d", "e", "f", "g", "h"] {
512 let path = format!("src/m{i}/{f}.txt");
513 let n = i * 7;
514 let _ = match kind {
515 "name-only" => writeln!(out, "{path}"),
516 "name-status" => writeln!(out, "A\t{path}"),
517 "numstat" => writeln!(out, "{n}\t0\t{path}"),
518 _ => writeln!(out, " {path} | {n} {}", "+".repeat(n)),
519 };
520 }
521 if kind == "stat" {
522 let _ = writeln!(out, " 8 files changed, {} insertions(+)", i * 56);
523 }
524 if i > 1 {
525 out.push('\n');
526 }
527 }
528 out
529 }
530
531 #[test]
532 fn git_log_name_only_keeps_every_file() {
533 let output = issue_2298_log("name-only");
534 let result = compress("git log --name-only -6", &output).unwrap();
535 for i in 1..=6 {
536 assert!(
537 result.contains(&format!("{i}{i}{i}{i}{i}{i}{i} feat: change module {i}")),
538 "{result}"
539 );
540 for f in ["a", "b", "c", "d", "e", "f", "g", "h"] {
541 assert!(
542 result.lines().any(|l| l == format!("src/m{i}/{f}.txt")),
543 "missing src/m{i}/{f}.txt: {result}"
544 );
545 }
546 }
547 assert!(
548 !result.contains("Author:") && !result.contains("Date:"),
549 "{result}"
550 );
551 assert!(result.len() < output.len(), "{result}");
552 }
553
554 #[test]
555 fn git_log_stat_keeps_every_stat_line() {
556 let output = issue_2298_log("stat");
557 let result = compress("git log --stat", &output).unwrap();
558 for i in 1..=6 {
559 assert!(result.contains(&format!("feat: change module {i}")));
560 for f in ["a", "h"] {
561 let n = i * 7;
562 let row = format!(" src/m{i}/{f}.txt | {n} {}", "+".repeat(n));
563 assert!(result.lines().any(|l| l == row), "missing {row}: {result}");
564 }
565 let summary = format!(" 8 files changed, {} insertions(+)", i * 56);
566 assert!(result.lines().any(|l| l == summary), "{result}");
567 }
568 assert!(result.contains("[6 commits, +1176/-0 total]"), "{result}");
569 }
570
571 #[test]
572 fn git_log_name_status_and_numstat_keep_every_file() {
573 let output = issue_2298_log("name-status");
574 let result = compress("git log --name-status", &output).unwrap();
575 assert_eq!(
576 result.lines().filter(|l| l.starts_with("A\tsrc/m")).count(),
577 48,
578 "{result}"
579 );
580
581 let output = issue_2298_log("numstat");
582 let result = compress("git log --numstat", &output).unwrap();
583 assert_eq!(
584 result.lines().filter(|l| l.contains("\t0\tsrc/m")).count(),
585 48,
586 "{result}"
587 );
588 }
589
590 #[test]
591 fn git_log_oneline_name_only_is_not_capped_as_commits() {
592 let mut output = String::new();
593 for i in 0..30 {
594 output.push_str(&format!("abc{i:04} change {i}\n"));
595 for f in 0..8 {
596 output.push_str(&format!("src/m{i}/{f}.txt\n"));
597 }
598 }
599 let result = compress("git log --oneline --name-only", &output).unwrap();
600 assert_eq!(result, output.trim_end());
601 }
602
603 const SHOW_STAT_FULLER: &str = "commit 6666666aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
604Author: t <t@example.com>
605AuthorDate: Fri Dec 4 19:30:53 2026 +0700
606Commit: t <t@example.com>
607CommitDate: Fri Dec 4 19:30:53 2026 +0700
608
609 feat: change module 6
610
611 Longer body text that explains the change.
612
613 src/m6/a.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
614 src/m6/b.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
615 src/m6/c.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
616 src/m6/d.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
617 src/m6/e.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
618 src/m6/f.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
619 src/m6/g.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
620 src/m6/h.txt | 42 ++++++++++++++++++++++++++++++++++++++++++
621 8 files changed, 336 insertions(+)
622";
623
624 #[test]
625 fn git_show_stat_fuller_keeps_subject_and_files() {
626 let result = compress("git show --stat --format=fuller HEAD", SHOW_STAT_FULLER).unwrap();
627 assert!(
628 result.starts_with("6666666 feat: change module 6\n"),
629 "{result}"
630 );
631 assert!(!result.contains("AuthorDate") && !result.contains("CommitDate"));
632 assert!(!result.contains("Longer body text"), "{result}");
633 for f in ["a", "b", "c", "d", "e", "f", "g", "h"] {
634 let row = format!(" src/m6/{f}.txt | 42 {}", "+".repeat(42));
635 assert!(result.lines().any(|l| l == row), "missing {row}: {result}");
636 }
637 assert!(
638 result.contains(" 8 files changed, 336 insertions(+)"),
639 "{result}"
640 );
641 }
642
643 #[test]
644 fn git_show_fuller_without_stat_reports_real_subject() {
645 let result = compress("git show --format=fuller HEAD", SHOW_STAT_FULLER).unwrap();
646 assert_eq!(result, "6666666 feat: change module 6 [8 files, +336/-0]");
647
648 let raw = "commit 6666666aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ntree 1234\nparent 5555\nauthor t <t@example.com> 1 +0700\ncommitter t <t@example.com> 1 +0700\n\n feat: raw subject\n";
649 let result = compress("git show --format=raw HEAD", raw).unwrap();
650 assert_eq!(result, "6666666 feat: raw subject");
651 }
652
653 #[test]
654 fn git_log_fuller_reports_real_subject() {
655 let output =
656 SHOW_STAT_FULLER.replace(" Longer body text that explains the change.\n\n", "");
657 let result = compress("git log --format=fuller -1", &output).unwrap();
658 assert!(
659 result.starts_with("6666666 feat: change module 6"),
660 "{result}"
661 );
662 assert!(
663 !result.contains(" src/m6/a.txt"),
664 "no file list asked: {result}"
665 );
666 }
667
668 #[test]
669 fn git_show_plain_compression_unchanged() {
670 let output = "commit abcdef0123456789\nAuthor: U <u@e.com>\nDate: Mon\n\n fix: thing\n\n src/a.rs | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)\n";
671 assert_eq!(
672 compress("git show HEAD", output).unwrap(),
673 "abcdef0 fix: thing [1 files, +1/-1]"
674 );
675 assert_eq!(
676 compress("git log", output).unwrap(),
677 "abcdef0 fix: thing\n[1 commits, +1/-1 total]"
678 );
679 }
680
681 #[test]
682 fn git_commit_with_feature_branch() {
683 let output = "[feature/my-branch abc1234] feat: add new thing\n 3 files changed, 20 insertions(+), 5 deletions(-)\n";
684 let result = compress("git commit -m 'feat'", output).unwrap();
685 assert!(
686 result.contains("abc1234"),
687 "should extract hash from feature branch, got: {result}"
688 );
689 assert!(
690 result.contains("feature/my-branch"),
691 "should preserve branch name, got: {result}"
692 );
693 }
694
695 #[test]
696 fn git_commit_many_hooks_compressed() {
697 let mut output = String::new();
698 for i in 0..30 {
699 output.push_str(&format!("check-{i}..........passed\n"));
700 }
701 output.push_str("[main abc1234] fix: resolve bug\n 1 file changed, 1 insertion(+)\n");
702 let result = compress("git commit -m 'fix'", &output).unwrap();
703 assert!(result.contains("abc1234"), "should contain commit hash");
704 assert!(
705 result.contains("hooks passed"),
706 "should summarize passed hooks, got: {result}"
707 );
708 assert!(
709 result.len() < output.len() / 2,
710 "should compress verbose hook output ({} vs {})",
711 result.len(),
712 output.len()
713 );
714 }
715
716 #[test]
717 fn stash_push_preserves_short_message() {
718 let output = "Saved working directory and index state WIP on main: abc1234 fix stuff\n";
719 let result = compress("git stash", output).unwrap();
720 assert!(
721 result.contains("Saved working directory"),
722 "short stash messages must be preserved, got: {result}"
723 );
724 }
725
726 #[test]
727 fn stash_drop_preserves_short_message() {
728 let output = "Dropped refs/stash@{0} (abc123def456)\n";
729 let result = compress("git stash drop", output).unwrap();
730 assert!(
731 result.contains("Dropped"),
732 "short drop messages must be preserved, got: {result}"
733 );
734 }
735
736 #[test]
737 fn stash_list_short_preserved() {
738 let output = "stash@{0}: WIP on main: abc1234 fix\nstash@{1}: On feature: def5678 add\n";
739 let result = compress("git stash list", output).unwrap();
740 assert!(
741 result.contains("stash@{0}"),
742 "short stash list must be preserved, got: {result}"
743 );
744 }
745
746 #[test]
747 fn stash_list_long_reformats() {
748 let lines: Vec<String> = (0..10)
749 .map(|i| format!("stash@{{{i}}}: WIP on main: abc{i:04} commit {i}"))
750 .collect();
751 let output = lines.join("\n");
752 let result = compress("git stash list", &output).unwrap();
753 assert!(result.contains("@0:"), "should reformat @0, got: {result}");
754 assert!(result.contains("@9:"), "should reformat @9, got: {result}");
755 }
756
757 #[test]
758 fn stash_show_routes_to_show_compressor() {
759 let output = " src/main.rs | 10 +++++-----\n src/lib.rs | 3 ++-\n 2 files changed, 7 insertions(+), 6 deletions(-)\n";
760 let result = compress("git stash show", output).unwrap();
761 assert!(
762 result.contains("main.rs"),
763 "stash show should preserve file names, got: {result}"
764 );
765 }
766
767 #[test]
768 fn stash_show_patch_not_over_compressed() {
769 let lines: Vec<String> = (0..40)
770 .map(|i| format!("+line {i}: some content here"))
771 .collect();
772 let output = format!(
773 "diff --git a/file.rs b/file.rs\n--- a/file.rs\n+++ b/file.rs\n{}",
774 lines.join("\n")
775 );
776 let result = compress("git stash show -p", &output).unwrap();
777 let result_lines = result.lines().count();
778 assert!(
779 result_lines >= 10,
780 "stash show -p must not over-compress to 3 lines, got {result_lines} lines"
781 );
782 }
783
784 #[test]
785 fn show_stash_ref_routes_correctly() {
786 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";
787 let result = compress("git show stash@{0}", output).unwrap();
788 assert!(
789 result.len() > 10,
790 "git show stash@{{0}} must not be over-compressed, got: {result}"
791 );
792 }
793
794 #[test]
795 fn show_source_blob_is_preserved_verbatim() {
796 let output = (0..40).fold(String::new(), |mut acc, i| {
797 use std::fmt::Write;
798 let _ = writeln!(acc, "pub const VALUE_{i}: usize = {i};");
799 acc
800 });
801
802 let result = compress("git show HEAD:src/generated.rs", &output).unwrap();
803
804 assert_eq!(result, output);
805 assert!(!result.contains("more lines"));
806 }
807
808 #[test]
809 fn show_format_colon_is_not_mistaken_for_blob_selector() {
810 assert!(!show_requests_blob("git show --format=%H:%s HEAD"));
811 }
812
813 #[test]
814 fn extract_subcommand_basic() {
815 assert_eq!(extract_git_subcommand("git status"), Some("status"));
816 assert_eq!(extract_git_subcommand("git log --oneline"), Some("log"));
817 assert_eq!(extract_git_subcommand("git diff HEAD~1"), Some("diff"));
818 assert_eq!(
819 extract_git_subcommand("git -C /tmp commit -m 'x'"),
820 Some("commit")
821 );
822 }
823
824 #[test]
825 fn extract_subcommand_avoids_filename_ambiguity() {
826 assert_eq!(
827 extract_git_subcommand("git log status.txt"),
828 Some("log"),
829 "should NOT match 'status' in filename"
830 );
831 assert_eq!(
832 extract_git_subcommand("git add commit.rs"),
833 Some("add"),
834 "should NOT match 'commit' in filename"
835 );
836 }
837
838 #[test]
839 fn extract_subcommand_full_path() {
840 assert_eq!(
841 extract_git_subcommand("/usr/bin/git status"),
842 Some("status")
843 );
844 }
845
846 #[test]
847 fn extract_subcommand_no_git() {
848 assert_eq!(extract_git_subcommand("cargo build"), None);
849 }
850
851 #[test]
852 fn filename_not_treated_as_subcommand() {
853 let output = "On branch main\nnothing to commit\n";
854 assert!(
855 compress("git log status.txt", output).is_some(),
856 "should route to log, not status"
857 );
858 }
859}