repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/gitignore.ts

Raw
File outline
/** Single test function compiled from one gitignore pattern. */
type TestFn = (path: string) => boolean;

interface Rule {
	/** True if this rule negates a previous match. */
	negative: boolean;
	/** True if the original pattern ended with `/`. */
	directoryOnly: boolean;
	/** Compiled matcher for this rule. */
	test: TestFn;
}

/** Cache-key prefixes to avoid magic strings. */
const CACHE_DIR = "d:";
const CACHE_FILE = "f:";

/** Characters that have special meaning in gitignore globs. */
const GLOB_SPECIAL = new Set<string>(["*", "?", "[", "\\"]);

/** Characters that need escaping in a JavaScript RegExp. */
const REGEX_META = new Set<string>(".*+?^${}()|[]\\".split(""));

/**
 * A lightweight gitignore matcher.
 *
 * Parses `.gitignore`/`.ignore` rules line-by-line, compiles them to test
 * functions, and checks paths against them.  Rules are evaluated in order;
 * negation (`!`) flips the current state.
 *
 * Parent-directory short-circuit: if any ancestor directory is ignored, every
 * path beneath it is also ignored (matching git behaviour).
 *
 * Results are cached per `(path, isDir)` pair so repeated checks are O(1).
 */
export class GitIgnoreMatcher {
	private readonly rules: Rule[] = [];
	private readonly cache = new Map<string, boolean>();

	/**
	 * Parse a multi-line gitignore source and append the resulting rules.
	 * @param source Raw file contents (CRLF or LF line endings are accepted).
	 * @returns `this` for chaining.
	 */
	add(source: string): this {
		for (const line of source.split(/\r?\n/)) {
			const rule = parseRule(line);
			if (rule) this.rules.push(rule);
		}
		return this;
	}

	/**
	 * Check whether a path is ignored.
	 *
	 * @param inputPath Slash-separated path.  A trailing `/` indicates a
	 *   directory, which matters for patterns ending with `/`.
	 */
	ignores(inputPath: string): boolean {
		const isDir = inputPath.endsWith("/");

		// If any parent directory is ignored, the child is too.
		let slash = inputPath.lastIndexOf("/", inputPath.length - 2);
		while (slash > 0) {
			if (this._testCached(inputPath.slice(0, slash + 1), true)) return true;
			slash = inputPath.lastIndexOf("/", slash - 1);
		}

		return this._testCached(inputPath, isDir);
	}

	private _testCached(path: string, isDir: boolean): boolean {
		const key = isDir ? CACHE_DIR + path : CACHE_FILE + path;
		const cached = this.cache.get(key);
		if (cached !== undefined) return cached;
		const result = this._test(path, isDir);
		this.cache.set(key, result);
		return result;
	}

	private _test(path: string, isDir: boolean): boolean {
		let ignored = false;
		for (const rule of this.rules) {
			if (rule.directoryOnly && !isDir) continue;
			if (rule.test(path)) {
				ignored = !rule.negative;
			}
		}
		return ignored;
	}
}

/* ── Parsing ─────────────────────────────────────────────── */

function parseRule(rawLine: string): Rule | null {
	// Skip blank lines and comments.
	const line = rawLine.trimStart();
	if (!line || line[0] === "#") return null;

	// Negation.
	let pattern = line;
	let negative = false;
	if (pattern[0] === "!") {
		negative = true;
		pattern = pattern.slice(1);
	}

	// Leading escaped `!` or `#`.
	if (pattern.startsWith("\\!")) pattern = "!" + pattern.slice(2);
	if (pattern.startsWith("\\#")) pattern = "#" + pattern.slice(2);

	// Strip unescaped trailing spaces.
	pattern = stripTrailingSpaces(pattern);

	// Directory-only flag (trailing `/`).
	const directoryOnly = pattern.endsWith("/");
	if (directoryOnly) pattern = pattern.slice(0, -1);

	// Invalid patterns that never match.
	if (pattern.endsWith("\\")) return null;
	if (!pattern || pattern === "." || pattern === "..") return null;
	if (pattern.startsWith("../") || pattern.startsWith("./")) return null;

	const test = compileTest(pattern, directoryOnly);
	return test ? { negative, directoryOnly, test } : null;
}

/** Remove spaces at the end of a pattern unless preceded by `\`. */
function stripTrailingSpaces(s: string): string {
	let end = s.length;
	while (end > 0) {
		if (s[end - 1] !== " ") break;
		if (end > 1 && s[end - 2] === "\\") break; // escaped space
		end--;
	}
	return end === s.length ? s : s.slice(0, end);
}

/* ── Pattern analysis & fast-path compilation ────────────── */

interface PatternInfo {
	/** Leading `/` was stripped. */
	anchored: boolean;
	/** Contains at least one `/`. */
	hasSlash: boolean;
	/** Middle-slash pattern → relative to .gitignore dir only. */
	isRelative: boolean;
}

function analyzePattern(raw: string): { pattern: string; info: PatternInfo } {
	let pattern = raw;
	const anchored = pattern[0] === "/";
	if (anchored) pattern = pattern.slice(1);

	const hasSlash = pattern.includes("/");
	const isRelative = hasSlash && !anchored && !pattern.startsWith("**/");

	return { pattern, info: { anchored, hasSlash, isRelative } };
}

/** Return the basename (last path component) of `p`. */
function basenameOf(p: string): string {
	const i = p.lastIndexOf("/");
	return i >= 0 ? p.slice(i + 1) : p;
}

/** True if `s` contains any glob meta-character (`* ? [ \`). */
function hasSpecialChars(s: string): boolean {
	for (let i = 0; i < s.length; i++) {
		if (GLOB_SPECIAL.has(s[i])) return true;
	}
	return false;
}

/**
 * Compile a single gitignore pattern into a test function.
 *
 * Several fast paths avoid RegExp construction for common patterns:
 * exact names, suffix (`*.ext`), prefix (`foo*`), and anchored literals.
 */
function compileTest(
	rawPattern: string,
	directoryOnly: boolean,
): TestFn | null {
	const { pattern, info } = analyzePattern(rawPattern);
	const { anchored, isRelative } = info;

	// Fast path: literal patterns with no glob chars.
	if (!hasSpecialChars(pattern)) {
		return compileLiteral(pattern, anchored, isRelative, directoryOnly);
	}

	// Fast path: `*.ext` (no slash, no other specials).
	if (
		!anchored &&
		!info.hasSlash &&
		pattern.startsWith("*.") &&
		!hasSpecialChars(pattern.slice(2))
	) {
		const suffix = pattern.slice(1); // includes the dot
		return (p) => basenameOf(p).endsWith(suffix);
	}

	// Fast path: `foo*` (no slash, trailing star only).
	if (
		!anchored &&
		!info.hasSlash &&
		pattern.endsWith("*") &&
		pattern.indexOf("*") === pattern.length - 1 &&
		!hasSpecialChars(pattern.slice(0, -1))
	) {
		const prefix = pattern.slice(0, -1);
		return (p) => basenameOf(p).startsWith(prefix);
	}

	// Fallback: build a RegExp.
	const regex = buildRegex(pattern, anchored, isRelative);
	return regex ? (p) => regex.test(p) : null;
}

/** Compile a literal (no glob) pattern. */
function compileLiteral(
	pattern: string,
	anchored: boolean,
	isRelative: boolean,
	directoryOnly: boolean,
): TestFn {
	if (directoryOnly) {
		if (anchored || isRelative) {
			return (p) => p === `${pattern}/` || p.startsWith(`${pattern}/`);
		}
		return (p) => p === `${pattern}/` || p.endsWith(`/${pattern}/`);
	}

	if (anchored || isRelative) {
		return (p) => {
			const norm = p.endsWith("/") ? p.slice(0, -1) : p;
			return norm === pattern || norm.startsWith(`${pattern}/`);
		};
	}

	return (p) => {
		const norm = p.endsWith("/") ? p.slice(0, -1) : p;
		return norm === pattern || norm.endsWith(`/${pattern}`);
	};
}

/* ── RegExp builder ──────────────────────────────────────── */

function buildRegex(
	pattern: string,
	anchored: boolean,
	isRelative: boolean,
): RegExp | null {
	let src = "";
	let i = 0;
	while (i < pattern.length) {
		const ch = pattern[i];

		if (ch === "\\") {
			const next = pattern[i + 1];
			if (next) {
				src += escapeRegex(next);
				i += 2;
				continue;
			}
			i++;
			continue;
		}

		if (ch === "*") {
			if (pattern[i + 1] === "*") {
				if (pattern[i + 2] === "/") {
					src += "(?:.*\\/)?";
					i += 3;
					continue;
				}
				if (i + 2 === pattern.length) {
					src += ".+"; // trailing ** matches at least one char inside
					i += 2;
					continue;
				}
				src += "[^/]*";
				i++;
				continue;
			}
			src += "[^/]*";
			i++;
			continue;
		}

		if (ch === "?") {
			src += "[^/]";
			i++;
			continue;
		}

		if (ch === "[") {
			const segment = parseCharClass(pattern, i);
			if (segment === null) {
				src += "\\[";
				i++;
				continue;
			}
			src += segment;
			i = pattern.indexOf("]", i + 1) + 1;
			continue;
		}

		src += escapeRegex(ch);
		i++;
	}

	if (!src) return null;

	let body: string;
	if (anchored || isRelative) {
		body = `^${src}(?=$|/)`;
	} else if (pattern.includes("/")) {
		body = `^(?:.*/)?${src}(?=$|/)`;
	} else {
		body = `^(?:[^/]*/)??${src}(?=$|/)`;
	}

	return new RegExp(body);
}

/**
 * Parse a gitignore character class `[...]` into its regex equivalent.
 *
 * Handles negation (`[!...]` → `[^...]`) and sanitizes invalid ASCII
 * ranges (e.g. `[z-a]` is silently dropped).
 *
 * @returns The regex segment (including surrounding brackets) or `null`
 *   if the closing `]` was not found.
 */
function parseCharClass(pattern: string, openIndex: number): string | null {
	const close = pattern.indexOf("]", openIndex + 1);
	if (close === -1) return null;

	let content = pattern.slice(openIndex + 1, close);

	// Sanitize out-of-order ASCII ranges.
	content = content.replace(/([0-z])-([0-z])/g, (m, a, b) =>
		a.charCodeAt(0) <= b.charCodeAt(0) ? m : "",
	);

	// Gitignore uses `!` for negation; regex uses `^`.
	if (content[0] === "!") {
		content = "^" + content.slice(1);
	}

	return `[${content}]`;
}

/** Escape a single character for use in a JavaScript RegExp. */
function escapeRegex(ch: string): string {
	return REGEX_META.has(ch) ? `\\${ch}` : ch;
}