Open History to see the last commit
1import { splitsSurrogatePair } from "./assistantCitations.ts";
2
3export interface GrepOutputResult {
4 readonly fileName: string;
5 readonly line?: number;
6 readonly preview?: string;
7}
8
9// Search results ride the timeline wire, so matched text shares one budget; later matches keep
10// their file and line without the text.
11const PREVIEW_BUDGET_CHARS = 8_000;
12const NOTE_MAX_CHARS = 500;
13
14const SUMMARY_LINE = /^(?:Found \d+ (?:match|file)|No (?:files|matches) found)/i;
15const NOTE_LINE = /^\(.*\)$/;
16const FILE_HEADING = /^File: (.+)$/;
17// OpenCode and Gemini put a space after the colon; ripgrep's `--heading` lines start right after it.
18const NUMBERED_LINE = /^\s*(?:(?:Line |L)(\d+): ?|(\d+):)(.*)$/;
19const CONTEXT_LINE = /^\s*\d+-/;
20const PATH_LINE_TEXT = /^(\S.*?):(\d+):(.*)$/;
21const COLON_HEADING = /^(\S.*):$/;
22const OPENCODE_NUMBERED_LINE = /^\s+Line \d+:/;
23const RIPGREP_NUMBERED_LINE = /^\d+:/;
24
25/**
26 * Grep tool text as one result per matched line, from ripgrep's `path:line:text` and `--heading`
27 * forms, OpenCode's `path:` / `Line N: text`, and Gemini's `File: path` / `LN: text`. Returns
28 * undefined unless every line fits, so listings, errors, and prose stay as the provider wrote them.
29 * Parenthesized notes such as truncation warnings stay, as one line-less result on `root`.
30 */
31export function parseGrepOutput(
32 output: string,
33 root: string,
34): ReadonlyArray<GrepOutputResult> | undefined {
35 const matches: Array<{ fileName: string; line: number; text: string }> = [];
36 const notes: string[] = [];
37 let file: string | undefined;
38 let ripgrepFormat: "heading" | "inline" | undefined;
39 const lines = output.split(/\r?\n/);
40 for (const [index, line] of lines.entries()) {
41 const trimmed = line.trim();
42 if (!trimmed) {
43 // ripgrep separates file groups with a blank line. OpenCode also uses blanks within a group.
44 if (ripgrepFormat === "heading") file = undefined;
45 continue;
46 }
47 if (trimmed === "--" || trimmed === "---" || SUMMARY_LINE.test(trimmed)) continue;
48 const heading = FILE_HEADING.exec(trimmed);
49 if (heading) {
50 file = heading[1];
51 ripgrepFormat = undefined;
52 continue;
53 }
54 const numbered = file === undefined ? null : NUMBERED_LINE.exec(line);
55 if (file !== undefined && numbered) {
56 const lineNumber = numbered[1] ?? numbered[2];
57 matches.push({ fileName: file, line: Number(lineNumber), text: numbered[3] ?? "" });
58 continue;
59 }
60 // ripgrep context lines (`N-text`) can't be told apart from a file named like one.
61 if (file !== undefined && CONTEXT_LINE.test(line)) return undefined;
62 const nextLine = lines[index + 1] ?? "";
63 // `dir/a:12:b.txt:` is both an inline match and an OpenCode heading; an indented `Line N:` next decides.
64 const colonHeading = COLON_HEADING.exec(line.trimEnd());
65 const inline =
66 colonHeading && OPENCODE_NUMBERED_LINE.test(nextLine) ? null : PATH_LINE_TEXT.exec(line);
67 if (ripgrepFormat !== "inline" && RIPGREP_NUMBERED_LINE.test(nextLine)) {
68 // Two inline rows can also look like a bare heading and its numbered match.
69 if (
70 ripgrepFormat === undefined &&
71 PATH_LINE_TEXT.test(nextLine) &&
72 PATH_LINE_TEXT.test(trimmed)
73 ) {
74 return undefined;
75 }
76 file = line;
77 ripgrepFormat = "heading";
78 continue;
79 }
80 if (inline) {
81 ripgrepFormat = "inline";
82 matches.push({ fileName: inline[1] ?? "", line: Number(inline[2]), text: inline[3] ?? "" });
83 continue;
84 }
85 if (colonHeading) {
86 file = colonHeading[1];
87 ripgrepFormat = undefined;
88 continue;
89 }
90 if (NOTE_LINE.test(trimmed)) {
91 notes.push(trimmed);
92 continue;
93 }
94 // With no numbered match after it, only a space-free bare path can be a heading.
95 if (!/\s/.test(line.trimEnd())) {
96 file = line;
97 ripgrepFormat = undefined;
98 continue;
99 }
100 return undefined;
101 }
102 if (matches.length === 0 || matches.some((match) => match.line < 1 || !match.fileName.trim())) {
103 return undefined;
104 }
105 const joinedNotes = notes.join("\n");
106 const note = joinedNotes.slice(
107 0,
108 splitsSurrogatePair(joinedNotes, NOTE_MAX_CHARS) ? NOTE_MAX_CHARS - 1 : NOTE_MAX_CHARS,
109 );
110 let budget = PREVIEW_BUDGET_CHARS - note.length;
111 const results: GrepOutputResult[] = matches.map((match) => {
112 const fits = match.text.length <= budget;
113 if (fits) budget -= match.text.length;
114 return { fileName: match.fileName, line: match.line, ...(fits ? { preview: match.text } : {}) };
115 });
116 return note ? [...results, { fileName: root, preview: note }] : results;
117}