Skip to main content

aft_base/compress/
generic.rs

1use crate::compress::{CompressionResult, Compressor};
2
3pub fn strip_ansi(input: &str) -> String {
4    let stripped = strip_ansi_cow(input);
5    #[cfg(any(test, feature = "test-support"))]
6    if matches!(stripped, std::borrow::Cow::Borrowed(_)) {
7        ANSI_STRIP_ALLOC_BYTES.with(|bytes| bytes.set(bytes.get() + input.len()));
8    }
9    stripped.into_owned()
10}
11
12/// Borrow plain text; ANSI-bearing input still uses the exact same stripping
13/// grammar. Dispatch and its output probe can share this single derived view.
14pub(super) fn strip_ansi_cow(input: &str) -> std::borrow::Cow<'_, str> {
15    record_ansi_strip();
16    let bytes = input.as_bytes();
17    let Some(mut index) = bytes.iter().position(|byte| *byte == 0x1b) else {
18        return std::borrow::Cow::Borrowed(input);
19    };
20    let mut output = String::with_capacity(input.len());
21    #[cfg(any(test, feature = "test-support"))]
22    ANSI_STRIP_ALLOC_BYTES.with(|bytes| bytes.set(bytes.get() + output.capacity()));
23    let mut last_kept = 0;
24
25    while index < bytes.len() {
26        if bytes[index] != 0x1b {
27            index += 1;
28            continue;
29        }
30
31        let Some(next) = bytes.get(index + 1).copied() else {
32            break;
33        };
34
35        let end = if next == b'[' {
36            let mut cursor = index + 2;
37            while cursor < bytes.len() {
38                if (0x40..=0x7e).contains(&bytes[cursor]) {
39                    cursor += 1;
40                    break;
41                }
42                cursor += 1;
43            }
44            cursor
45        } else if (0x40..=0x5f).contains(&next) {
46            index + 2
47        } else {
48            index += 1;
49            continue;
50        };
51
52        output.push_str(&input[last_kept..index]);
53        index = end.min(bytes.len());
54        last_kept = index;
55    }
56
57    output.push_str(&input[last_kept..]);
58    std::borrow::Cow::Owned(output)
59}
60
61pub fn dedup_consecutive(input: &str) -> String {
62    let had_trailing_newline = input.ends_with('\n');
63    let mut output = String::with_capacity(input.len());
64    let mut lines = input.lines();
65
66    let Some(mut current) = lines.next() else {
67        return String::new();
68    };
69    let mut count = 1usize;
70
71    for line in lines {
72        if line == current {
73            count += 1;
74        } else {
75            push_dedup_run(&mut output, current, count);
76            current = line;
77            count = 1;
78        }
79    }
80    push_dedup_run(&mut output, current, count);
81
82    if !had_trailing_newline {
83        output.pop();
84    }
85
86    output
87}
88
89fn push_dedup_run(output: &mut String, line: &str, count: usize) {
90    output.push_str(line);
91    output.push('\n');
92    if count >= 4 {
93        output.push_str("... (");
94        output.push_str(&(count - 1).to_string());
95        output.push_str(" more)\n");
96    } else {
97        for _ in 1..count {
98            output.push_str(line);
99            output.push('\n');
100        }
101    }
102}
103
104pub fn middle_truncate(
105    input: &str,
106    threshold_bytes: usize,
107    keep_head: usize,
108    keep_tail: usize,
109) -> String {
110    if input.len() <= threshold_bytes {
111        return input.to_string();
112    }
113
114    let head_end = floor_char_boundary(input, keep_head.min(input.len()));
115    let tail_start = ceil_char_boundary(input, input.len().saturating_sub(keep_tail));
116
117    if head_end >= tail_start {
118        return input.to_string();
119    }
120
121    let truncated_bytes = tail_start - head_end;
122    let mut output = String::with_capacity(head_end + keep_tail + 64);
123    output.push_str(&input[..head_end]);
124    if !output.ends_with('\n') {
125        output.push('\n');
126    }
127    output.push_str("...<truncated ");
128    output.push_str(&truncated_bytes.to_string());
129    output.push_str(" bytes>...\n");
130    output.push_str(&input[tail_start..]);
131    output
132}
133
134pub fn floor_char_boundary(input: &str, mut index: usize) -> usize {
135    while index > 0 && !input.is_char_boundary(index) {
136        index -= 1;
137    }
138    index
139}
140
141pub fn ceil_char_boundary(input: &str, mut index: usize) -> usize {
142    while index < input.len() && !input.is_char_boundary(index) {
143        index += 1;
144    }
145    index
146}
147
148pub struct GenericCompressor;
149
150impl GenericCompressor {
151    pub fn compress_output(output: &str) -> String {
152        let stripped = strip_ansi(output);
153        Self::compress_stripped_output(&stripped)
154    }
155
156    pub(crate) fn compress_stripped_output(output: &str) -> String {
157        dedup_consecutive(output)
158    }
159}
160
161#[cfg(any(test, feature = "test-support"))]
162thread_local! {
163    static ANSI_STRIP_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
164    static ANSI_STRIP_ALLOC_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
165}
166
167#[cfg(any(test, feature = "test-support"))]
168fn record_ansi_strip() {
169    ANSI_STRIP_COUNT.with(|count| count.set(count.get() + 1));
170}
171
172#[cfg(all(debug_assertions, any(test, feature = "test-support")))]
173#[cfg_attr(not(test), allow(dead_code))]
174pub(super) fn reset_ansi_strip_alloc_bytes() {
175    ANSI_STRIP_ALLOC_BYTES.with(|bytes| bytes.set(0));
176}
177
178#[cfg(all(debug_assertions, any(test, feature = "test-support")))]
179#[cfg_attr(not(test), allow(dead_code))]
180pub(super) fn ansi_strip_alloc_bytes() -> usize {
181    ANSI_STRIP_ALLOC_BYTES.with(std::cell::Cell::get)
182}
183
184#[cfg(not(any(test, feature = "test-support")))]
185fn record_ansi_strip() {}
186
187#[cfg(any(test, feature = "test-support"))]
188#[cfg_attr(not(test), allow(dead_code))]
189pub(crate) fn reset_ansi_strip_count() {
190    ANSI_STRIP_COUNT.with(|count| count.set(0));
191}
192
193#[cfg(any(test, feature = "test-support"))]
194#[cfg_attr(not(test), allow(dead_code))]
195pub(crate) fn ansi_strip_count() -> usize {
196    ANSI_STRIP_COUNT.with(std::cell::Cell::get)
197}
198
199impl Compressor for GenericCompressor {
200    fn matches(&self, _command: &str) -> bool {
201        true
202    }
203
204    fn compress_with_exit_code(
205        &self,
206        _command: &str,
207        output: &str,
208        _exit_code: Option<i64>,
209    ) -> CompressionResult {
210        Self::compress_output(output).into()
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn generic_does_not_pretruncate_above_old_five_kib_threshold() {
220        let input = (0..900)
221            .map(|idx| format!("unique-line-{idx:04}"))
222            .collect::<Vec<_>>()
223            .join("\n");
224        assert!(input.len() > 5 * 1024);
225
226        let compressed = GenericCompressor::compress_output(&input);
227
228        assert!(!compressed.contains("...<truncated "));
229        assert!(compressed.len() > 5 * 1024);
230        assert!(compressed.contains("unique-line-0000"));
231        assert!(compressed.contains("unique-line-0899"));
232    }
233}