repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/llmiterate/path-filter.ts

Raw
File outline
import { createHash } from "node:crypto";
import * as os from "node:os";
import * as path from "node:path";
import type { LlmiterateConfig } from "./config";
import { APP_STATE_DIR, STORE_NAMESPACE } from "./constants";
import { toSlash } from "./util";

const REGEX_CHARS = /[|\\{}()[\]^$+?.]/;

export type CompiledGlobSegment = "**" | RegExp;

export interface CompiledPathFilter {
	include: RegExp[];
	includeDirPatterns: CompiledGlobSegment[][];
	exclude: RegExp[];
	excludeRootDirs: Set<string>;
	excludePrefixes: string[];
}

export function projectStoreDir(root: string): string {
	return path.join(platformStateDir(), STORE_NAMESPACE, hashProjectRoot(root));
}

export function platformStateDir(
	platform: NodeJS.Platform = process.platform,
	env: NodeJS.ProcessEnv = process.env,
	home = os.homedir(),
): string {
	const paths = platform === "win32" ? path.win32 : path.posix;

	if (platform === "win32") {
		return paths.join(
			env.LOCALAPPDATA ?? paths.join(home, "AppData", "Local"),
			APP_STATE_DIR,
		);
	}

	if (env.XDG_STATE_HOME) return paths.join(env.XDG_STATE_HOME, APP_STATE_DIR);
	if (platform === "darwin")
		return paths.join(home, "Library", "Application Support", APP_STATE_DIR);
	return paths.join(home, ".local", "state", APP_STATE_DIR);
}

export function hashProjectRoot(root: string): string {
	return createHash("sha256").update(root).digest("hex");
}

export function compilePathFilter(
	config: Pick<LlmiterateConfig, "include" | "exclude">,
): CompiledPathFilter {
	const includeDirPatterns = config.include.map(compileGlobSegments);
	const excludeRootDirs = new Set<string>();
	const excludePrefixes: string[] = [];
	const exclude: RegExp[] = [];

	for (const glob of config.exclude) {
		const prefix = simpleGlobstarPrefix(glob);
		if (!prefix) {
			exclude.push(globToRegExp(glob));
			continue;
		}

		const rootDir = rootDirPrefix(prefix);
		if (rootDir) excludeRootDirs.add(rootDir);
		else excludePrefixes.push(prefix);
	}

	return {
		include: config.include.map(globToRegExp),
		includeDirPatterns,
		exclude,
		excludeRootDirs,
		excludePrefixes,
	};
}

export function shouldIncludePath(
	relPath: string,
	config: Pick<LlmiterateConfig, "include" | "exclude"> | CompiledPathFilter,
): boolean {
	const filter = isCompiledPathFilter(config)
		? config
		: compilePathFilter(config);
	return shouldIncludeCompiledPath(relPath, filter);
}

export function shouldIncludeCompiledPath(
	relPath: string,
	filter: CompiledPathFilter,
): boolean {
	const rel = toSlash(relPath);
	if (isExcludedPath(rel, filter)) return false;
	return filter.include.some((pattern) => pattern.test(rel));
}

export function isExcludedPath(
	relPath: string,
	filter: CompiledPathFilter,
): boolean {
	const rel = toSlash(relPath);
	return (
		filter.excludeRootDirs.has(firstPathSegment(rel)) ||
		filter.excludePrefixes.some((prefix) => rel.startsWith(prefix)) ||
		filter.exclude.some((pattern) => pattern.test(rel))
	);
}

export function shouldWatchDirectory(
	relPath: string,
	filter: CompiledPathFilter,
): boolean {
	const rel = toSlash(relPath);
	if (rel && (isExcludedPath(rel, filter) || isExcludedPath(`${rel}/`, filter)))
		return false;
	const segments = rel ? rel.split("/") : [];
	return filter.includeDirPatterns.some((include) =>
		includeCanMatchUnderDir(include, segments),
	);
}

export function globToRegExp(pattern: string): RegExp {
	const glob = toSlash(pattern);
	let s = "^";
	for (let i = 0; i < glob.length; ) {
		const c = glob[i];
		if (c === "*") {
			if (glob[i + 1] === "*") {
				i += 2;
				if (glob[i] === "/") {
					i++;
					s += "(?:.*/)?";
				} else {
					s += ".*";
				}
				continue;
			}
			s += "[^/]*";
			i++;
			continue;
		}
		if (c === "?") {
			s += "[^/]";
			i++;
			continue;
		}
		if (c === "{") {
			const end = glob.indexOf("}", i + 1);
			if (end !== -1) {
				const parts = glob
					.slice(i + 1, end)
					.split(",")
					.map((p) => p.trim())
					.filter(Boolean)
					.map(escapeRegExp);
				if (parts.length) {
					s += `(?:${parts.join("|")})`;
					i = end + 1;
					continue;
				}
			}
		}
		s += REGEX_CHARS.test(c) ? `\\${c}` : c;
		i++;
	}
	return new RegExp(`${s}$`);
}

function includeCanMatchUnderDir(
	pattern: CompiledGlobSegment[],
	dir: string[],
): boolean {
	const memo = new Map<string, boolean>();
	const visit = (patternIndex: number, dirIndex: number): boolean => {
		const key = `${patternIndex}:${dirIndex}`;
		const cached = memo.get(key);
		if (cached !== undefined) return cached;

		let result: boolean;
		if (dirIndex >= dir.length) {
			result = patternIndex < pattern.length;
		} else if (patternIndex >= pattern.length) {
			result = false;
		} else {
			const segment = pattern[patternIndex]!;
			result =
				segment === "**"
					? visit(patternIndex + 1, dirIndex) ||
						visit(patternIndex, dirIndex + 1)
					: segment.test(dir[dirIndex]!) &&
						visit(patternIndex + 1, dirIndex + 1);
		}

		memo.set(key, result);
		return result;
	};
	return visit(0, 0);
}

function compileGlobSegments(pattern: string): CompiledGlobSegment[] {
	return toSlash(pattern)
		.split("/")
		.filter(Boolean)
		.map((segment) => (segment === "**" ? "**" : globToRegExp(segment)));
}

function simpleGlobstarPrefix(glob: string): string | undefined {
	const normalized = toSlash(glob);
	if (!normalized.endsWith("/**")) return undefined;
	const prefix = normalized.slice(0, -2);
	return /[*?{[]/.test(prefix) ? undefined : prefix;
}

function rootDirPrefix(prefix: string): string | undefined {
	const dir = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
	return dir && !dir.includes("/") ? dir : undefined;
}

function firstPathSegment(path: string): string {
	const slash = path.indexOf("/");
	return slash === -1 ? path : path.slice(0, slash);
}

function escapeRegExp(s: string): string {
	return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function isCompiledPathFilter(
	value: Pick<LlmiterateConfig, "include" | "exclude"> | CompiledPathFilter,
): value is CompiledPathFilter {
	return "includeDirPatterns" in value;
}