Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 1.6 KiBRawPermalink
1export function formatGrepSearchResults(results: string): string {
2 const keepLines: string[] = [];
3
4 function countLeadingSpaces(line: string) {
5 return line?.match(/^ */)?.[0].length ?? 0;
6 }
7
8 const processResult = (lines: string[]) => {
9 // Skip results in which only the file path was kept
10 const resultPath = lines[0];
11 const resultContent = lines.slice(1);
12 if (resultContent.length === 0) {
13 return;
14 }
15
16 // Add path
17 keepLines.push(resultPath);
18
19 // Find the minimum indentation of content lines
20 let minIndent = Infinity;
21 for (const line of resultContent) {
22 const indent = countLeadingSpaces(line);
23 if (indent < minIndent) {
24 minIndent = indent;
25 }
26 }
27
28 // Make all lines line up to 2-space indent
29 const changeIndentBy = 2 - minIndent;
30 if (changeIndentBy === 0) {
31 keepLines.push(...resultContent);
32 } else if (changeIndentBy < 0) {
33 keepLines.push(
34 ...resultContent.map((line) => line.substring(-changeIndentBy)),
35 );
36 } else {
37 keepLines.push(
38 ...resultContent.map((line) => " ".repeat(changeIndentBy) + line),
39 );
40 }
41 };
42
43 let resultLines: string[] = [];
44 for (const line of results.split("\n").filter((l) => !!l)) {
45 if (line.startsWith("./") || line === "--") {
46 processResult(resultLines); // process previous result
47 resultLines = [line];
48 continue;
49 }
50
51 // Exclude leading zero- or single-char lines
52 if (resultLines.length === 1 && line.trim().length <= 1) {
53 continue;
54 }
55
56 resultLines.push(line);
57 }
58 processResult(resultLines);
59
60 return keepLines.join("\n");
61}