Project Files
src / git / grep-parsing.ts
/**
* A single match returned by `git grep`.
*/
export interface GrepMatch {
/** Path of the matching file relative to the repository root. */
file: string
/** One-based line number of the match within the file. */
line: number
/** Content of the matching line. */
text: string
}
/**
* Regular expression that splits a `git grep -nz` record into file, line number, and content.
* The `-z` flag separates the three fields with NUL bytes so paths containing colons are unambiguous.
* The trailing `\r?` strips the carriage return that git grep emits for source files with CRLF endings.
*
* @const {RegExp}
* @default /^([^\0]+)\0(\d+)\0(.*)\r?$/
*/
const grepRecordRegex = /^([^\0]+)\0(\d+)\0(.*)\r?$/
/**
* Parses raw `git grep -nz` output into a typed list of matches.
*
* @param raw The raw stdout produced by `git grep -nz`.
* @returns The parsed match list.
*/
export function parseGrepOutput(raw: string): GrepMatch[] {
const matches: GrepMatch[] = []
for (const record of raw.split("\n")) {
const parsed = grepRecordRegex.exec(record)
if (parsed !== null) {
matches.push({ file: parsed[1], line: Number(parsed[2]), text: parsed[3] })
}
}
return matches
}