Skip to main content

aft_base/compress/
git.rs

1use crate::compress::generic::{dedup_consecutive, middle_truncate, GenericCompressor};
2use crate::compress::{CompressionResult, Compressor};
3
4const STATUS_SHORT_LIMIT: usize = 1024;
5const STATUS_KEEP_PER_SECTION: usize = 10;
6const DIFF_MAX_FILES: usize = 5;
7const DIFF_MAX_HUNKS: usize = 20;
8const HUNK_KEEP_LINES: usize = 30;
9const LOG_SHORT_HASH_LEN: usize = 12;
10const BLAME_KEEP_LINES: usize = 50;
11const GIT_WRITE_KEEP_LINES: usize = 50;
12const GIT_ADD_KEEP_PATHS: usize = 5;
13const GIT_STASH_STATUS_KEEP_LINES: usize = 20;
14
15pub struct GitCompressor;
16
17impl Compressor for GitCompressor {
18    fn matches(&self, command: &str) -> bool {
19        command_head(command).is_some_and(|head| head == "git")
20    }
21
22    fn compress_with_exit_code(
23        &self,
24        command: &str,
25        output: &str,
26        exit_code: Option<i64>,
27    ) -> CompressionResult {
28        let compressed = match git_subcommand(command).as_deref() {
29            Some("add") => compress_add(output),
30            Some("status") => compress_status(output),
31            Some("diff") => compress_diff(output, false),
32            Some("log") => compress_log(output),
33            Some("show") => compress_diff(output, true),
34            Some("branch") => trim_trailing_lines(&dedup_consecutive(output)),
35            Some("blame") => compress_blame(output),
36            Some("commit") => compress_commit(output),
37            Some("push") => compress_push(output),
38            Some("pull") => compress_pull(output),
39            Some("fetch") => compress_fetch(output),
40            Some("stash") => compress_stash(command, output),
41            _ => GenericCompressor::compress_output(output),
42        };
43        if matches!(exit_code, Some(code) if code != 0)
44            && looks_like_git_success_summary(&compressed)
45        {
46            GenericCompressor::compress_output(output).into()
47        } else {
48            compressed.into()
49        }
50    }
51}
52
53fn looks_like_git_success_summary(text: &str) -> bool {
54    let trimmed = text.trim();
55    matches!(
56        trimmed,
57        "git: ok" | "git fetch: ok" | "Everything up-to-date" | "Already up to date."
58    ) || trimmed.contains("working tree clean")
59}
60
61fn command_head(command: &str) -> Option<&str> {
62    command.split_whitespace().next()
63}
64
65fn git_subcommand(command: &str) -> Option<String> {
66    git_command_tokens(command).next().map(str::to_string)
67}
68
69// Global options that take a separate value must not make that value look like
70// the subcommand. Attached values are already contained in the option token.
71fn git_command_tokens(command: &str) -> impl Iterator<Item = &str> {
72    let mut tokens = command.split_whitespace();
73    while let Some(token) = tokens.next() {
74        if token == "git" {
75            break;
76        }
77    }
78    while let Some(token) = tokens.next() {
79        if crate::compress::is_shell_boundary(token) {
80            return "".split_whitespace();
81        }
82        if matches!(
83            token,
84            "-C" | "-c"
85                | "--git-dir"
86                | "--work-tree"
87                | "--namespace"
88                | "--config-env"
89                | "--super-prefix"
90        ) {
91            if tokens.next().is_none_or(crate::compress::is_shell_boundary) {
92                return "".split_whitespace();
93            }
94        } else if !token.starts_with('-') {
95            // Return the original suffix so callers can also inspect commands
96            // such as `git remote add` without parsing global options twice.
97            let offset = token.as_ptr() as usize - command.as_ptr() as usize;
98            return command[offset..].split_whitespace();
99        }
100    }
101    "".split_whitespace()
102}
103
104fn git_subcommand_after(command: &str, subcommand: &str) -> Option<String> {
105    let mut tokens = git_command_tokens(command);
106    if tokens.next()? != subcommand {
107        return None;
108    }
109    for token in tokens {
110        if crate::compress::is_shell_boundary(token) {
111            return None;
112        }
113        if !token.starts_with('-') && !token.contains('=') {
114            return Some(token.to_string());
115        }
116    }
117    None
118}
119
120fn compress_add(output: &str) -> String {
121    if output.trim().is_empty() {
122        return "git: ok".to_string();
123    }
124    if looks_like_git_error(output) {
125        return trim_trailing_lines(output);
126    }
127    let lines: Vec<&str> = output
128        .lines()
129        .filter(|line| !line.trim().is_empty())
130        .collect();
131    if lines.is_empty() {
132        return "git: ok".to_string();
133    }
134    let mut result: Vec<String> = lines
135        .iter()
136        .take(GIT_ADD_KEEP_PATHS)
137        .map(|line| line.trim_end().to_string())
138        .collect();
139    if lines.len() > GIT_ADD_KEEP_PATHS {
140        result.push(format!(
141            "... ({} more files added)",
142            lines.len() - GIT_ADD_KEEP_PATHS
143        ));
144    }
145    cap_git_lines(result, "files added", GIT_WRITE_KEEP_LINES)
146}
147
148fn compress_commit(output: &str) -> String {
149    if output.trim().is_empty() {
150        return GenericCompressor::compress_output(output);
151    }
152    if looks_like_git_error(output) {
153        return trim_trailing_lines(output);
154    }
155    if let Some(line) = output
156        .lines()
157        .find(|line| line.contains("nothing to commit"))
158    {
159        return line.trim_end().to_string();
160    }
161    let subject = output.lines().find(|line| looks_like_commit_subject(line));
162    let summary = output.lines().find(|line| looks_like_commit_summary(line));
163    match (subject, summary) {
164        (Some(subject), Some(summary)) => {
165            trim_trailing_lines(&format!("{}\n{}", subject.trim_end(), summary.trim()))
166        }
167        (Some(subject), None) => subject.trim_end().to_string(),
168        _ => GenericCompressor::compress_output(output),
169    }
170}
171
172fn compress_push(output: &str) -> String {
173    if output.trim().is_empty() {
174        return GenericCompressor::compress_output(output);
175    }
176    if looks_like_git_error(output) {
177        return trim_trailing_lines(output);
178    }
179    if let Some(line) = output
180        .lines()
181        .find(|line| line.trim() == "Everything up-to-date")
182    {
183        return line.trim_end().to_string();
184    }
185    let result: Vec<String> = output
186        .lines()
187        .filter(|line| is_remote_destination(line) || is_ref_update_line(line))
188        .map(|line| line.trim_end().to_string())
189        .collect();
190    if result.is_empty() {
191        return GenericCompressor::compress_output(output);
192    }
193    cap_git_lines(result, "push lines", GIT_WRITE_KEEP_LINES)
194}
195
196fn compress_pull(output: &str) -> String {
197    if output.trim().is_empty() {
198        return GenericCompressor::compress_output(output);
199    }
200    if looks_like_git_error(output) {
201        return trim_trailing_lines(output);
202    }
203    if let Some(line) = output
204        .lines()
205        .find(|line| line.trim() == "Already up to date.")
206    {
207        return line.trim_end().to_string();
208    }
209    let result: Vec<String> = output
210        .lines()
211        .filter(|line| {
212            looks_like_updating_line(line)
213                || looks_like_pull_marker(line)
214                || looks_like_commit_summary(line)
215        })
216        .map(|line| line.trim_end().to_string())
217        .collect();
218    if result.is_empty() {
219        return GenericCompressor::compress_output(output);
220    }
221    cap_git_lines(result, "pull lines", GIT_WRITE_KEEP_LINES)
222}
223
224fn compress_fetch(output: &str) -> String {
225    if output.trim().is_empty() {
226        return "git fetch: ok".to_string();
227    }
228    if looks_like_git_error(output) {
229        return trim_trailing_lines(output);
230    }
231    let result: Vec<String> = output
232        .lines()
233        .filter(|line| is_fetch_from_line(line) || is_ref_update_line(line))
234        .map(|line| line.trim_end().to_string())
235        .collect();
236    if result.is_empty() {
237        return GenericCompressor::compress_output(output);
238    }
239    cap_git_lines(result, "fetch lines", GIT_WRITE_KEEP_LINES)
240}
241
242fn compress_stash(command: &str, output: &str) -> String {
243    if output.trim().is_empty() {
244        return GenericCompressor::compress_output(output);
245    }
246    if looks_like_git_error(output) {
247        return trim_trailing_lines(output);
248    }
249    match git_subcommand_after(command, "stash").as_deref() {
250        None | Some("push") | Some("save") => output
251            .lines()
252            .find(|line| line.starts_with("Saved working directory and index state"))
253            .map(|line| line.trim_end().to_string())
254            .unwrap_or_else(|| GenericCompressor::compress_output(output)),
255        Some("pop" | "apply") => cap_git_lines(
256            output
257                .lines()
258                .map(|line| line.trim_end().to_string())
259                .collect(),
260            "stash status lines",
261            GIT_STASH_STATUS_KEEP_LINES,
262        ),
263        Some("list") => trim_trailing_lines(output),
264        _ => GenericCompressor::compress_output(output),
265    }
266}
267
268fn looks_like_git_error(output: &str) -> bool {
269    output.lines().any(|line| {
270        let trimmed = line.trim_start();
271        trimmed.starts_with("error:")
272            || trimmed.starts_with("fatal:")
273            || trimmed.starts_with("CONFLICT ")
274            || trimmed.starts_with("Automatic merge failed")
275            || trimmed.starts_with("! [rejected]")
276            || trimmed.starts_with("! [remote rejected]")
277            || trimmed.starts_with("failed to push")
278    })
279}
280
281fn looks_like_commit_subject(line: &str) -> bool {
282    let trimmed = line.trim_start();
283    trimmed.starts_with('[') && trimmed.contains("] ")
284}
285
286fn looks_like_commit_summary(line: &str) -> bool {
287    let trimmed = line.trim();
288    (trimmed.contains("file changed") || trimmed.contains("files changed"))
289        && (trimmed.contains("insertion")
290            || trimmed.contains("deletion")
291            || trimmed.contains("changed"))
292}
293
294fn is_remote_destination(line: &str) -> bool {
295    line.starts_with("To ")
296}
297
298fn is_fetch_from_line(line: &str) -> bool {
299    line.starts_with("From ")
300}
301
302fn is_ref_update_line(line: &str) -> bool {
303    let trimmed = line.trim_start();
304    trimmed.contains(" -> ")
305        && (trimmed.starts_with('*')
306            || trimmed.starts_with('+')
307            || trimmed.starts_with('-')
308            || trimmed.starts_with('=')
309            || trimmed.starts_with('!')
310            || trimmed.split_whitespace().next().is_some_and(is_hash_range))
311}
312
313fn is_hash_range(token: &str) -> bool {
314    token
315        .split_once("..")
316        .is_some_and(|(left, right)| is_short_hash(left) && is_short_hash(right))
317}
318
319fn is_short_hash(token: &str) -> bool {
320    (4..=40).contains(&token.len()) && token.bytes().all(|byte| byte.is_ascii_hexdigit())
321}
322
323fn looks_like_updating_line(line: &str) -> bool {
324    line.trim_start().starts_with("Updating ")
325}
326
327fn looks_like_pull_marker(line: &str) -> bool {
328    let trimmed = line.trim();
329    trimmed == "Fast-forward" || trimmed.starts_with("Merge made by ")
330}
331
332fn cap_git_lines(lines: Vec<String>, summary_name: &str, keep_lines: usize) -> String {
333    // Head plus tail: `git stash pop` and `git pull` end with their outcome
334    // ("Dropped refs/stash@{0}", the files-changed summary), so the cut goes in
335    // the middle rather than after the first lines.
336    let kept = crate::compress::line_cut::cap_lines_head_tail(&lines, keep_lines, summary_name);
337    trim_trailing_lines(&kept.join("\n"))
338}
339
340fn compress_status(output: &str) -> String {
341    if output.len() <= STATUS_SHORT_LIMIT {
342        return trim_trailing_lines(output);
343    }
344
345    let mut result = Vec::new();
346    let mut section_entries = Vec::new();
347    let mut in_section = false;
348
349    for line in output.lines() {
350        if is_status_section_header(line) {
351            flush_status_entries(&mut result, &mut section_entries);
352            result.push(line.to_string());
353            in_section = true;
354        } else if in_section && is_status_instructional(line) {
355            // Lines like `  (use "git add <file>..." to include in what will be
356            // committed)` come right after the section header in real git
357            // output. They're informational, not entries — pass them through
358            // verbatim WITHOUT resetting `in_section` so the entries that
359            // follow still get aggregated and summarized.
360            result.push(line.to_string());
361        } else if in_section && is_status_entry(line) {
362            section_entries.push(line.to_string());
363        } else {
364            flush_status_entries(&mut result, &mut section_entries);
365            result.push(line.to_string());
366            in_section = false;
367        }
368    }
369    flush_status_entries(&mut result, &mut section_entries);
370
371    trim_trailing_lines(&result.join("\n"))
372}
373
374fn is_status_section_header(line: &str) -> bool {
375    matches!(
376        line.trim_end_matches(':'),
377        "Changes to be committed"
378            | "Changes not staged for commit"
379            | "Untracked files"
380            | "Unmerged paths"
381    )
382}
383
384/// Recognize the parenthesized instructional lines git emits inside a status
385/// section, e.g. `  (use "git add <file>..." to include in what will be committed)`.
386/// These come right after the section header and must NOT reset the
387/// in-section state, otherwise the actual entries that follow are missed by
388/// the entry aggregator.
389fn is_status_instructional(line: &str) -> bool {
390    let trimmed = line.trim_start();
391    trimmed.starts_with('(') || trimmed.starts_with("use ")
392}
393
394fn is_status_entry(line: &str) -> bool {
395    let trimmed = line.trim_start();
396    trimmed.starts_with("modified:")
397        || trimmed.starts_with("new file:")
398        || trimmed.starts_with("deleted:")
399        || trimmed.starts_with("renamed:")
400        || trimmed.starts_with("copied:")
401        || trimmed.starts_with("both modified:")
402        || trimmed.starts_with("both added:")
403        || trimmed.starts_with("deleted by us:")
404        || trimmed.starts_with("deleted by them:")
405        || (!trimmed.is_empty()
406            && !trimmed.starts_with('(')
407            && !trimmed.starts_with("use ")
408            && !trimmed.starts_with("no changes"))
409}
410
411fn flush_status_entries(result: &mut Vec<String>, entries: &mut Vec<String>) {
412    if entries.is_empty() {
413        return;
414    }
415
416    let keep = entries.len().min(STATUS_KEEP_PER_SECTION);
417    result.extend(entries.iter().take(keep).cloned());
418    if entries.len() > keep {
419        result.push(format!("... and {} more", entries.len() - keep));
420    }
421    entries.clear();
422}
423
424fn compress_diff(output: &str, keep_commit_header: bool) -> String {
425    let files = split_diff_files(output, keep_commit_header);
426    let total_hunks: usize = files.iter().map(|file| count_hunks(&file.lines)).sum();
427
428    if files.is_empty() || total_hunks <= 2 && output.len() <= 5 * 1024 {
429        return trim_trailing_lines(output);
430    }
431
432    let max_files = if total_hunks > DIFF_MAX_HUNKS {
433        DIFF_MAX_FILES
434    } else {
435        usize::MAX
436    };
437
438    let mut result = Vec::new();
439    let mut emitted_files = 0usize;
440
441    for file in &files {
442        if file.is_diff && emitted_files >= max_files {
443            continue;
444        }
445        result.extend(compress_diff_file(&file.lines));
446        emitted_files += usize::from(file.is_diff);
447    }
448
449    let changed_files = files.iter().filter(|file| file.is_diff).count();
450    if changed_files > emitted_files {
451        result.push(format!(
452            "... and {} more files changed",
453            changed_files - emitted_files
454        ));
455    }
456
457    middle_truncate(
458        &trim_trailing_lines(&result.join("\n")),
459        16 * 1024,
460        7 * 1024,
461        7 * 1024,
462    )
463}
464
465struct DiffFile {
466    lines: Vec<String>,
467    is_diff: bool,
468}
469
470fn split_diff_files(output: &str, keep_commit_header: bool) -> Vec<DiffFile> {
471    let mut files = Vec::new();
472    let mut current = Vec::new();
473    let mut current_is_diff = false;
474
475    for line in output.lines() {
476        if line.starts_with("diff --git ") {
477            if !current.is_empty() {
478                files.push(DiffFile {
479                    lines: std::mem::take(&mut current),
480                    is_diff: current_is_diff,
481                });
482            }
483            current_is_diff = true;
484        } else if !current_is_diff && !keep_commit_header && !line.starts_with("diff --git ") {
485            current_is_diff = true;
486        }
487        current.push(line.to_string());
488    }
489
490    if !current.is_empty() {
491        files.push(DiffFile {
492            lines: current,
493            is_diff: current_is_diff,
494        });
495    }
496
497    files
498}
499
500fn compress_diff_file(lines: &[String]) -> Vec<String> {
501    let mut result = Vec::new();
502    let mut index = 0usize;
503
504    while index < lines.len() {
505        let line = &lines[index];
506        if !line.starts_with("@@") {
507            result.push(line.clone());
508            index += 1;
509            continue;
510        }
511
512        let hunk_start = index;
513        index += 1;
514        while index < lines.len() && !lines[index].starts_with("@@") {
515            index += 1;
516        }
517        let hunk = &lines[hunk_start..index];
518        append_hunk(&mut result, hunk);
519    }
520
521    result
522}
523
524fn append_hunk(result: &mut Vec<String>, hunk: &[String]) {
525    if hunk.len() <= HUNK_KEEP_LINES + 1 {
526        result.extend(hunk.iter().cloned());
527        return;
528    }
529
530    result.extend(hunk.iter().take(HUNK_KEEP_LINES + 1).cloned());
531    let remaining = &hunk[HUNK_KEEP_LINES + 1..];
532    let added = remaining
533        .iter()
534        .filter(|line| line.starts_with('+'))
535        .count();
536    let removed = remaining
537        .iter()
538        .filter(|line| line.starts_with('-'))
539        .count();
540    result.push(format!(
541        "... +{} -{} in {} more lines",
542        added,
543        removed,
544        remaining.len()
545    ));
546}
547
548fn count_hunks(lines: &[String]) -> usize {
549    lines.iter().filter(|line| line.starts_with("@@")).count()
550}
551
552fn compress_log(output: &str) -> String {
553    if output.lines().any(|line| line.starts_with("commit ")) {
554        compress_full_format_log(output)
555    } else {
556        compress_oneline_log(output)
557    }
558}
559
560fn compress_full_format_log(output: &str) -> String {
561    let lines: Vec<&str> = output.lines().collect();
562    let mut blocks: Vec<usize> = Vec::new();
563    for (index, line) in lines.iter().enumerate() {
564        if line.starts_with("commit ") {
565            blocks.push(index);
566        }
567    }
568    if blocks.is_empty() {
569        return trim_trailing_lines(output);
570    }
571
572    let mut result = Vec::new();
573    for (block_index, &start) in blocks.iter().enumerate() {
574        let end = blocks.get(block_index + 1).copied().unwrap_or(lines.len());
575        let block = &lines[start..end];
576        if let Some(compact) = format_log_commit_block(block) {
577            result.push(compact);
578        }
579    }
580
581    trim_trailing_lines(&result.join("\n"))
582}
583
584fn format_log_commit_block(block: &[&str]) -> Option<String> {
585    let first = block.first()?;
586    let full_hash = first.strip_prefix("commit ")?.trim();
587    let short_hash = abbreviate_log_hash(full_hash);
588
589    let mut merge_parents: Option<String> = None;
590    let mut author: Option<String> = None;
591    let mut date_compact: Option<String> = None;
592    let mut header_end = 1usize;
593
594    for (offset, line) in block.iter().enumerate().skip(1) {
595        if line.starts_with("Merge: ") {
596            let rest = line.strip_prefix("Merge: ").unwrap_or("");
597            let parents: Vec<String> = rest.split_whitespace().map(abbreviate_log_hash).collect();
598            merge_parents = Some(format!("Merge: {}", parents.join(" ")));
599            header_end = offset + 1;
600        } else if let Some(rest) = line.strip_prefix("Author: ") {
601            author = Some(format_author_compact(rest.trim()));
602            header_end = offset + 1;
603        } else if let Some(rest) = line.strip_prefix("Date: ") {
604            date_compact = Some(compact_git_log_date(rest.trim()));
605            header_end = offset + 1;
606        } else if line.trim().is_empty() {
607            header_end = offset + 1;
608            break;
609        } else {
610            break;
611        }
612    }
613
614    let mut body_iter = block[header_end..].iter().copied();
615    let mut subject = String::new();
616    let mut body_rest = Vec::new();
617    if let Some(first_body) = body_iter.next() {
618        subject = first_body.trim().to_string();
619        for line in body_iter {
620            body_rest.push(normalize_log_body_line(line));
621        }
622    }
623
624    let author = author.unwrap_or_default();
625    let date_compact = date_compact.unwrap_or_default();
626    let mut header = format!("{short_hash} {subject}");
627    if let Some(merge) = merge_parents {
628        header = format!("{short_hash} {merge} {subject}");
629    }
630    if !author.is_empty() {
631        header.push_str(&format!("  {author}"));
632    }
633    if !date_compact.is_empty() {
634        header.push(' ');
635        header.push_str(&date_compact);
636    }
637
638    let mut out = header;
639    for line in collapse_log_body_blank_runs(&body_rest) {
640        out.push('\n');
641        out.push_str(&line);
642    }
643    Some(out)
644}
645
646fn normalize_log_body_line(line: &str) -> String {
647    if line.starts_with(' ') || line.starts_with('\t') {
648        format!("    {}", line.trim_start())
649    } else {
650        format!("    {line}")
651    }
652}
653
654fn collapse_log_body_blank_runs(body: &[String]) -> Vec<String> {
655    body.iter()
656        .filter(|line| !line.trim().is_empty())
657        .cloned()
658        .collect()
659}
660
661fn format_author_compact(author: &str) -> String {
662    if let Some((name, email)) = author.split_once('<') {
663        let name = name.trim();
664        let email = email.trim_end_matches('>').trim();
665        format!("<{name} {email}>")
666    } else {
667        format!("<{author}>")
668    }
669}
670
671fn abbreviate_log_hash(hash: &str) -> String {
672    let hash = hash.trim();
673    if hash.len() <= LOG_SHORT_HASH_LEN {
674        hash.to_string()
675    } else {
676        hash[..LOG_SHORT_HASH_LEN].to_string()
677    }
678}
679
680fn compact_git_log_date(date_field: &str) -> String {
681    let parts: Vec<&str> = date_field.split_whitespace().collect();
682    if parts.len() < 5 {
683        return date_field.to_string();
684    }
685    let month = parts[1];
686    let day = parts[2];
687    let time = parts[3];
688    let year = parts[4];
689    let month_num = match month {
690        "Jan" => "01",
691        "Feb" => "02",
692        "Mar" => "03",
693        "Apr" => "04",
694        "May" => "05",
695        "Jun" => "06",
696        "Jul" => "07",
697        "Aug" => "08",
698        "Sep" => "09",
699        "Oct" => "10",
700        "Nov" => "11",
701        "Dec" => "12",
702        _ => return date_field.to_string(),
703    };
704    let day_padded = if day.len() == 1 {
705        format!("0{day}")
706    } else {
707        day.to_string()
708    };
709    format!("{year}-{month_num}-{day_padded} {time}")
710}
711
712fn compress_oneline_log(output: &str) -> String {
713    let result: Vec<String> = output
714        .lines()
715        .filter(|line| !line.trim().is_empty())
716        .map(|line| {
717            if looks_like_oneline_commit(line) {
718                let mut parts = line.splitn(2, ' ');
719                let hash = parts.next().unwrap_or("");
720                let rest = parts.next().unwrap_or("");
721                let short = abbreviate_log_hash(hash);
722                if rest.is_empty() {
723                    short
724                } else {
725                    format!("{short} {rest}")
726                }
727            } else {
728                line.trim_end().to_string()
729            }
730        })
731        .collect();
732    trim_trailing_lines(&result.join("\n"))
733}
734
735fn looks_like_oneline_commit(line: &str) -> bool {
736    let Some((hash, _message)) = line.split_once(' ') else {
737        return false;
738    };
739    (7..=40).contains(&hash.len()) && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
740}
741
742fn compress_blame(output: &str) -> String {
743    let total = output.lines().count();
744    if total <= BLAME_KEEP_LINES {
745        return trim_trailing_lines(output);
746    }
747
748    let mut result: Vec<String> = output
749        .lines()
750        .take(BLAME_KEEP_LINES)
751        .map(ToString::to_string)
752        .collect();
753    result.push(format!("... {} more blame lines", total - BLAME_KEEP_LINES));
754    result.join("\n")
755}
756
757fn trim_trailing_lines(input: &str) -> String {
758    input
759        .lines()
760        .map(str::trim_end)
761        .collect::<Vec<_>>()
762        .join("\n")
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768    use crate::compress::Compressor;
769
770    fn compress(command: &str, output: &str) -> CompressionResult {
771        GitCompressor.compress(command, output)
772    }
773
774    #[test]
775    fn test_add_empty_output_ok() {
776        let compressed = compress("git add .", "");
777        assert_eq!(compressed, "git: ok");
778    }
779    #[test]
780    fn test_add_verbose_many_files() {
781        let raw = "add 'src/a.rs'\nadd 'src/b.rs'\nadd 'src/c.rs'\nadd 'src/d.rs'\nadd 'src/e.rs'\nadd 'src/f.rs'\nadd 'src/g.rs'\n";
782        let compressed = compress("git add --verbose .", raw);
783        assert!(compressed.contains("add 'src/a.rs'"));
784        assert!(compressed.contains("add 'src/e.rs'"));
785        assert!(compressed.contains("... (2 more files added)"));
786        assert!(!compressed.contains("add 'src/g.rs'"));
787    }
788    #[test]
789    fn test_add_error_passthrough() {
790        let raw = "fatal: pathspec 'missing.rs' did not match any files\n";
791        let compressed = compress("git add missing.rs", raw);
792        assert_eq!(
793            compressed,
794            "fatal: pathspec 'missing.rs' did not match any files"
795        );
796    }
797    #[test]
798    fn test_commit_success_extracts_subject_and_summary() {
799        let raw = "[main 1a2b3c4] add git write compression\n 3 files changed, 42 insertions(+), 7 deletions(-)\n create mode 100644 crates/aft/src/foo.rs\n rewrite crates/aft/src/bar.rs (80%)\n";
800        let compressed = compress("git commit -m 'add git write compression'", raw);
801        assert_eq!(
802            compressed,
803            "[main 1a2b3c4] add git write compression\n3 files changed, 42 insertions(+), 7 deletions(-)"
804        );
805    }
806    #[test]
807    fn test_commit_nothing_to_commit_verbatim() {
808        let raw = "On branch main\nnothing to commit, working tree clean\n";
809        let compressed = compress("git commit -m noop", raw);
810        assert_eq!(compressed, "nothing to commit, working tree clean");
811    }
812    #[test]
813    fn test_commit_error_passthrough() {
814        let raw = "error: Committing is not possible because you have unmerged files.\nhint: Fix them up in the work tree, and then use 'git add/rm <file>'\nfatal: Exiting because of an unresolved conflict.\n";
815        let compressed = compress("git commit", raw);
816        assert!(compressed.contains("error: Committing is not possible"));
817        assert!(compressed.contains("fatal: Exiting because of an unresolved conflict."));
818    }
819    #[test]
820    fn test_push_success_drops_progress_keeps_remote_and_ref() {
821        let raw = "Counting objects: 12, done.\nDelta compression using up to 8 threads\nCompressing objects: 100% (7/7), done.\nWriting objects: 100% (7/7), 1.23 KiB | 1.23 MiB/s, done.\nTotal 7 (delta 4), reused 0 (delta 0), pack-reused 0\nremote: Resolving deltas: 100% (4/4), completed with 4 local objects.\nTo github.com:example/repo.git\n   9d8c7b6..1a2b3c4  main -> main\n";
822        let compressed = compress("git push", raw);
823        assert_eq!(
824            compressed,
825            "To github.com:example/repo.git\n   9d8c7b6..1a2b3c4  main -> main"
826        );
827    }
828    #[test]
829    fn test_push_everything_up_to_date_and_empty() {
830        assert_eq!(
831            compress("git push", "Everything up-to-date\n"),
832            "Everything up-to-date"
833        );
834        assert_eq!(compress("git push", ""), "");
835    }
836    #[test]
837    fn test_push_error_passthrough() {
838        let raw = "To github.com:example/repo.git\n ! [rejected]        main -> main (fetch first)\nerror: failed to push some refs to 'github.com:example/repo.git'\n";
839        let compressed = compress("git push", raw);
840        assert!(compressed.contains("! [rejected]        main -> main (fetch first)"));
841        assert!(compressed.contains("error: failed to push some refs"));
842    }
843    #[test]
844    fn test_pull_fast_forward_keeps_summary() {
845        let raw = "remote: Enumerating objects: 9, done.\nremote: Counting objects: 100% (9/9), done.\nFrom github.com:example/repo\n   1111111..2222222  main       -> origin/main\nUpdating 1111111..2222222\nFast-forward\n crates/aft/src/compress/git.rs | 12 +++++++++---\n 1 file changed, 9 insertions(+), 3 deletions(-)\n";
846        let compressed = compress("git pull --ff-only", raw);
847        assert_eq!(
848            compressed,
849            "Updating 1111111..2222222\nFast-forward\n 1 file changed, 9 insertions(+), 3 deletions(-)"
850        );
851    }
852    #[test]
853    fn test_pull_already_up_to_date_empty_and_error() {
854        assert_eq!(
855            compress("git pull", "Already up to date.\n"),
856            "Already up to date."
857        );
858        assert_eq!(compress("git pull", ""), "");
859        let raw = "CONFLICT (content): Merge conflict in README.md\nAutomatic merge failed; fix conflicts and then commit the result.\n";
860        let compressed = compress("git pull", raw);
861        assert!(compressed.contains("CONFLICT (content): Merge conflict in README.md"));
862        assert!(compressed.contains("Automatic merge failed"));
863    }
864    #[test]
865    fn test_fetch_success_empty_and_error() {
866        let raw = "remote: Enumerating objects: 5, done.\nremote: Counting objects: 100% (5/5), done.\nFrom github.com:example/repo\n * [new branch]      feature/git-compress -> origin/feature/git-compress\n   abc1234..def5678  main                 -> origin/main\n";
867        let compressed = compress("git fetch --all", raw);
868        assert_eq!(
869            compressed,
870            "From github.com:example/repo\n * [new branch]      feature/git-compress -> origin/feature/git-compress\n   abc1234..def5678  main                 -> origin/main"
871        );
872        assert_eq!(compress("git fetch", "   \n"), "git fetch: ok");
873        let error =
874            "fatal: unable to access 'https://example.invalid/repo.git/': Could not resolve host\n";
875        assert_eq!(
876            compress("git fetch", error),
877            "fatal: unable to access 'https://example.invalid/repo.git/': Could not resolve host"
878        );
879    }
880    #[test]
881    fn test_stash_push_pop_list_empty_and_error() {
882        let push = "Saved working directory and index state WIP on main: 1a2b3c4 add tests\nHEAD is now at 1a2b3c4 add tests\n";
883        assert_eq!(
884            compress("git stash push", push),
885            "Saved working directory and index state WIP on main: 1a2b3c4 add tests"
886        );
887        let pop = "On branch main\nChanges not staged for commit:\n  (use \"git add <file>...\" to update what will be committed)\n\tmodified:   README.md\nDropped refs/stash@{0} (abc123456789)\n";
888        let compressed_pop = compress("git stash pop", pop);
889        assert!(compressed_pop.contains("On branch main"));
890        assert!(compressed_pop.contains("Dropped refs/stash@{0}"));
891        let list = "stash@{0}: WIP on main: 1111111 first\nstash@{1}: On feature: second\n";
892        assert_eq!(compress("git stash list", list), list.trim_end());
893        assert_eq!(compress("git stash", ""), "");
894        let error = "error: Your local changes to the following files would be overwritten by merge:\n\tREADME.md\n";
895        let compressed_error = compress("git stash apply", error);
896        assert!(compressed_error.contains("error: Your local changes"));
897        assert!(compressed_error.contains("README.md"));
898    }
899
900    #[test]
901    fn test_log_merge_commit_keeps_parents() {
902        let raw = "commit cccccccccccccccccccccccccccccccccccc\nMerge: dddddddddddddddddddddddddddddddddddd eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\nAuthor: Merger <merge@example.com>\nDate:   Mon Jan 01 12:00:00 2024 +0000\n\n    Merge branch 'feature'\n";
903        let compressed = compress("git log", raw);
904        assert!(compressed.contains("Merge: dddddddddddd eeeeeeeeeeee"));
905        assert!(compressed.contains("Merge branch 'feature'"));
906    }
907
908    #[test]
909    fn test_log_format_collapse_short_log() {
910        let raw = "commit aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nAuthor: Alice Example <alice@example.com>\nDate:   Thu Jun 18 17:39:12 2026 +0200\n\n    first subject\n    detail one\n\ncommit bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\nAuthor: Bob Example <bob@example.com>\nDate:   Wed Jun 17 10:00:00 2026 +0000\n\n    second subject\n";
911        let compressed = compress("git log", raw);
912        assert!(!compressed.contains("commit "));
913        assert!(!compressed.contains("Author:"));
914        assert!(!compressed.contains("Date:"));
915        assert!(compressed.contains("aaaaaaaaaaaa first subject"));
916        assert!(compressed.contains("<Alice Example alice@example.com>"));
917        assert!(compressed.contains("2026-06-18 17:39:12"));
918        assert!(compressed.contains("detail one"));
919        assert!(compressed.contains("bbbbbbbbbbbb second subject"));
920        assert!(!compressed.contains(" ago"));
921        assert!(compressed.len() < raw.len());
922    }
923
924    #[test]
925    fn test_log_compress_is_deterministic() {
926        let raw = "commit 1111111111111111111111111111111111111111\nAuthor: x <x@y.com>\nDate:   Thu Jun 18 17:39:12 2026 +0200\n\n    subject\n    body\n";
927        let a = compress_log(raw);
928        let b = compress_log(raw);
929        assert_eq!(a, b);
930        assert!(a.contains("111111111111"));
931        assert!(a.contains("2026-06-18 17:39:12"));
932    }
933
934    #[test]
935    fn test_log_oneline_abbreviates_hash_keeps_all_lines() {
936        let raw = "e4e8f7e1234567890abcdef1234567890abcdef (HEAD -> main) chore\n9c4aa18abcdef1234567890abcdef1234567890 feat\n";
937        let compressed = compress("git log --oneline", raw);
938        assert!(compressed.contains("e4e8f7e12345"));
939        assert!(compressed.contains("(HEAD -> main) chore"));
940        assert!(compressed.contains("9c4aa18abcde"));
941        assert!(compressed.contains("feat"));
942        assert!(!compressed.contains("... more commits"));
943    }
944
945    #[test]
946    fn test_log_deep_needle_survives_without_drop_line() {
947        let raw = include_str!("../../../aft/tests/fixtures/git_log_deep_needle.txt");
948        let compressed = compress("git log", raw);
949        assert!(compressed.contains("feedfacefeed"));
950        assert!(compressed.contains("NEEDLE_GIT_auth_bypass"));
951        assert!(compressed.contains("UNIQUE_BODY_MARKER_needle_xyz"));
952        assert!(!compressed.contains("... more commits"));
953        assert!(compressed.len() < raw.len());
954    }
955
956    #[test]
957    fn git_subcommand_returns_none_for_pipe_before_subcommand() {
958        assert_eq!(git_subcommand("git --no-pager | grep log"), None);
959    }
960
961    #[test]
962    fn git_subcommand_returns_subcommand_when_before_pipe() {
963        assert_eq!(git_subcommand("git log | grep fix").as_deref(), Some("log"));
964    }
965
966    #[test]
967    fn git_subcommand_returns_none_for_redirect_before_subcommand() {
968        assert_eq!(git_subcommand("git --no-pager > out.log"), None);
969    }
970
971    #[test]
972    fn git_subcommand_unaffected_without_metacharacters() {
973        assert_eq!(git_subcommand("git log --oneline").as_deref(), Some("log"));
974    }
975}
976
977#[cfg(any(test, feature = "test-support"))]
978mod audit_regressions {
979    #[test]
980    fn git_global_options_before_subcommand() {
981        assert_eq!(super::git_subcommand("git -C | head"), None);
982        assert_eq!(super::git_subcommand("git -C"), None);
983        assert_eq!(
984            super::git_subcommand_after("git -C /repo remote add", "remote").as_deref(),
985            Some("add")
986        );
987        for command in [
988            "git -C /repo log",
989            "git -c k=v log",
990            "git --no-pager log",
991            "git --git-dir /repo log",
992            "git --work-tree /repo log",
993            "git --git-dir=/repo log",
994            "git -C/repo log",
995            "git --namespace ns log",
996        ] {
997            assert_eq!(
998                super::git_subcommand(command).as_deref(),
999                Some("log"),
1000                "{command}"
1001            );
1002        }
1003    }
1004}