lean_ctx/core/patterns/
grep.rs1use 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#[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 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 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 }
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 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 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
124fn parse_match_line(line: &str) -> Option<(&str, usize, &str)> {
131 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
149fn 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
170fn 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 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 #[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 #[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 #[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}