Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

glob.ts

42 lines1.1 KB

1/**
2 * Minimal path glob matcher (no dependency): supports `**`, `*`, and `?`.
3 * `**` spans path segments; `*` and `?` stay within one segment.
4 */
5​
6const REGEX_SPECIALS = /[.+^${}()|[\]\\]/g
7​
8export function globToRegExp(glob: string): RegExp {
9 let out = '^'
10 let i = 0
11 while (i < glob.length) {
12 const c = glob[i]!
13 if (c === '*') {
14 if (glob[i + 1] === '*') {
15 // `**` — optionally followed by `/`; matches any depth (including none)
16 i += 2
17 if (glob[i] === '/') i++
18 out += out === '^' || out.endsWith('/') ? '(?:.*/)?' : '.*'
19 // when `**` is the trailing token (e.g. `docs/**`) match everything below
20 if (i >= glob.length) out += '.*'
21 } else {
22 out += '[^/]*'
23 i++
24 }
25 } else if (c === '?') {
26 out += '[^/]'
27 i++
28 } else {
29 out += c.replace(REGEX_SPECIALS, '\\$&')
30 i++
31 }
32 }
33 return new RegExp(out + '$')
35​
36export function matchesGlob(path: string, glob: string): boolean {
37 return globToRegExp(glob).test(path)
39​
40export function matchesAnyGlob(path: string, globs: Array<string>): boolean {
41 return globs.some((g) => matchesGlob(path, g))