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 tokens = raw.split("\0")
const matches: GrepMatch[] = []
for (let i = 0; i + 2 < tokens.length; i += 3) {
const file = tokens[i]
const lineStr = tokens[i + 1]
const text = tokens[i + 2]
// Skip empty filenames or invalid line numbers
if (file.length === 0) continue
const line = Number(lineStr)
if (Number.isNaN(line)) continue
matches.push({ file, line, text })
}
return matches
}
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 tokens = raw.split("\0")
const matches: GrepMatch[] = []
for (let i = 0; i + 2 < tokens.length; i += 3) {
const file = tokens[i]
const lineStr = tokens[i + 1]
const text = tokens[i + 2]
// Skip empty filenames or invalid line numbers
if (file.length === 0) continue
const line = Number(lineStr)
if (Number.isNaN(line)) continue
matches.push({ file, line, text })
}
return matches
}