1use anyhow::{Result, bail};
20use globset::{GlobBuilder, GlobSet, GlobSetBuilder};
21
22#[derive(Clone)]
23pub struct Pattern {
24 included: GlobSet,
25 excluded: GlobSet,
26}
27
28impl Pattern {
29 pub fn new(pattern: &str, negated: bool) -> Result<Self> {
34 Self::from_globs(&[pattern], negated)
35 }
36
37 pub fn fileset(pattern: &str, negated: bool) -> Result<Self> {
40 if pattern.is_empty() || pattern.ends_with('/') || !names_a_path(pattern) {
41 return Self::new(pattern, negated);
42 }
43 Self::from_globs(&[pattern, &format!("{pattern}/**")], negated)
44 }
45
46 fn from_globs(patterns: &[&str], negated: bool) -> Result<Self> {
47 let mut included = GlobSetBuilder::new();
48 let mut excluded = GlobSetBuilder::new();
49 for pattern in patterns {
50 let globs = if negated
51 || ["|", "(", "{,", "!"]
52 .iter()
53 .any(|token| unescaped(pattern).contains(token))
54 {
55 expand(pattern)?
56 } else {
57 vec![((*pattern).to_owned(), false)]
58 };
59 for (glob, excludes) in globs {
60 let glob = if glob.ends_with('/') {
61 format!("{glob}**")
62 } else {
63 glob
64 };
65 let glob = GlobBuilder::new(&glob)
66 .literal_separator(true)
67 .backslash_escape(true)
68 .build()?;
69 if excludes && !negated {
70 excluded.add(glob);
71 } else {
72 included.add(glob);
73 }
74 }
75 }
76 Ok(Self {
77 included: included.build()?,
78 excluded: excluded.build()?,
79 })
80 }
81
82 pub fn is_match(&self, path: impl AsRef<std::path::Path>) -> bool {
85 let path = path.as_ref();
86 let excluded = self.excluded.is_match(path);
87 if self.included.is_empty() {
88 !excluded
89 } else {
90 !excluded && self.included.is_match(path)
91 }
92 }
93}
94
95fn unescaped(pattern: &str) -> String {
98 let mut result = String::new();
99 let mut chars = pattern.chars();
100 while let Some(c) = chars.next() {
101 if c == '\\' {
102 chars.next();
103 } else {
104 result.push(c);
105 }
106 }
107 result
108}
109
110pub fn escape(path: &str) -> String {
113 let mut escaped = String::with_capacity(path.len());
114 for c in path.chars() {
115 if matches!(
116 c,
117 '*' | '?' | '[' | ']' | '{' | '}' | '(' | ')' | '!' | '@' | '+' | ',' | '|' | '\\'
118 ) {
119 escaped.push('\\');
120 }
121 escaped.push(c);
122 }
123 escaped
124}
125
126pub fn literal_path(pattern: &str) -> String {
129 let mut path = String::new();
130 let mut chars = pattern.chars();
131 while let Some(c) = chars.next() {
132 path.push(if c == '\\' {
133 chars.next().unwrap_or('\\')
134 } else {
135 c
136 });
137 }
138 path
139}
140
141pub fn names_a_path(pattern: &str) -> bool {
145 !unescaped(pattern).contains(['*', '?', '[', ']', '{', '}', '(', ')', '!'])
146}
147
148pub fn is_literal(segment: &str) -> bool {
150 !segment.contains([
151 '!', '?', '@', '+', '*', '|', ',', '{', '}', '[', ']', '(', ')', '\\',
152 ])
153}
154
155#[derive(Debug, PartialEq)]
156enum Group {
157 Optional(String),
159 Once(String),
161 Negated(String),
163 NegatedFileName(String),
165 NegatedWildcard(String),
167 Literal(String),
168}
169
170fn expand(pattern: &str) -> Result<Vec<(String, bool)>> {
174 let segments: Vec<_> = pattern.split('/').collect();
175 let mut built = Vec::new();
176 for (index, segment) in segments.iter().enumerate() {
177 let groups = parse_segment(segment)
178 .map_err(|error| anyhow::anyhow!("{error} in glob {pattern:?}"))?;
179 built.push(build_segment(
180 "",
181 &groups,
182 index == segments.len() - 1,
183 false,
184 ));
185 }
186 let mut products: Vec<Vec<&(String, bool)>> = vec![Vec::new()];
188 for options in &built {
189 products = products
190 .iter()
191 .flat_map(|product| {
192 options.iter().map(move |option| {
193 let mut next = product.clone();
194 next.push(option);
195 next
196 })
197 })
198 .collect();
199 }
200 let mut globs: Vec<(String, bool)> = products
201 .into_iter()
202 .map(|product| {
203 let mut path = String::new();
204 let mut excludes = false;
205 let mut whole = false;
206 for (index, (segment, negative)) in product.iter().enumerate() {
207 whole = index == product.len() - 1;
208 path.push_str(segment);
209 path.push('/');
210 if *negative {
211 excludes = true;
212 if !whole {
213 break;
214 }
215 }
216 }
217 if whole {
218 path.pop();
219 }
220 (path, excludes)
221 })
222 .collect();
223 globs.sort_by(|a, b| (!a.1, &a.0).cmp(&(!b.1, &b.0)));
224 globs.dedup();
225 Ok(globs)
226}
227
228fn parse_segment(segment: &str) -> Result<Vec<Group>> {
229 let mut groups = Vec::new();
230 let mut rest = segment;
231 while !rest.is_empty() {
232 if let Some(after) = rest.strip_prefix(['?', '+', '@'])
234 && !after.is_empty()
235 && !after.starts_with('(')
236 {
237 rest = after;
238 }
239 let parsed = [
240 ("(", ")", false),
241 ("*(", ")", true),
242 ("?(", ")", true),
243 ("+(", ")", false),
244 ("@(", ")", false),
245 ("{,", "}", true),
246 ]
247 .into_iter()
248 .find_map(|(open, close, optional)| {
249 let body = rest.strip_prefix(open)?;
250 let end = body.find(close)?;
251 let items = body[..end].split(['|', ',']).collect::<Vec<_>>().join(",");
252 let group = if optional {
253 Group::Optional(items)
254 } else {
255 Group::Once(items)
256 };
257 Some((group, &body[end + close.len()..]))
258 })
259 .or_else(|| {
261 let body = rest.strip_prefix("!(")?;
262 let end = body.find(')')?;
263 let items = body[..end].split(['|', ',']).collect::<Vec<_>>().join(",");
264 let after = &body[end + 1..];
265 Some(if let Some(after) = after.strip_prefix('.') {
266 (Group::NegatedFileName(items), after)
267 } else if let Some(after) = after.strip_prefix('*') {
268 (Group::NegatedWildcard(items), after)
269 } else {
270 (Group::Negated(items), after)
271 })
272 });
273 if let Some((group, remaining)) = parsed {
274 groups.push(group);
275 rest = remaining;
276 continue;
277 }
278 let end = literal_end(rest);
281 if end == 0 {
282 bail!("unsupported glob syntax at {rest:?}");
283 }
284 groups.push(Group::Literal(rest[..end].to_owned()));
285 rest = &rest[end..];
286 }
287 Ok(groups)
288}
289
290fn literal_end(rest: &str) -> usize {
293 let mut brace = None;
294 let mut special = None;
295 let mut chars = rest.char_indices();
296 while let Some((index, c)) = chars.next() {
297 match c {
298 '\\' => {
299 chars.next();
300 }
301 '{' if brace.is_none() && rest[index + 1..].starts_with(',') => brace = Some(index),
302 '?' | '+' | '@' | '!' | '(' if special.is_none() => special = Some(index),
303 _ => {}
304 }
305 }
306 brace.or(special).unwrap_or(rest.len())
307}
308
309fn display(items: &str) -> String {
310 if items.contains(',') {
311 format!("{{{items}}}")
312 } else {
313 items.to_owned()
314 }
315}
316
317fn build_segment(
320 existing: &str,
321 groups: &[Group],
322 is_last: bool,
323 negative: bool,
324) -> Vec<(String, bool)> {
325 let Some((group, rest)) = groups.split_first() else {
326 return vec![(existing.to_owned(), negative)];
327 };
328 let omitted = if is_last { existing } else { "*" };
330 let both = |off: &str, on: &str, on_negative: bool| {
331 let mut options = build_segment(off, rest, is_last, negative);
332 options.extend(build_segment(on, rest, is_last, on_negative));
333 options
334 };
335 match group {
336 Group::Optional(items) => both(omitted, &format!("{existing}{}", display(items)), negative),
337 Group::Negated(items) => both(omitted, &format!("{existing}{}", display(items)), true),
338 Group::NegatedFileName(items) => {
339 both("*.", &format!("{existing}{}.", display(items)), true)
340 }
341 Group::NegatedWildcard(items) => both("*", &format!("{existing}{}*", display(items)), true),
342 Group::Once(items) => build_segment(
343 &format!("{existing}{}", display(items)),
344 rest,
345 is_last,
346 negative,
347 ),
348 Group::Literal(text) => {
349 build_segment(&format!("{existing}{text}"), rest, is_last, negative)
350 }
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::*;
357
358 fn nx(pattern: &str) -> Vec<String> {
360 expand(pattern)
361 .unwrap()
362 .into_iter()
363 .map(|(glob, excludes)| if excludes { format!("!{glob}") } else { glob })
364 .collect()
365 }
366
367 #[test]
369 fn expands_like_nx() {
370 assert_eq!(
371 nx("libs/**/?(*.)+spec.ts?(.snap)"),
372 [
373 "libs/**/*.spec.ts",
374 "libs/**/*.spec.ts.snap",
375 "libs/**/spec.ts",
376 "libs/**/spec.ts.snap"
377 ]
378 );
379 for pattern in [
380 "libs/**/?(*.)@spec.ts?(.snap)",
381 "libs/**/?(*.)?spec.ts?(.snap)",
382 ] {
383 assert_eq!(nx(pattern), nx("libs/**/?(*.)+spec.ts?(.snap)"));
384 }
385 assert_eq!(nx("dist/**/*.js"), ["dist/**/*.js"]);
386 assert_eq!(nx("**/*.(js|ts)"), ["**/*.{js,ts}"]);
387 assert_eq!(
388 nx("**/*.spec.ts{,.snap}"),
389 ["**/*.spec.ts", "**/*.spec.ts.snap"]
390 );
391 }
392
393 #[test]
394 fn expands_workspace_patterns() {
395 assert_eq!(
396 nx("app/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)"),
397 [
398 "app/**/*.{spec,test}.[jt]s",
399 "app/**/*.{spec,test}.[jt]s.snap",
400 "app/**/*.{spec,test}.[jt]sx",
401 "app/**/*.{spec,test}.[jt]sx.snap",
402 "app/**/{spec,test}.[jt]s",
403 "app/**/{spec,test}.[jt]s.snap",
404 "app/**/{spec,test}.[jt]sx",
405 "app/**/{spec,test}.[jt]sx.snap",
406 ]
407 );
408 assert_eq!(nx("biome.json?(c)"), ["biome.json", "biome.jsonc"]);
409 assert_eq!(nx("app/(.cache|dist)/**/*"), ["app/{.cache,dist}/**/*"]);
410 assert_eq!(nx("a?(b)/c"), ["*/c", "ab/c"]);
412 }
413
414 #[test]
415 fn rejects_what_nx_rejects() {
416 assert!(expand("src/a!b").is_err());
417 assert!(expand("file?").is_err());
418 assert!(expand("src/(unterminated").is_err());
419 }
420
421 #[test]
423 fn expands_negated_groups_like_nx() {
424 assert_eq!(
425 nx("dist/!(cache|cache2)/**/!(README|LICENSE).(js|ts)"),
426 [
427 "!dist/*/**/{README,LICENSE}.{js,ts}",
428 "!dist/{cache,cache2}/",
429 "dist/*/**/*.{js,ts}",
430 ]
431 );
432 assert_eq!(
433 nx("dist/**/!(README|LICENSE).(js|ts)"),
434 ["!dist/**/{README,LICENSE}.{js,ts}", "dist/**/*.{js,ts}"]
435 );
436 assert_eq!(
437 nx("dist/!(cache|cache2)/**/*.(js|ts)"),
438 ["!dist/{cache,cache2}/", "dist/*/**/*.{js,ts}"]
439 );
440 assert_eq!(
441 nx("dist/!(cache|cache2)/**/*.js"),
442 ["!dist/{cache,cache2}/", "dist/*/**/*.js"]
443 );
444 assert_eq!(
445 nx("packages/!(package-a)*"),
446 ["!packages/package-a*", "packages/*"]
447 );
448 assert_eq!(
449 nx("packages/!(package-a)*/package.json"),
450 ["!packages/package-a*/", "packages/*/package.json"]
451 );
452 assert_eq!(nx("**/!(package-a)*"), ["!**/package-a*", "**/*"]);
453 assert_eq!(
454 nx("!(test|e2e)/?(*.)+(spec|test).[jt]s!(x)?(.snap)"),
455 [
456 "!*/*.{spec,test}.[jt]sx",
457 "!*/*.{spec,test}.[jt]sx.snap",
458 "!*/{spec,test}.[jt]sx",
459 "!*/{spec,test}.[jt]sx.snap",
460 "!{test,e2e}/",
461 "*/*.{spec,test}.[jt]s",
462 "*/*.{spec,test}.[jt]s.snap",
463 "*/{spec,test}.[jt]s",
464 "*/{spec,test}.[jt]s.snap",
465 ]
466 );
467 }
468
469 #[test]
470 fn negated_groups_exclude_what_they_name() {
471 let pattern = Pattern::new("src/**/!(*.test|*.spec).ts", false).unwrap();
472 assert!(pattern.is_match("src/a/x.ts"));
473 assert!(!pattern.is_match("src/a/x.test.ts") && !pattern.is_match("src/a/x.spec.ts"));
474 let directories = Pattern::new("src/!(a|b)/*", false).unwrap();
475 assert!(directories.is_match("src/c/z.md"));
476 assert!(!directories.is_match("src/a/x.ts"));
477 let odd = Pattern::new("src/**/*.!(ts)", false).unwrap();
480 assert!(!odd.is_match("src/b/y.js") && !odd.is_match("src/b/y.ts"));
481 let whole = Pattern::new("src/**/!(*.test).ts", true).unwrap();
483 assert!(whole.is_match("src/a/x.ts") && whole.is_match("src/a/x.test.ts"));
484 }
485
486 #[test]
487 fn matches_expanded_patterns() {
488 let tests = Pattern::new("app/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)", true).unwrap();
489 for path in [
490 "app/a.spec.ts",
491 "app/deep/b.test.jsx",
492 "app/test.ts",
493 "app/c.spec.tsx.snap",
494 ] {
495 assert!(tests.is_match(path), "{path}");
496 }
497 for path in ["app/a.ts", "app/a.spec.mts", "other/a.spec.ts"] {
498 assert!(!tests.is_match(path), "{path}");
499 }
500 let plain = Pattern::new("src/*.ts", false).unwrap();
501 assert!(plain.is_match("src/a.ts") && !plain.is_match("src/a/b.ts"));
502 }
503
504 #[test]
507 fn a_backslash_escapes_the_next_character() {
508 let route = Pattern::new(r"app/\(marketing\)/**/*", false).unwrap();
509 assert!(route.is_match("app/(marketing)/page.tsx"));
510 assert!(!route.is_match("app/marketing/page.tsx"));
511 let id = Pattern::new(r"src/\[id\].ts", false).unwrap();
512 assert!(id.is_match("src/[id].ts") && !id.is_match("src/i.ts"));
513 let mixed = Pattern::new(r"app/\(a\)/?(*.)+(spec|test).ts", false).unwrap();
514 assert!(mixed.is_match("app/(a)/x.spec.ts") && !mixed.is_match("app/a/x.spec.ts"));
515 assert!(!Pattern::new(r"src\**", false).unwrap().is_match("src/a.ts"));
518 }
519
520 #[test]
522 fn a_fileset_path_with_no_pattern_names_a_file_or_a_directory() {
523 for pattern in ["src", "src/"] {
524 let fileset = Pattern::fileset(pattern, false).unwrap();
525 assert!(fileset.is_match("src/a.ts") && fileset.is_match("src/deep/b.ts"));
526 assert!(!fileset.is_match("srcs/a.ts"));
527 }
528 assert!(
529 Pattern::fileset("package.json", false)
530 .unwrap()
531 .is_match("package.json")
532 );
533 for named in ["@types", "c++", r"\(group\)"] {
534 let fileset = Pattern::fileset(named, false).unwrap();
535 let unescaped = named.replace('\\', "");
536 assert!(fileset.is_match(format!("{unescaped}/x")), "{named}");
537 }
538 let glob = Pattern::fileset("src/*.ts", false).unwrap();
540 assert!(glob.is_match("src/a.ts") && !glob.is_match("src/a.ts/b"));
541 assert!(!Pattern::new("src", false).unwrap().is_match("src/a.ts"));
542 }
543
544 #[test]
546 fn selects_the_files_nx_selects() {
547 let files = [
548 "src/a/x.ts",
549 "src/a/x.test.ts",
550 "src/a/x.spec.ts",
551 "src/b/y.ts",
552 "src/b/y.js",
553 "src/c/deep/z.ts",
554 "src/c/z.md",
555 "src/root.ts",
556 "src/README.md",
557 ];
558 let selected = |pattern: &str| -> Vec<&str> {
559 let pattern = Pattern::new(pattern, false).unwrap();
560 files
561 .iter()
562 .copied()
563 .filter(|file| pattern.is_match(file))
564 .collect()
565 };
566 assert_eq!(
567 selected("src/**/!(*.test).ts"),
568 [
569 "src/a/x.ts",
570 "src/a/x.spec.ts",
571 "src/b/y.ts",
572 "src/c/deep/z.ts",
573 "src/root.ts"
574 ]
575 );
576 assert_eq!(
577 selected("src/!(a)/**"),
578 ["src/b/y.ts", "src/b/y.js", "src/c/deep/z.ts", "src/c/z.md"]
579 );
580 assert_eq!(selected("src/**/*.!(ts)"), [] as [&str; 0]);
581 assert_eq!(selected("src/!(a|b)/*"), ["src/c/z.md"]);
582 assert_eq!(
583 selected("src/*/!(x)*"),
584 ["src/b/y.ts", "src/b/y.js", "src/c/z.md"]
585 );
586 assert_eq!(
587 selected("src/**/!(*.test|*.spec).ts"),
588 ["src/a/x.ts", "src/b/y.ts", "src/c/deep/z.ts", "src/root.ts"]
589 );
590 }
591}