repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/diff-review/search.ts
RawFile outline
export type SearchEntry = {
file: string;
side: "additions" | "deletions";
line: number;
text: string;
};
export type SearchMatch = SearchEntry & {
matchStart: number;
matchEnd: number;
};
export function buildSearchIndex(diffText: string): SearchEntry[] {
const entries: SearchEntry[] = [];
const lines = diffText.split(/\r?\n/);
let currentFile = "";
let oldLine = 0;
let newLine = 0;
let inHunk = false;
for (const line of lines) {
if (line.startsWith("diff --git ")) {
currentFile = parseFileFromDiffGit(line);
oldLine = 0;
newLine = 0;
inHunk = false;
continue;
}
if (line.startsWith("@@")) {
const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
if (match) {
oldLine = Number(match[1]);
newLine = Number(match[2]);
inHunk = true;
}
continue;
}
if (!inHunk || !currentFile || line.startsWith("\\")) continue;
if (line.startsWith("+")) {
entries.push({
file: currentFile,
side: "additions",
line: newLine,
text: line.slice(1),
});
newLine++;
} else if (line.startsWith("-")) {
entries.push({
file: currentFile,
side: "deletions",
line: oldLine,
text: line.slice(1),
});
oldLine++;
} else if (line.startsWith(" ")) {
entries.push({
file: currentFile,
side: "additions",
line: newLine,
text: line.slice(1),
});
oldLine++;
newLine++;
}
}
return entries;
}
export function searchCode(query: string, index: SearchEntry[]): SearchMatch[] {
const hits: SearchMatch[] = [];
const trimmed = query.trim();
if (!trimmed) return hits;
const isRegex = trimmed.startsWith("/") && trimmed.endsWith("/");
const pattern = isRegex
? trimmed.slice(1, -1)
: trimmed.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
let re: RegExp;
try {
re = new RegExp(pattern, "i");
} catch {
return hits;
}
for (const entry of index) {
const m = re.exec(entry.text);
if (m && m.index >= 0) {
hits.push({
...entry,
matchStart: m.index,
matchEnd: m.index + m[0].length,
});
if (hits.length >= 500) break;
}
}
return hits;
}
function parseFileFromDiffGit(line: string): string {
const match = /^diff --git a\/(.+) b\/(.+)$/.exec(line);
return match?.[2] ?? "";
}