repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(gitignore): clean up slop — no perf loss

1cbb79ef6aa1e22c83e757afc0cc7e586a2d9663

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

extensions/llmiterate/gitignore.ts

Modified
1 +/** Single test function compiled from one gitignore pattern. */
1 2 type TestFn = (path: string) => boolean;
3 4 interface Rule {
5 + /** True if this rule negates a previous match. */
4 6 negative: boolean;
7 + /** True if the original pattern ended with `/`. */
5 8 directoryOnly: boolean;
9 + /** Compiled matcher for this rule. */
6 10 test: TestFn;
13 +/** Cache-key prefixes to avoid magic strings. */
14 +const CACHE_DIR = "d:";
15 +const CACHE_FILE = "f:";
17 +/** Characters that have special meaning in gitignore globs. */
18 +const GLOB_SPECIAL = new Set<string>(["*", "?", "[", "\\"]);
20 +/** Characters that need escaping in a JavaScript RegExp. */
21 +const REGEX_META = new Set<string>(".*+?^${}()|[]\\".split(""));
23 +/**
24 + * A lightweight gitignore matcher.
25 + *
26 + * Parses `.gitignore`/`.ignore` rules line-by-line, compiles them to test
27 + * functions, and checks paths against them. Rules are evaluated in order;
28 + * negation (`!`) flips the current state.
29 + *
30 + * Parent-directory short-circuit: if any ancestor directory is ignored, every
31 + * path beneath it is also ignored (matching git behaviour).
32 + *
33 + * Results are cached per `(path, isDir)` pair so repeated checks are O(1).
34 + */
9 35 export class GitIgnoreMatcher {
10 36 private readonly rules: Rule[] = [];
11 37 private readonly cache = new Map<string, boolean>();
39 + /**
40 + * Parse a multi-line gitignore source and append the resulting rules.
41 + * @param source Raw file contents (CRLF or LF line endings are accepted).
42 + * @returns `this` for chaining.
43 + */
13 44 add(source: string): this {
14 45 for (const line of source.split(/\r?\n/)) {
15 46 const rule = parseRule(line);
18 49 return this;
52 + /**
53 + * Check whether a path is ignored.
54 + *
55 + * @param inputPath Slash-separated path. A trailing `/` indicates a
56 + * directory, which matters for patterns ending with `/`.
57 + */
21 58 ignores(inputPath: string): boolean {
22 59 const isDir = inputPath.endsWith("/");
24 - // Check parent directories first.
25 - // If a parent is ignored, the child is too.
61 + // If any parent directory is ignored, the child is too.
26 62 let slash = inputPath.lastIndexOf("/", inputPath.length - 2);
27 63 while (slash > 0) {
28 - const parent = inputPath.slice(0, slash + 1);
29 - if (this._testCached(parent, true)) return true;
64 + if (this._testCached(inputPath.slice(0, slash + 1), true)) return true;
30 65 slash = inputPath.lastIndexOf("/", slash - 1);
36 71 private _testCached(path: string, isDir: boolean): boolean {
37 - const key = isDir ? `d:${path}` : `f:${path}`;
72 + const key = isDir ? CACHE_DIR + path : CACHE_FILE + path;
38 73 const cached = this.cache.get(key);
39 74 if (cached !== undefined) return cached;
40 75 const result = this._test(path, isDir);
57 -function parseRule(line: string): Rule | null {
58 - // Skip blank lines and comments.
59 - const trimmed = line.trimStart();
60 - if (!trimmed || trimmed.startsWith("#")) return null;
92 +/* ── Parsing ─────────────────────────────────────────────── */
62 - // Handle negation.
63 - let pattern = trimmed;
94 +function parseRule(rawLine: string): Rule | null {
95 + // Skip blank lines and comments.
96 + const line = rawLine.trimStart();
97 + if (!line || line[0] === "#") return null;
99 + // Negation.
100 + let pattern = line;
64 101 let negative = false;
65 - if (pattern.startsWith("!")) {
102 + if (pattern[0] === "!") {
66 103 negative = true;
67 104 pattern = pattern.slice(1);
70 - // Handle leading escaped `!` or `#`.
107 + // Leading escaped `!` or `#`.
71 108 if (pattern.startsWith("\\!")) pattern = "!" + pattern.slice(2);
72 109 if (pattern.startsWith("\\#")) pattern = "#" + pattern.slice(2);
74 111 // Strip unescaped trailing spaces.
75 - let end = pattern.length;
76 - while (end > 0 && pattern[end - 1] === ' ' && (end === 1 || pattern[end - 2] !== '\\')) {
77 - end--;
78 - }
79 - pattern = pattern.slice(0, end);
112 + pattern = stripTrailingSpaces(pattern);
81 - // Directory-only flag.
114 + // Directory-only flag (trailing `/`).
82 115 const directoryOnly = pattern.endsWith("/");
83 116 if (directoryOnly) pattern = pattern.slice(0, -1);
85 - // Invalid: trailing backslash.
118 + // Invalid patterns that never match.
86 119 if (pattern.endsWith("\\")) return null;
88 - // Skip patterns that resolve to empty or invalid.
89 120 if (!pattern || pattern === "." || pattern === "..") return null;
90 121 if (pattern.startsWith("../") || pattern.startsWith("./")) return null;
93 124 return test ? { negative, directoryOnly, test } : null;
96 -function compileTest(pattern: string, directoryOnly: boolean): TestFn | null {
97 - const anchored = pattern.startsWith("/");
127 +/** Remove spaces at the end of a pattern unless preceded by `\`. */
128 +function stripTrailingSpaces(s: string): string {
129 + let end = s.length;
130 + while (end > 0) {
131 + if (s[end - 1] !== " ") break;
132 + if (end > 1 && s[end - 2] === "\\") break; // escaped space
133 + end--;
135 + return end === s.length ? s : s.slice(0, end);
138 +/* ── Pattern analysis & fast-path compilation ────────────── */
140 +interface PatternInfo {
141 + /** Leading `/` was stripped. */
142 + anchored: boolean;
143 + /** Contains at least one `/`. */
144 + hasSlash: boolean;
145 + /** Middle-slash pattern → relative to .gitignore dir only. */
146 + isRelative: boolean;
149 +function analyzePattern(raw: string): { pattern: string; info: PatternInfo } {
150 + let pattern = raw;
151 + const anchored = pattern[0] === "/";
98 152 if (anchored) pattern = pattern.slice(1);
100 154 const hasSlash = pattern.includes("/");
155 + const isRelative = hasSlash && !anchored && !pattern.startsWith("**/");
102 - // Detect if pattern has a slash that's not at the very start (after **/)
103 - // and not part of a leading **/ prefix. Patterns with middle slashes are
104 - // relative to the .gitignore location, not any depth.
105 - const isRelative =
106 - hasSlash && !anchored && !pattern.startsWith("**/");
157 + return { pattern, info: { anchored, hasSlash, isRelative } };
108 - // --- Fast path: simple exact-match patterns ---
109 - // e.g. "node_modules/", ".DS_Store", "Makefile"
110 - if (!anchored && !hasSpecialChars(pattern)) {
111 - if (directoryOnly) {
112 - if (isRelative) {
113 - return (p) => p === `${pattern}/` || p.startsWith(`${pattern}/`);
114 - }
115 - return (p) => p === `${pattern}/` || p.endsWith(`/${pattern}/`);
116 - }
117 - // File pattern that also matches directories (gitignore: no trailing slash = both)
118 - if (isRelative) {
119 - return (p) => p === pattern || p === `${pattern}/` || p.startsWith(`${pattern}/`);
120 - }
121 - return (p) => {
122 - const norm = p.endsWith('/') ? p.slice(0, -1) : p;
123 - return norm === pattern || norm.endsWith(`/${pattern}`);
124 - };
160 +/** Return the basename (last path component) of `p`. */
161 +function basenameOf(p: string): string {
162 + const i = p.lastIndexOf("/");
163 + return i >= 0 ? p.slice(i + 1) : p;
166 +/** True if `s` contains any glob meta-character (`* ? [ \`). */
167 +function hasSpecialChars(s: string): boolean {
168 + for (let i = 0; i < s.length; i++) {
169 + if (GLOB_SPECIAL.has(s[i])) return true;
171 + return false;
174 +/**
175 + * Compile a single gitignore pattern into a test function.
177 + * Several fast paths avoid RegExp construction for common patterns:
178 + * exact names, suffix (`*.ext`), prefix (`foo*`), and anchored literals.
179 + */
180 +function compileTest(rawPattern: string, directoryOnly: boolean): TestFn | null {
181 + const { pattern, info } = analyzePattern(rawPattern);
182 + const { anchored, isRelative } = info;
184 + // Fast path: literal patterns with no glob chars.
185 + if (!hasSpecialChars(pattern)) {
186 + return compileLiteral(pattern, anchored, isRelative, directoryOnly);
127 - // --- Fast path: anchored exact-match ---
128 - // e.g. "/Makefile", "/build/"
129 - if (anchored && !hasSpecialChars(pattern)) {
130 - if (directoryOnly) {
131 - return (p) => p === `${pattern}/`;
132 - }
133 - return (p) => p === pattern || p.startsWith(`${pattern}/`);
134 - }
136 - // --- Fast path: suffix patterns (*.ext) ---
137 - // e.g. "*.log", "*.tmp", "*.min.js"
138 - if (!anchored && !hasSlash && pattern.startsWith("*.") && !hasSpecialChars(pattern.slice(2))) {
189 + // Fast path: `*.ext` (no slash, no other specials).
190 + if (!anchored && !info.hasSlash && pattern.startsWith("*.") && !hasSpecialChars(pattern.slice(2))) {
139 191 const suffix = pattern.slice(1); // includes the dot
140 - return (p) => {
141 - const slash = p.lastIndexOf("/");
142 - const basename = slash >= 0 ? p.slice(slash + 1) : p;
143 - return basename.endsWith(suffix);
144 - };
192 + return (p) => basenameOf(p).endsWith(suffix);
147 - // --- Fast path: prefix patterns (foo*) ---
148 - if (!anchored && !hasSlash && pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1 && !hasSpecialChars(pattern.slice(0, -1))) {
195 + // Fast path: `foo*` (no slash, trailing star only).
196 + if (!anchored && !info.hasSlash && pattern.endsWith("*") && pattern.indexOf("*") === pattern.length - 1 && !hasSpecialChars(pattern.slice(0, -1))) {
149 197 const prefix = pattern.slice(0, -1);
150 - return (p) => {
151 - const slash = p.lastIndexOf("/");
152 - const basename = slash >= 0 ? p.slice(slash + 1) : p;
153 - return basename.startsWith(prefix);
154 - };
198 + return (p) => basenameOf(p).startsWith(prefix);
157 - // --- Fast path: relative directory patterns ---
158 - // e.g. "doc/frotz/" — relative to gitignore dir
159 - if (isRelative && directoryOnly && !hasSpecialChars(pattern)) {
160 - return (p) => p === `${pattern}/` || p.startsWith(`${pattern}/`);
161 - }
163 - // --- Fallback: regex ---
201 + // Fallback: build a RegExp.
164 202 const regex = buildRegex(pattern, anchored, isRelative);
165 203 return regex ? (p) => regex.test(p) : null;
168 -function hasSpecialChars(s: string): boolean {
169 - for (let i = 0; i < s.length; i++) {
170 - const c = s[i];
171 - if (c === "*" || c === "?" || c === "[" || c === "\\") return true;
206 +/** Compile a literal (no glob) pattern. */
207 +function compileLiteral(
208 + pattern: string,
209 + anchored: boolean,
210 + isRelative: boolean,
211 + directoryOnly: boolean,
212 +): TestFn {
213 + if (directoryOnly) {
214 + if (anchored || isRelative) {
215 + return (p) => p === `${pattern}/` || p.startsWith(`${pattern}/`);
217 + return (p) => p === `${pattern}/` || p.endsWith(`/${pattern}/`);
173 - return false;
220 + if (anchored || isRelative) {
221 + return (p) => {
222 + const norm = p.endsWith("/") ? p.slice(0, -1) : p;
223 + return norm === pattern || norm.startsWith(`${pattern}/`);
224 + };
227 + return (p) => {
228 + const norm = p.endsWith("/") ? p.slice(0, -1) : p;
229 + return norm === pattern || norm.endsWith(`/${pattern}`);
230 + };
233 +/* ── RegExp builder ──────────────────────────────────────── */
176 235 function buildRegex(pattern: string, anchored: boolean, isRelative: boolean): RegExp | null {
177 236 let src = "";
178 237 let i = 0;
198 257 continue;
200 259 if (i + 2 === pattern.length) {
201 - // trailing ** must match at least one char (everything INSIDE)
202 - src += ".+";
260 + src += ".+"; // trailing ** matches at least one char inside
203 261 i += 2;
204 262 continue;
221 279 if (ch === "[") {
222 - const end = pattern.indexOf("]", i + 1);
223 - if (end === -1) {
280 + const segment = parseCharClass(pattern, i);
281 + if (segment === null) {
224 282 src += "\\[";
226 284 continue;
228 - let range = pattern.slice(i + 1, end);
229 - range = range.replace(/([0-z])-([0-z])/g, (m, a, b) =>
230 - a.charCodeAt(0) <= b.charCodeAt(0) ? m : "",
231 - );
232 - // Gitignore uses [!...] for negated classes, regex uses [^...]
233 - if (range.startsWith("!")) {
234 - range = "^" + range.slice(1);
235 - }
236 - src += `[${range}]`;
237 - i = end + 1;
286 + src += segment;
287 + i = pattern.indexOf("]", i + 1) + 1;
238 288 continue;
256 306 return new RegExp(body);
309 +/**
310 + * Parse a gitignore character class `[...]` into its regex equivalent.
312 + * Handles negation (`[!...]` → `[^...]`) and sanitizes invalid ASCII
313 + * ranges (e.g. `[z-a]` is silently dropped).
315 + * @returns The regex segment (including surrounding brackets) or `null`
316 + * if the closing `]` was not found.
317 + */
318 +function parseCharClass(pattern: string, openIndex: number): string | null {
319 + const close = pattern.indexOf("]", openIndex + 1);
320 + if (close === -1) return null;
322 + let content = pattern.slice(openIndex + 1, close);
324 + // Sanitize out-of-order ASCII ranges.
325 + content = content.replace(/([0-z])-([0-z])/g, (m, a, b) =>
326 + a.charCodeAt(0) <= b.charCodeAt(0) ? m : "",
327 + );
329 + // Gitignore uses `!` for negation; regex uses `^`.
330 + if (content[0] === "!") {
331 + content = "^" + content.slice(1);
334 + return `[${content}]`;
337 +/** Escape a single character for use in a JavaScript RegExp. */
259 338 function escapeRegex(ch: string): string {
260 - return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
339 + return REGEX_META.has(ch) ? `\\${ch}` : ch;