Elffuss BraidHub

kikocis/continue public

main · 2.3 KiBRawPermalink
1/*
2 Formats the output of a grep search to reduce unnecessary indentation, lines, etc
3 Assumes a command with these params
4 ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
5
6 Also can truncate the output to a specified number of characters
7*/
8export function formatGrepSearchResults(
9 results: string,
10 maxChars?: number,
11): {
12 formatted: string;
13 numResults: number;
14 truncated: boolean;
15} {
16 let numResults = 0;
17 const keepLines: string[] = [];
18
19 function countLeadingSpaces(line: string) {
20 return line?.match(/^ */)?.[0].length ?? 0;
21 }
22
23 const processResult = (lines: string[]) => {
24 // Skip results in which only the file path was kept
25 const resultPath = lines[0];
26 const resultContent = lines.slice(1);
27 if (resultContent.length === 0) {
28 return;
29 }
30
31 // Add path
32 keepLines.push(resultPath);
33
34 // Find the minimum indentation of content lines
35 let minIndent = Infinity;
36 for (const line of resultContent) {
37 const indent = countLeadingSpaces(line);
38 if (indent < minIndent) {
39 minIndent = indent;
40 }
41 }
42
43 // Make all lines line up to 2-space indent
44 const changeIndentBy = 2 - minIndent;
45 if (changeIndentBy === 0) {
46 keepLines.push(...resultContent);
47 } else if (changeIndentBy < 0) {
48 keepLines.push(
49 ...resultContent.map((line) => line.substring(-changeIndentBy)),
50 );
51 } else {
52 keepLines.push(
53 ...resultContent.map((line) => " ".repeat(changeIndentBy) + line),
54 );
55 }
56 };
57
58 let resultLines: string[] = [];
59 for (const line of results.split("\n").filter((l) => !!l)) {
60 if (line.startsWith("./") || line === "--") {
61 processResult(resultLines); // process previous result
62 resultLines = [line];
63 numResults++;
64 continue;
65 }
66
67 // Exclude leading zero- or single-char lines
68 if (resultLines.length === 1 && line.trim().length <= 1) {
69 continue;
70 }
71
72 resultLines.push(line);
73 }
74 processResult(resultLines);
75
76 const formatted = keepLines.join("\n");
77 if (maxChars && formatted.length > maxChars) {
78 return {
79 formatted: formatted.substring(0, maxChars),
80 numResults,
81 truncated: true,
82 };
83 } else {
84 return {
85 formatted,
86 numResults,
87 truncated: false,
88 };
89 }
90}