The best way to control Claude Code, Codex and more from any computer or phone

main
ts 176 lines 6.53 KB
Raw
1 /**
2 * Gitignore-syntax matching for `.ignore` files, which git cannot evaluate for us. Patterns come
3 * from the repository, so each runs as an NFA over the path (O(pattern × path)): a backtracking
4 * regex stalls for seconds on `a*a*a*…b`. POSIX `[:class:]` names are not supported.
5 */
6
7 type Token =
8 | { readonly type: "char"; readonly char: string }
9 | { readonly type: "one" }
10 | { readonly type: "class"; readonly negated: boolean; readonly ranges: ReadonlyArray<string> }
11 | { readonly type: "star" }
12 | { readonly type: "any" }
13 /** A leading or inner `**` segment: nothing, or anything ending in `/`. */
14 | { readonly type: "folders" };
15
16 interface Pattern {
17 readonly tokens: ReadonlyArray<Token>;
18 readonly negated: boolean;
19 readonly folderOnly: boolean;
20 }
21
22 export type IgnoreDecision = "ignored" | "included";
23
24 const utf8 = new TextEncoder();
25
26 // Git wildcards consume UTF-8 bytes, including inside character classes.
27 const globBytes = (value: string) =>
28 Array.from(utf8.encode(value), (byte) => String.fromCharCode(byte));
29
30 function parseClass(chars: ReadonlyArray<string>, start: number) {
31 let index = start + 1;
32 const negated = chars[index] === "!" || chars[index] === "^";
33 if (negated) index += 1;
34 const ranges: string[] = [];
35 for (let first = true; index < chars.length; first = false) {
36 let char = chars[index]!;
37 if (char === "]" && !first)
38 return { token: { type: "class", negated, ranges } as const, end: index };
39 if (char === "\\" && index + 1 < chars.length) char = chars[++index]!;
40 if (chars[index + 1] === "-" && index + 2 < chars.length && chars[index + 2] !== "]") {
41 let last = chars[index + 2]!;
42 index += 2;
43 if (last === "\\" && index + 1 < chars.length) last = chars[++index]!;
44 ranges.push(char, last);
45 } else {
46 ranges.push(char, char);
47 }
48 index += 1;
49 }
50 return undefined;
51 }
52
53 function parseLine(rawLine: string): Pattern | undefined {
54 let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
55 // Trailing spaces are dropped unless escaped.
56 while (line.endsWith(" ") && !line.endsWith("\\ ")) line = line.slice(0, -1);
57 if (line === "" || line.startsWith("#")) return undefined;
58 const negated = line.startsWith("!");
59 if (negated) line = line.slice(1);
60 else if (line.startsWith("\\!") || line.startsWith("\\#")) line = line.slice(1);
61 const folderOnly = line.endsWith("/") && !line.endsWith("\\/");
62 if (folderOnly) line = line.slice(0, -1);
63 if (line === "") return undefined;
64 const anchored = line.slice(0, -1).includes("/");
65 if (line.startsWith("/")) line = line.slice(1);
66
67 const chars = globBytes(line);
68 const tokens: Token[] = anchored ? [] : [{ type: "folders" }];
69 // A `[` that never closes leaves every later `[` unclosed too, so one failed scan settles them
70 // all; rescanning the suffix for each would make `[[[[…` quadratic.
71 let classesClose = true;
72 for (let index = 0; index < chars.length; index += 1) {
73 const char = chars[index]!;
74 if (char === "*" && chars[index + 1] === "*") {
75 const atSegmentStart = index === 0 || chars[index - 1] === "/";
76 const next = chars[index + 2];
77 if (atSegmentStart && next === "/") {
78 tokens.push({ type: "folders" });
79 index += 2;
80 continue;
81 }
82 if (atSegmentStart && next === undefined) {
83 tokens.push({ type: "any" });
84 index += 1;
85 continue;
86 }
87 }
88 if (char === "*") tokens.push({ type: "star" });
89 else if (char === "?") tokens.push({ type: "one" });
90 else if (char === "[") {
91 const parsed = classesClose ? parseClass(chars, index) : undefined;
92 if (!parsed) classesClose = false;
93 if (parsed) {
94 tokens.push(parsed.token);
95 index = parsed.end;
96 } else tokens.push({ type: "char", char });
97 } else if (char === "\\" && index + 1 < chars.length) {
98 tokens.push({ type: "char", char: chars[++index]! });
99 } else tokens.push({ type: "char", char });
100 }
101 return { tokens, negated, folderOnly };
102 }
103
104 /**
105 * States are token positions. A `folders` token that has consumed part of a segment is `~position`
106 * instead: it may only finish after the next `/`, so an inner globstar never matches `xbar` as `bar`.
107 */
108 function matches(tokens: ReadonlyArray<Token>, path: ReadonlyArray<string>): boolean {
109 let states = new Set<number>();
110 const add = (set: Set<number>, position: number) => {
111 // Wildcards also match nothing, so reaching one reaches the token after it.
112 for (; position <= tokens.length && !set.has(position); position += 1) {
113 set.add(position);
114 const type = tokens[position]?.type;
115 if (type !== "star" && type !== "any" && type !== "folders") return;
116 }
117 };
118 add(states, 0);
119 for (const char of path) {
120 const next = new Set<number>();
121 for (const state of states) {
122 const position = state < 0 ? ~state : state;
123 const token = tokens[position];
124 if (!token) continue;
125 switch (token.type) {
126 case "char":
127 if (token.char === char) add(next, position + 1);
128 break;
129 case "one":
130 if (char !== "/") add(next, position + 1);
131 break;
132 case "class": {
133 let inRange = false;
134 for (let index = 0; index < token.ranges.length && !inRange; index += 2) {
135 inRange = token.ranges[index]! <= char && char <= token.ranges[index + 1]!;
136 }
137 if (char !== "/" && inRange !== token.negated) add(next, position + 1);
138 break;
139 }
140 case "star":
141 if (char !== "/") add(next, position);
142 break;
143 case "any":
144 add(next, position);
145 break;
146 case "folders":
147 if (char === "/") add(next, position);
148 else next.add(~position);
149 break;
150 }
151 }
152 if (next.size === 0) return false;
153 states = next;
154 }
155 return states.has(tokens.length);
156 }
157
158 export interface IgnoreFile {
159 /** The last pattern that matches decides; `undefined` when none does. */
160 readonly decide: (relativePath: string, isFolder: boolean) => IgnoreDecision | undefined;
161 }
162
163 export function parseIgnoreFile(contents: string): IgnoreFile {
164 const patterns = contents.split("\n").flatMap((line) => parseLine(line) ?? []);
165 return {
166 decide: (relativePath, isFolder) => {
167 const path = globBytes(relativePath);
168 for (let index = patterns.length - 1; index >= 0; index -= 1) {
169 const pattern = patterns[index]!;
170 if (pattern.folderOnly && !isFolder) continue;
171 if (matches(pattern.tokens, path)) return pattern.negated ? "included" : "ignored";
172 }
173 return undefined;
174 },
175 };
176 }