repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/lazy/src/debt.ts

Raw
File outline
import { readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";

const SKIP_DIRS = new Set([
	".git",
	"node_modules",
	"dist",
	"build",
	"coverage",
	".cache",
	".turbo",
	".next",
	"target",
	"vendor",
]);

const MARKER_RE = /(?:\/\/|#|\/\*|<!--)\s*lazy:\s*(.*)$/i;
const TRIGGER_RE = /\b(?:until|when|trigger|upgrade|if)\b\s*[:=-]?\s*(.+)$/i;

export interface LazyDebtMarker {
	file: string;
	line: number;
	ceiling: string;
	trigger?: string;
	noTrigger: boolean;
}

export interface ScanOptions {
	maxFileBytes?: number;
	maxMarkers?: number;
}

export interface ScanResult {
	markers: LazyDebtMarker[];
	omitted: number;
}

function isBinary(buffer: Buffer): boolean {
	return buffer.includes(0);
}

function parseMarkerText(text: string): { ceiling: string; trigger?: string } {
	const triggerMatch = text.match(TRIGGER_RE);
	if (!triggerMatch?.[1]) return { ceiling: text.trim() || "unspecified" };
	const ceiling = text
		.slice(0, triggerMatch.index)
		.trim()
		.replace(/[;,-]+$/u, "");
	return {
		ceiling: ceiling || "unspecified",
		trigger: triggerMatch[1].trim().replace(/\s*(?:\*\/|-->)\s*$/u, ""),
	};
}

export function parseLazyMarker(
	lineText: string,
	file: string,
	line: number,
): LazyDebtMarker | undefined {
	const match = lineText.match(MARKER_RE);
	if (!match) return undefined;
	const parsed = parseMarkerText(match[1] ?? "");
	return {
		file,
		line,
		ceiling: parsed.ceiling,
		trigger: parsed.trigger,
		noTrigger: !parsed.trigger,
	};
}

function scanFile(abs: string, rel: string): LazyDebtMarker[] {
	const buffer = readFileSync(abs);
	if (isBinary(buffer)) return [];
	return buffer
		.toString("utf8")
		.split(/\r?\n/u)
		.flatMap((lineText, index) => {
			const marker = parseLazyMarker(lineText, rel, index + 1);
			return marker ? [marker] : [];
		});
}

export function scanLazyDebt(
	root: string,
	options: ScanOptions = {},
): ScanResult {
	const maxFileBytes = options.maxFileBytes ?? 256 * 1024;
	const maxMarkers = options.maxMarkers ?? 100;
	const markers: LazyDebtMarker[] = [];
	let omitted = 0;

	function visit(dir: string): void {
		for (const entry of readdirSync(dir, { withFileTypes: true })) {
			if (entry.name.startsWith(".") && entry.name !== ".pi") {
				if (SKIP_DIRS.has(entry.name)) continue;
			}
			const abs = path.join(dir, entry.name);
			const rel = path.relative(root, abs).split(path.sep).join("/");
			if (entry.isDirectory()) {
				if (SKIP_DIRS.has(entry.name)) continue;
				visit(abs);
				continue;
			}
			if (!entry.isFile()) continue;
			const stat = statSync(abs);
			if (stat.size > maxFileBytes) continue;
			for (const marker of scanFile(abs, rel)) {
				if (markers.length < maxMarkers) markers.push(marker);
				else omitted += 1;
			}
		}
	}

	visit(root);
	return { markers, omitted };
}

export function formatDebt(result: ScanResult): string {
	if (result.markers.length === 0) return "No lazy debt.";
	const lines = result.markers.map((marker) => {
		const trigger = marker.noTrigger
			? "no-trigger"
			: `trigger: ${marker.trigger}`;
		return `${marker.file}:${marker.line} ceiling: ${marker.ceiling} ${trigger}`;
	});
	if (result.omitted > 0) lines.push(`… ${result.omitted} omitted`);
	return lines.join("\n");
}

export function markersFromUnifiedDiff(
	diff: string,
	max = 20,
): LazyDebtMarker[] {
	const markers: LazyDebtMarker[] = [];
	let file = "";
	let newLine = 0;
	for (const line of diff.split(/\r?\n/u)) {
		if (line.startsWith("+++ b/")) {
			file = line.slice(6);
			continue;
		}
		const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u);
		if (hunk) {
			newLine = Number(hunk[1]);
			continue;
		}
		if (line.startsWith("+") && !line.startsWith("+++")) {
			const marker = parseLazyMarker(line.slice(1), file, newLine);
			if (marker) markers.push(marker);
			newLine += 1;
		} else if (line.startsWith("-") && !line.startsWith("---")) {
			continue;
		} else if (line) {
			newLine += 1;
		}
		if (markers.length >= max) break;
	}
	return markers;
}