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