Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

IgnorePatterns.ts

181 lines6.7 KB

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​
7type 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​
16interface Pattern {
17 readonly tokens: ReadonlyArray<Token>;
18 readonly negated: boolean;
19 readonly folderOnly: boolean;
21​
22export type IgnoreDecision = "ignored" | "included";
23​
24const utf8 = new TextEncoder();
25​
26// Git wildcards consume UTF-8 bytes, including inside character classes.
27const globBytes = (value: string) =>
28 Array.from(utf8.encode(value), (byte) => String.fromCharCode(byte));
29​
30function 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;
52​
53function parseLine(rawLine: string): Pattern | undefined {
54 let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
55 // Trailing spaces are dropped unless escaped; `\\ ` escapes the backslash, not the space.
56 while (line.endsWith(" ")) {
57 let backslashes = 0;
58 while (line[line.length - 2 - backslashes] === "\\") backslashes += 1;
59 if (backslashes % 2 === 1) break;
60 line = line.slice(0, -1);
61 }
62 if (line === "" || line.startsWith("#")) return undefined;
63 const negated = line.startsWith("!");
64 if (negated) line = line.slice(1);
65 else if (line.startsWith("\\!") || line.startsWith("\\#")) line = line.slice(1);
66 const folderOnly = line.endsWith("/") && !line.endsWith("\\/");
67 if (folderOnly) line = line.slice(0, -1);
68 if (line === "") return undefined;
69 const anchored = line.slice(0, -1).includes("/");
70 if (line.startsWith("/")) line = line.slice(1);
71​
72 const chars = globBytes(line);
73 const tokens: Token[] = anchored ? [] : [{ type: "folders" }];
74 // A `[` that never closes leaves every later `[` unclosed too, so one failed scan settles them
75 // all; rescanning the suffix for each would make `[[[[…` quadratic.
76 let classesClose = true;
77 for (let index = 0; index < chars.length; index += 1) {
78 const char = chars[index]!;
79 if (char === "*" && chars[index + 1] === "*") {
80 const atSegmentStart = index === 0 || chars[index - 1] === "/";
81 const next = chars[index + 2];
82 if (atSegmentStart && next === "/") {
83 tokens.push({ type: "folders" });
84 index += 2;
85 continue;
86 }
87 if (atSegmentStart && next === undefined) {
88 tokens.push({ type: "any" });
89 index += 1;
90 continue;
91 }
92 }
93 if (char === "*") tokens.push({ type: "star" });
94 else if (char === "?") tokens.push({ type: "one" });
95 else if (char === "[") {
96 const parsed = classesClose ? parseClass(chars, index) : undefined;
97 if (!parsed) classesClose = false;
98 if (parsed) {
99 tokens.push(parsed.token);
100 index = parsed.end;
101 } else tokens.push({ type: "char", char });
102 } else if (char === "\\" && index + 1 < chars.length) {
103 tokens.push({ type: "char", char: chars[++index]! });
104 } else tokens.push({ type: "char", char });
105 }
106 return { tokens, negated, folderOnly };
108​
109/**
110 * States are token positions. A `folders` token that has consumed part of a segment is `~position`
111 * instead: it may only finish after the next `/`, so an inner globstar never matches `xbar` as `bar`.
112 */
113function matches(tokens: ReadonlyArray<Token>, path: ReadonlyArray<string>): boolean {
114 let states = new Set<number>();
115 const add = (set: Set<number>, position: number) => {
116 // Wildcards also match nothing, so reaching one reaches the token after it.
117 for (; position <= tokens.length && !set.has(position); position += 1) {
118 set.add(position);
119 const type = tokens[position]?.type;
120 if (type !== "star" && type !== "any" && type !== "folders") return;
121 }
122 };
123 add(states, 0);
124 for (const char of path) {
125 const next = new Set<number>();
126 for (const state of states) {
127 const position = state < 0 ? ~state : state;
128 const token = tokens[position];
129 if (!token) continue;
130 switch (token.type) {
131 case "char":
132 if (token.char === char) add(next, position + 1);
133 break;
134 case "one":
135 if (char !== "/") add(next, position + 1);
136 break;
137 case "class": {
138 let inRange = false;
139 for (let index = 0; index < token.ranges.length && !inRange; index += 2) {
140 inRange = token.ranges[index]! <= char && char <= token.ranges[index + 1]!;
141 }
142 if (char !== "/" && inRange !== token.negated) add(next, position + 1);
143 break;
144 }
145 case "star":
146 if (char !== "/") add(next, position);
147 break;
148 case "any":
149 add(next, position);
150 break;
151 case "folders":
152 if (char === "/") add(next, position);
153 else next.add(~position);
154 break;
155 }
156 }
157 if (next.size === 0) return false;
158 states = next;
159 }
160 return states.has(tokens.length);
162​
163export interface IgnoreFile {
164 /** The last pattern that matches decides; `undefined` when none does. */
165 readonly decide: (relativePath: string, isFolder: boolean) => IgnoreDecision | undefined;
167​
168export function parseIgnoreFile(contents: string): IgnoreFile {
169 const patterns = contents.split("\n").flatMap((line) => parseLine(line) ?? []);
170 return {
171 decide: (relativePath, isFolder) => {
172 const path = globBytes(relativePath);
173 for (let index = patterns.length - 1; index >= 0; index -= 1) {
174 const pattern = patterns[index]!;
175 if (pattern.folderOnly && !isFolder) continue;
176 if (matches(pattern.tokens, path)) return pattern.negated ? "included" : "ignored";
177 }
178 return undefined;
179 },
180 };