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

main
ts 94 lines 2.84 KB
Raw
1 /**
2 * The small glob matcher the `documents` patterns use:
3 * `*`, `**`, `?` and `{a,b}`, matched against `/`-separated paths relative
4 * to the config file. A `{` without a closing `}` is a literal character.
5 *
6 * @internal
7 */
8
9 export interface Glob {
10 /** The leading directory segments without wildcards, e.g. `src/app` for `src/app/**\/*.graphql`. */
11 readonly root: string
12 /** The root runs through a skipped directory, so the generator reads nothing under it. */
13 readonly skipped: boolean
14 readonly matches: (path: string) => boolean
15 }
16
17 /** Dot-files, dot-directories and `node_modules`, which the generator never reads or watches. */
18 export const isSkipped = (name: string): boolean => name.startsWith(".") || name === "node_modules"
19
20 const wildcard = /[*?{]/
21
22 const escapeRegExp = (char: string): string => /[.+^$()|[\]\\{}]/.test(char) ? `\\${char}` : char
23
24 /** The indices of the `{` that have a closing `}`, and of those `}`. */
25 const matchedBraces = (pattern: string): Set<number> => {
26 const matched = new Set<number>()
27 const open: Array<number> = []
28 for (let i = 0; i < pattern.length; i++) {
29 if (pattern[i] === "{") {
30 open.push(i)
31 } else if (pattern[i] === "}" && open.length > 0) {
32 matched.add(open.pop()!)
33 matched.add(i)
34 }
35 }
36 return matched
37 }
38
39 const normalize = (pattern: string): string => pattern.replace(/^(?:\.\/)+/, "")
40
41 const toRegExpSource = (pattern: string): string => {
42 let out = ""
43 let i = 0
44 let braces = 0
45 const matched = matchedBraces(pattern)
46 while (i < pattern.length) {
47 const char = pattern[i]!
48 if (char === "*") {
49 if (pattern[i + 1] === "*") {
50 const atSegmentStart = i === 0 || pattern[i - 1] === "/"
51 if (atSegmentStart && pattern[i + 2] === "/") {
52 out += "(?:[^/]+/)*"
53 i += 3
54 continue
55 }
56 out += ".*"
57 i += 2
58 continue
59 }
60 out += "[^/]*"
61 } else if (char === "?") {
62 out += "[^/]"
63 } else if (char === "{" && matched.has(i)) {
64 braces++
65 out += "(?:"
66 } else if (char === "}" && matched.has(i)) {
67 braces--
68 out += ")"
69 } else if (char === "," && braces > 0) {
70 out += "|"
71 } else {
72 out += escapeRegExp(char)
73 }
74 i++
75 }
76 return out
77 }
78
79 export const make = (pattern: string): Glob => {
80 const normalized = normalize(pattern)
81 const segments = normalized.split("/")
82 const rootSegments: Array<string> = []
83 for (const segment of segments.slice(0, -1)) {
84 if (wildcard.test(segment)) break
85 rootSegments.push(segment)
86 }
87 const regExp = new RegExp(`^${toRegExpSource(normalized)}$`)
88 return {
89 root: rootSegments.join("/"),
90 // `.` and `..` only navigate, so they don't make a root skipped.
91 skipped: rootSegments.some((segment) => segment !== "." && segment !== ".." && isSkipped(segment)),
92 matches: (path) => regExp.test(path)
93 }
94 }