Skip to main content

lean_ctx/core/patterns/
grep.rs

1use std::collections::HashMap;
2
3use crate::core::tokens::count_tokens;
4
5fn normalize_shell_tokens(text: &str) -> String {
6    text.split_whitespace().collect::<Vec<_>>().join(" ")
7}
8
9/// One rendered line: a match, or a context line around one.
10#[derive(Clone, Copy)]
11struct Entry<'a> {
12    line_num: usize,
13    content: &'a str,
14    is_match: bool,
15}
16
17pub fn compress(output: &str) -> Option<String> {
18    let lines: Vec<&str> = output.lines().collect();
19    if lines.len() < 3 {
20        return None;
21    }
22
23    let mut by_file: HashMap<&str, Vec<Entry<'_>>> = HashMap::new();
24    let mut total_matches = 0usize;
25
26    // Pass 1 — matches only (`path:line:content`).
27    for line in &lines {
28        if let Some((file, line_num, content)) = parse_match_line(line) {
29            total_matches += 1;
30            by_file.entry(file).or_default().push(Entry {
31                line_num,
32                content,
33                is_match: true,
34            });
35        }
36    }
37
38    if total_matches == 0 {
39        return None;
40    }
41
42    // Pass 2 — context (`path-line-content`), resolved against the paths pass 1
43    // already proved exist (GH #1648).
44    //
45    // Doing it this way, rather than scanning for a `-digits-` delimiter, is
46    // what makes it unambiguous: both a path and the context text may contain
47    // hyphens and digits, but grep only emits context for a file it also
48    // matched in, so the path is always one we have already seen.
49    let known: Vec<&str> = by_file.keys().copied().collect();
50    for line in &lines {
51        if parse_match_line(line).is_some() {
52            continue;
53        }
54        if let Some((file, line_num, content)) = parse_context_line(line, &known) {
55            by_file.entry(file).or_default().push(Entry {
56                line_num,
57                content,
58                is_match: false,
59            });
60        }
61        // Anything else — grep's `--` group separators, stray text — is
62        // dropped. It used to become a synthetic file with empty content,
63        // inflating both the file and the match count.
64    }
65
66    let max_matches_per_file = if total_matches > 200 { 5 } else { 10 };
67
68    let mut result = format!("{total_matches} matches in {}F:\n", by_file.len());
69    let mut sorted_files: Vec<_> = by_file.iter_mut().collect();
70    sorted_files.sort_by(|a, b| {
71        let am = a.1.iter().filter(|e| e.is_match).count();
72        let bm = b.1.iter().filter(|e| e.is_match).count();
73        bm.cmp(&am).then_with(|| a.0.cmp(b.0))
74    });
75
76    for (file, entries) in &mut sorted_files {
77        entries.sort_by_key(|e| (e.line_num, !e.is_match));
78        let match_count = entries.iter().filter(|e| e.is_match).count();
79        let short = shorten_path(file);
80        result.push_str(&format!("\n{short} ({match_count}):"));
81
82        // The cap counts *matches*, and any context around a shown match comes
83        // with it — capping raw lines would silently drop matches once context
84        // was requested.
85        let mut shown_matches = 0usize;
86        for entry in entries.iter() {
87            if entry.is_match {
88                if shown_matches == max_matches_per_file {
89                    break;
90                }
91                shown_matches += 1;
92            }
93            let trimmed = entry.content.trim();
94            let short_content = if trimmed.len() > 120 {
95                let truncated: String = trimmed.chars().take(119).collect();
96                format!("{truncated}…")
97            } else {
98                trimmed.to_string()
99            };
100            // grep's own convention: `:` marks a match, `-` marks context.
101            let sep = if entry.is_match { ':' } else { '-' };
102            if entry.line_num > 0 {
103                result.push_str(&format!("\n  {}{sep} {short_content}", entry.line_num));
104            } else {
105                result.push_str(&format!("\n  {short_content}"));
106            }
107        }
108        if match_count > shown_matches {
109            result.push_str(&format!("\n  ... +{} more", match_count - shown_matches));
110        }
111    }
112
113    let out_n = normalize_shell_tokens(output);
114    let res_n = normalize_shell_tokens(&result);
115    let ct_r = count_tokens(&res_n);
116    let ct_o = count_tokens(&out_n);
117    if ct_r >= ct_o && !(ct_r == ct_o && res_n.len() < out_n.len()) {
118        return None;
119    }
120
121    Some(result)
122}
123
124/// Parse a match line: `path:line:content`.
125///
126/// The delimiter is the first colon *followed by digits and another colon* —
127/// not simply the first colon on the line (GH #1648). The old rule split
128/// `…/mod_1.py-2-    try:` at the colon inside the Python source, inventing a
129/// file named after the whole fragment.
130fn parse_match_line(line: &str) -> Option<(&str, usize, &str)> {
131    // Skip a Windows drive letter (e.g. "C:" at position 1).
132    let start = if line.len() >= 2
133        && line.as_bytes()[0].is_ascii_alphabetic()
134        && line.as_bytes()[1] == b':'
135    {
136        2
137    } else {
138        0
139    };
140
141    let (file, line_num, content) = split_numbered(line, ':', start)?;
142    if file.contains('/') || file.contains('\\') || file.contains('.') {
143        Some((file, line_num, content))
144    } else {
145        None
146    }
147}
148
149/// Split `prefix<D><digits><D>rest` at the first delimiter that is actually
150/// followed by a line number.
151fn split_numbered(line: &str, delim: char, start: usize) -> Option<(&str, usize, &str)> {
152    let bytes = line.as_bytes();
153    let mut from = start;
154    while let Some(rel) = line[from..].find(delim) {
155        let at = from + rel;
156        let after = at + delim.len_utf8();
157        let digits = bytes[after..]
158            .iter()
159            .take_while(|b| b.is_ascii_digit())
160            .count();
161        if digits > 0 && bytes.get(after + digits).copied() == Some(delim as u8) {
162            let num = line[after..after + digits].parse().ok()?;
163            return Some((&line[..at], num, &line[after + digits + 1..]));
164        }
165        from = at + delim.len_utf8();
166    }
167    None
168}
169
170/// Parse a context line: `path-line-content`, where `path` is one grep already
171/// reported a match in.
172///
173/// Anchoring on a known path rather than scanning for `-digits-` is what keeps
174/// this unambiguous: `src/v-1-x/mod.py-10-ctx` has three candidate delimiters
175/// and only one correct answer.
176fn parse_context_line<'a>(line: &'a str, known: &[&'a str]) -> Option<(&'a str, usize, &'a str)> {
177    for file in known {
178        let Some(rest) = line.strip_prefix(*file).and_then(|r| r.strip_prefix('-')) else {
179            continue;
180        };
181        let digits = rest
182            .as_bytes()
183            .iter()
184            .take_while(|b| b.is_ascii_digit())
185            .count();
186        if digits > 0 && rest.as_bytes().get(digits).copied() == Some(b'-') {
187            let num = rest[..digits].parse().ok()?;
188            return Some((file, num, &rest[digits + 1..]));
189        }
190    }
191    None
192}
193
194fn shorten_path(path: &str) -> &str {
195    path.strip_prefix("./").unwrap_or(path)
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn small_grep_output_is_not_claimed_without_matches() {
204        assert!(compress("hello\nworld").is_none());
205    }
206
207    #[test]
208    fn small_grep_output_still_compresses() {
209        let output = (0..20)
210            .map(|i| format!("src/main.rs:{i}: let x = {i};"))
211            .collect::<Vec<_>>()
212            .join("\n");
213        let result = compress(&output);
214        assert!(result.is_some());
215        let compressed = result.unwrap();
216        assert!(
217            compressed.contains("20 matches in 1F:"),
218            "should group by file: {compressed}"
219        );
220        assert!(
221            count_tokens(&compressed) < count_tokens(&output),
222            "should compress: {} vs {}",
223            count_tokens(&compressed),
224            count_tokens(&output)
225        );
226    }
227
228    #[test]
229    fn large_output_reduces_per_file_lines() {
230        let mut lines = Vec::new();
231        for i in 0..250 {
232            lines.push(format!("src/a.rs:{i}: line content {i}"));
233        }
234        let output = lines.join("\n");
235        let result = compress(&output).unwrap();
236        assert!(
237            result.contains("... +245 more"),
238            "should show +more for large output: {result}"
239        );
240    }
241
242    #[test]
243    fn non_grep_output_returns_none() {
244        let output = "no file:line pattern here\njust regular text\nmore text\nand more";
245        assert!(compress(output).is_none());
246    }
247
248    #[test]
249    fn tiny_grep_output_returns_none_if_inflation() {
250        let output = "a.rs:1:x\nb.rs:2:y\nc.rs:3:z\n";
251        let result = compress(output);
252        if let Some(ref compressed) = result {
253            assert!(
254                count_tokens(compressed) < count_tokens(output),
255                "must never inflate: compressed={} vs original={}",
256                count_tokens(compressed),
257                count_tokens(output)
258            );
259        }
260    }
261
262    #[test]
263    fn multi_file_many_matches_compresses_well() {
264        let mut lines = Vec::new();
265        for i in 0..50 {
266            lines.push(format!(
267                "src/models/user.rs:{}: pub fn method_{i}() {{}}",
268                i + 1
269            ));
270        }
271        for i in 0..30 {
272            lines.push(format!(
273                "src/controllers/auth.rs:{}: let val = method_{i}();",
274                i + 1
275            ));
276        }
277        let output = lines.join("\n");
278        let result = compress(&output).expect("80 matches should compress");
279        assert!(
280            count_tokens(&result) < count_tokens(&output),
281            "must compress: {} vs {}",
282            count_tokens(&result),
283            count_tokens(&output)
284        );
285        assert!(result.contains("80 matches in 2F:"));
286        assert!(result.contains("src/models/user.rs (50):"));
287        assert!(result.contains("src/controllers/auth.rs (30):"));
288    }
289
290    #[test]
291    fn many_single_match_files_falls_back_to_none() {
292        let lines: Vec<String> = (1..=30)
293            .map(|i| format!("src/file{i}.rs:42: fn search_result()"))
294            .collect();
295        let output = lines.join("\n");
296        let result = compress(&output);
297        if let Some(ref c) = result {
298            assert!(
299                count_tokens(c) < count_tokens(&output),
300                "if claimed, must be shorter in tokens: {} vs {}",
301                count_tokens(c),
302                count_tokens(&output)
303            );
304        }
305    }
306
307    #[test]
308    fn never_returns_inflated_output() {
309        for count in [3, 5, 10, 15, 25, 50] {
310            let lines: Vec<String> = (0..count).map(|i| format!("f{i}.rs:{i}:x")).collect();
311            let output = lines.join("\n");
312            if let Some(ref c) = compress(&output) {
313                assert!(
314                    count_tokens(c) < count_tokens(&output),
315                    "count={count}: inflated {} vs {}",
316                    count_tokens(c),
317                    count_tokens(&output)
318                );
319            }
320        }
321    }
322
323    // --- GH #1648: context lines (`path-line-text`) are not matches ---
324
325    /// The reporter's repro, reduced: 40 files, one match each, `-C 2`.
326    /// GNU grep separates a match with `:` and context with `-`; the parser
327    /// took the FIRST colon anywhere on the line, so `…/mod_1.py-2-    try:`
328    /// became a *file* named `…/mod_1.py-2-    try` with empty content —
329    /// counted as both a file and a match.
330    fn repro_with_context(files: usize) -> String {
331        let mut out = Vec::new();
332        for i in 1..=files {
333            let f = format!("/tmp/leanctx-grep-repro/mod_{i}.py");
334            out.push(format!("{f}-1-def handler_{i}():"));
335            out.push(format!("{f}-2-    try:"));
336            out.push(format!("{f}:3:        target_pattern_here()"));
337            out.push(format!("{f}-4-    except Exception:"));
338            out.push(format!("{f}-5-        pass"));
339            out.push("--".to_string());
340        }
341        out.join("\n")
342    }
343
344    #[test]
345    fn context_lines_do_not_become_files_or_matches() {
346        let result = compress(&repro_with_context(40)).expect("should compress");
347        assert!(
348            result.starts_with("40 matches in 40F:"),
349            "40 real matches in 40 files, not one per context line: {}",
350            result.lines().next().unwrap_or("")
351        );
352        assert!(
353            !result.contains("-2-"),
354            "a context line must not appear as a file header: {result}"
355        );
356        assert!(
357            !result.contains("try (1)"),
358            "text must not be truncated at a colon into a path: {result}"
359        );
360    }
361
362    /// The content the reporter lost. A context line whose text contains a
363    /// colon (Python, YAML, Go tags, prose) is exactly the case that broke.
364    #[test]
365    fn context_text_survives_intact() {
366        let result = compress(&repro_with_context(40)).expect("should compress");
367        assert!(
368            result.contains("try:"),
369            "the context line's own text, colon included, must survive: {result}"
370        );
371    }
372
373    /// `--` group separators are grep's, not data.
374    #[test]
375    fn group_separators_are_ignored() {
376        let out = (1..=20)
377            .map(|i| format!("a/b.rs-{}-ctx\na/b.rs:{i}:hit\n--", i * 10))
378            .collect::<Vec<_>>()
379            .join("\n");
380        let result = compress(&out).expect("should compress");
381        assert!(result.starts_with("20 matches in 1F:"), "{result}");
382    }
383
384    /// A path containing `-<digits>-` must not be mistaken for a context
385    /// delimiter. Context is resolved against paths already seen in match
386    /// lines, so the ambiguity never arises.
387    #[test]
388    fn a_hyphenated_path_is_not_split_as_context() {
389        let out = (1..=20)
390            .map(|i| format!("src/v-1-x/mod.py-{}-ctx\nsrc/v-1-x/mod.py:{i}:hit", i * 10))
391            .collect::<Vec<_>>()
392            .join("\n");
393        let result = compress(&out).expect("should compress");
394        assert!(
395            result.starts_with("20 matches in 1F:"),
396            "one file, not one per hyphen: {result}"
397        );
398    }
399}