Skip to main content

globset/
lib.rs

1/*!
2The globset crate provides cross platform single glob and glob set matching.
3
4Glob set matching is the process of matching one or more glob patterns against
5a single candidate path simultaneously, and returning all of the globs that
6matched. For example, given this set of globs:
7
8* `*.rs`
9* `src/lib.rs`
10* `src/**/foo.rs`
11
12and a path `src/bar/baz/foo.rs`, then the set would report the first and third
13globs as matching.
14
15# Example: one glob
16
17This example shows how to match a single glob against a single file path.
18
19```
20use globset::Glob;
21
22let glob = Glob::new("*.rs")?.compile_matcher();
23
24assert!(glob.is_match("foo.rs"));
25assert!(glob.is_match("foo/bar.rs"));
26assert!(!glob.is_match("Cargo.toml"));
27# Ok::<(), Box<dyn std::error::Error>>(())
28```
29
30# Example: configuring a glob matcher
31
32This example shows how to use a `GlobBuilder` to configure aspects of match
33semantics. In this example, we prevent wildcards from matching path separators.
34
35```
36use globset::GlobBuilder;
37
38let glob = GlobBuilder::new("*.rs")
39    .literal_separator(true).build()?.compile_matcher();
40
41assert!(glob.is_match("foo.rs"));
42assert!(!glob.is_match("foo/bar.rs")); // no longer matches
43assert!(!glob.is_match("Cargo.toml"));
44# Ok::<(), Box<dyn std::error::Error>>(())
45```
46
47# Example: match multiple globs at once
48
49This example shows how to match multiple glob patterns at once.
50
51```
52use globset::{Glob, GlobSetBuilder};
53
54let mut builder = GlobSetBuilder::new();
55// A GlobBuilder can be used to configure each glob's match semantics
56// independently.
57builder.add(Glob::new("*.rs")?);
58builder.add(Glob::new("src/lib.rs")?);
59builder.add(Glob::new("src/**/foo.rs")?);
60let set = builder.build()?;
61
62assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]);
63# Ok::<(), Box<dyn std::error::Error>>(())
64```
65
66# Syntax
67
68Standard Unix-style glob syntax is supported:
69
70* `?` matches any single character. (If the `literal_separator` option is
71  enabled, then `?` can never match a path separator.)
72* `*` matches zero or more characters. (If the `literal_separator` option is
73  enabled, then `*` can never match a path separator.)
74* `**` recursively matches directories but are only legal in three situations.
75  First, if the glob starts with <code>\*\*&#x2F;</code>, then it matches
76  all directories. For example, <code>\*\*&#x2F;foo</code> matches `foo`
77  and `bar/foo` but not `foo/bar`. Secondly, if the glob ends with
78  <code>&#x2F;\*\*</code>, then it matches all sub-entries. For example,
79  <code>foo&#x2F;\*\*</code> matches `foo/a` and `foo/a/b`, but not `foo`.
80  Thirdly, if the glob contains <code>&#x2F;\*\*&#x2F;</code> anywhere within
81  the pattern, then it matches zero or more directories. Using `**` anywhere
82  else is illegal (N.B. the glob `**` is allowed and means "match everything").
83* `{a,b}` matches `a` or `b` where `a` and `b` are arbitrary glob patterns.
84  (N.B. Nesting `{...}` is allowed.)
85* `[ab]` matches `a` or `b` where `a` and `b` are characters. Use
86  `[!ab]` to match any character except for `a` and `b`.
87* `[[:alpha:]]`, `[[:digit:]]`, `[[:space:]]` etc. match POSIX character
88  classes using ASCII-only definitions. Supported classes: `alnum`, `alpha`,
89  `blank`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`,
90  `upper`, `xdigit`. These can be combined with regular ranges, e.g.,
91  `[[:digit:]a-f]` matches hexadecimal digits.
92* Metacharacters such as `*` and `?` can be escaped with character class
93  notation. e.g., `[*]` matches `*`.
94* When backslash escapes are enabled, a backslash (`\`) will escape all meta
95  characters in a glob. If it precedes a non-meta character, then the slash is
96  ignored. A `\\` will match a literal `\\`. Note that this mode is only
97  enabled on Unix platforms by default, but can be enabled on any platform
98  via the `backslash_escape` setting on `Glob`.
99
100A `GlobBuilder` can be used to prevent wildcards from matching path separators,
101or to enable case insensitive matching.
102
103# Crate Features
104
105This crate includes optional features that can be enabled if necessary.
106These features are not required but may be useful depending on the use case.
107
108The following features are available:
109
110* **arbitrary** -
111  Enabling this feature introduces a public dependency on the
112  [`arbitrary`](https://crates.io/crates/arbitrary)
113  crate. Namely, it implements the `Arbitrary` trait from that crate for the
114  [`Glob`] type. This feature is disabled by default.
115*/
116
117#![deny(missing_docs)]
118
119use std::{
120    borrow::Cow,
121    panic::{RefUnwindSafe, UnwindSafe},
122    path::Path,
123    sync::Arc,
124};
125
126use {
127    aho_corasick::AhoCorasick,
128    bstr::{B, ByteSlice, ByteVec},
129    regex_automata::{
130        PatternSet,
131        meta::Regex,
132        util::pool::{Pool, PoolGuard},
133    },
134};
135
136use crate::{
137    glob::MatchStrategy,
138    pathutil::{file_name, file_name_ext, normalize_path},
139};
140
141pub use crate::glob::{Glob, GlobBuilder, GlobMatcher};
142
143mod fnv;
144mod glob;
145mod pathutil;
146
147#[cfg(feature = "serde1")]
148mod serde_impl;
149
150#[cfg(feature = "log")]
151macro_rules! debug {
152    ($($token:tt)*) => (::log::debug!($($token)*);)
153}
154
155#[cfg(not(feature = "log"))]
156macro_rules! debug {
157    ($($token:tt)*) => {};
158}
159
160/// Represents an error that can occur when parsing a glob pattern.
161#[derive(Clone, Debug, Eq, PartialEq)]
162pub struct Error {
163    /// The original glob provided by the caller.
164    glob: Option<String>,
165    /// The kind of error.
166    kind: ErrorKind,
167}
168
169/// The kind of error that can occur when parsing a glob pattern.
170#[derive(Clone, Debug, Eq, PartialEq)]
171#[non_exhaustive]
172pub enum ErrorKind {
173    /// **DEPRECATED**.
174    ///
175    /// This error used to occur for consistency with git's glob specification,
176    /// but the specification now accepts all uses of `**`. When `**` does not
177    /// appear adjacent to a path separator or at the beginning/end of a glob,
178    /// it is now treated as two consecutive `*` patterns. As such, this error
179    /// is no longer used.
180    InvalidRecursive,
181    /// Occurs when a character class (e.g., `[abc]`) is not closed.
182    UnclosedClass,
183    /// Occurs when a range in a character (e.g., `[a-z]`) is invalid. For
184    /// example, if the range starts with a lexicographically larger character
185    /// than it ends with.
186    InvalidRange(char, char),
187    /// Occurs when a `}` is found without a matching `{`.
188    UnopenedAlternates,
189    /// Occurs when a `{` is found without a matching `}`.
190    UnclosedAlternates,
191    /// **DEPRECATED**.
192    ///
193    /// This error used to occur when an alternating group was nested inside
194    /// another alternating group, e.g., `{{a,b},{c,d}}`. However, this is now
195    /// supported and as such this error cannot occur.
196    NestedAlternates,
197    /// Occurs when alternating groups are nested too deeply.
198    TooManyNestedAlternates,
199    /// Occurs when an unescaped '\' is found at the end of a glob.
200    DanglingEscape,
201    /// An error associated with parsing or compiling a regex.
202    Regex(String),
203}
204
205impl std::error::Error for Error {
206    fn description(&self) -> &str {
207        self.kind.description()
208    }
209}
210
211impl Error {
212    /// Return the glob that caused this error, if one exists.
213    pub fn glob(&self) -> Option<&str> {
214        self.glob.as_ref().map(|s| &**s)
215    }
216
217    /// Return the kind of this error.
218    pub fn kind(&self) -> &ErrorKind {
219        &self.kind
220    }
221}
222
223impl ErrorKind {
224    fn description(&self) -> &str {
225        match *self {
226            ErrorKind::InvalidRecursive => {
227                "invalid use of **; must be one path component"
228            }
229            ErrorKind::UnclosedClass => {
230                "unclosed character class; missing ']'"
231            }
232            ErrorKind::InvalidRange(_, _) => "invalid character range",
233            ErrorKind::UnopenedAlternates => {
234                "unopened alternate group; missing '{' \
235                (maybe escape '}' with '[}]'?)"
236            }
237            ErrorKind::UnclosedAlternates => {
238                "unclosed alternate group; missing '}' \
239                (maybe escape '{' with '[{]'?)"
240            }
241            ErrorKind::NestedAlternates => {
242                "nested alternate groups are not allowed"
243            }
244            ErrorKind::TooManyNestedAlternates => {
245                "alternate groups nested too deeply"
246            }
247            ErrorKind::DanglingEscape => "dangling '\\'",
248            ErrorKind::Regex(ref err) => err,
249        }
250    }
251}
252
253impl std::fmt::Display for Error {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        match self.glob {
256            None => self.kind.fmt(f),
257            Some(ref glob) => {
258                write!(f, "error parsing glob '{}': {}", glob, self.kind)
259            }
260        }
261    }
262}
263
264impl std::fmt::Display for ErrorKind {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        match *self {
267            ErrorKind::InvalidRecursive
268            | ErrorKind::UnclosedClass
269            | ErrorKind::UnopenedAlternates
270            | ErrorKind::UnclosedAlternates
271            | ErrorKind::NestedAlternates
272            | ErrorKind::TooManyNestedAlternates
273            | ErrorKind::DanglingEscape
274            | ErrorKind::Regex(_) => write!(f, "{}", self.description()),
275            ErrorKind::InvalidRange(s, e) => {
276                write!(f, "invalid range; '{}' > '{}'", s, e)
277            }
278        }
279    }
280}
281
282fn new_regex(pat: &str) -> Result<Regex, Error> {
283    let syntax = regex_automata::util::syntax::Config::new()
284        .utf8(false)
285        .dot_matches_new_line(true);
286    let config = Regex::config()
287        .utf8_empty(false)
288        .nfa_size_limit(Some(10 * (1 << 20)))
289        .hybrid_cache_capacity(10 * (1 << 20));
290    Regex::builder().syntax(syntax).configure(config).build(pat).map_err(
291        |err| Error {
292            glob: Some(pat.to_string()),
293            kind: ErrorKind::Regex(err.to_string()),
294        },
295    )
296}
297
298fn new_regex_set(pats: Vec<String>) -> Result<Regex, Error> {
299    let syntax = regex_automata::util::syntax::Config::new()
300        .utf8(false)
301        .dot_matches_new_line(true);
302    let config = Regex::config()
303        .match_kind(regex_automata::MatchKind::All)
304        .utf8_empty(false)
305        .nfa_size_limit(Some(10 * (1 << 20)))
306        .hybrid_cache_capacity(10 * (1 << 20));
307    Regex::builder()
308        .syntax(syntax)
309        .configure(config)
310        .build_many(&pats)
311        .map_err(|err| Error {
312            glob: None,
313            kind: ErrorKind::Regex(err.to_string()),
314        })
315}
316
317/// GlobSet represents a group of globs that can be matched together in a
318/// single pass.
319#[derive(Clone)]
320pub struct GlobSet {
321    len: usize,
322    strats: Vec<GlobSetMatchStrategy>,
323    pats: Vec<Glob>,
324}
325
326impl std::fmt::Debug for GlobSet {
327    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328        f.debug_tuple("GlobSet").field(&self.pats).finish()
329    }
330}
331
332impl GlobSet {
333    /// Create a new [`GlobSetBuilder`]. A `GlobSetBuilder` can be used to add
334    /// new patterns. Once all patterns have been added, `build` should be
335    /// called to produce a `GlobSet`, which can then be used for matching.
336    #[inline]
337    pub fn builder() -> GlobSetBuilder {
338        GlobSetBuilder::new()
339    }
340
341    /// Create an empty `GlobSet`. An empty set matches nothing.
342    #[inline]
343    pub const fn empty() -> GlobSet {
344        GlobSet { len: 0, strats: vec![], pats: vec![] }
345    }
346
347    /// Returns true if this set is empty, and therefore matches nothing.
348    #[inline]
349    pub fn is_empty(&self) -> bool {
350        self.len == 0
351    }
352
353    /// Returns the number of globs in this set.
354    #[inline]
355    pub fn len(&self) -> usize {
356        self.len
357    }
358
359    /// Returns true if any glob in this set matches the path given.
360    pub fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
361        self.is_match_candidate(&Candidate::new(path.as_ref()))
362    }
363
364    /// Returns true if any glob in this set matches the path given.
365    ///
366    /// This takes a Candidate as input, which can be used to amortize the
367    /// cost of preparing a path for matching.
368    pub fn is_match_candidate(&self, path: &Candidate<'_>) -> bool {
369        if self.is_empty() {
370            return false;
371        }
372        for strat in &self.strats {
373            if strat.is_match(path) {
374                return true;
375            }
376        }
377        false
378    }
379
380    /// Returns true if all globs in this set match the path given.
381    ///
382    /// This will return true if the set of globs is empty, as in that case all
383    /// `0` of the globs will match.
384    ///
385    /// ```
386    /// use globset::{Glob, GlobSetBuilder};
387    ///
388    /// let mut builder = GlobSetBuilder::new();
389    /// builder.add(Glob::new("src/*").unwrap());
390    /// builder.add(Glob::new("**/*.rs").unwrap());
391    /// let set = builder.build().unwrap();
392    ///
393    /// assert!(set.matches_all("src/foo.rs"));
394    /// assert!(!set.matches_all("src/bar.c"));
395    /// assert!(!set.matches_all("test.rs"));
396    /// ```
397    pub fn matches_all<P: AsRef<Path>>(&self, path: P) -> bool {
398        self.matches_all_candidate(&Candidate::new(path.as_ref()))
399    }
400
401    /// Returns true if all globs in this set match the path given.
402    ///
403    /// This takes a Candidate as input, which can be used to amortize the cost
404    /// of preparing a path for matching.
405    ///
406    /// This will return true if the set of globs is empty, as in that case all
407    /// `0` of the globs will match.
408    pub fn matches_all_candidate(&self, path: &Candidate<'_>) -> bool {
409        for strat in &self.strats {
410            if !strat.matches_all(path) {
411                return false;
412            }
413        }
414        true
415    }
416
417    /// Returns the sequence number of every glob pattern that matches the
418    /// given path.
419    pub fn matches<P: AsRef<Path>>(&self, path: P) -> Vec<usize> {
420        self.matches_candidate(&Candidate::new(path.as_ref()))
421    }
422
423    /// Returns the sequence number of every glob pattern that matches the
424    /// given path.
425    ///
426    /// This takes a Candidate as input, which can be used to amortize the
427    /// cost of preparing a path for matching.
428    pub fn matches_candidate(&self, path: &Candidate<'_>) -> Vec<usize> {
429        let mut into = vec![];
430        if self.is_empty() {
431            return into;
432        }
433        self.matches_candidate_into(path, &mut into);
434        into
435    }
436
437    /// Adds the sequence number of every glob pattern that matches the given
438    /// path to the vec given.
439    ///
440    /// `into` is cleared before matching begins, and contains the set of
441    /// sequence numbers (in ascending order) after matching ends. If no globs
442    /// were matched, then `into` will be empty.
443    pub fn matches_into<P: AsRef<Path>>(
444        &self,
445        path: P,
446        into: &mut Vec<usize>,
447    ) {
448        self.matches_candidate_into(&Candidate::new(path.as_ref()), into);
449    }
450
451    /// Adds the sequence number of every glob pattern that matches the given
452    /// path to the vec given.
453    ///
454    /// `into` is cleared before matching begins, and contains the set of
455    /// sequence numbers (in ascending order) after matching ends. If no globs
456    /// were matched, then `into` will be empty.
457    ///
458    /// This takes a Candidate as input, which can be used to amortize the
459    /// cost of preparing a path for matching.
460    pub fn matches_candidate_into(
461        &self,
462        path: &Candidate<'_>,
463        into: &mut Vec<usize>,
464    ) {
465        into.clear();
466        if self.is_empty() {
467            return;
468        }
469        for strat in &self.strats {
470            strat.matches_into(path, into);
471        }
472        into.sort();
473        into.dedup();
474    }
475
476    /// Builds a new matcher from a collection of Glob patterns.
477    ///
478    /// Once a matcher is built, no new patterns can be added to it.
479    pub fn new<I, G>(globs: I) -> Result<GlobSet, Error>
480    where
481        I: IntoIterator<Item = G>,
482        G: AsRef<Glob>,
483    {
484        let mut it = globs.into_iter().peekable();
485        if it.peek().is_none() {
486            return Ok(GlobSet::empty());
487        }
488
489        let mut len = 0;
490        let mut pats = vec![];
491        let mut lits = LiteralStrategy::new();
492        let mut base_lits = LiteralStrategy::new();
493        let mut exts = ExtensionStrategy::new();
494        let mut prefixes = MultiStrategyBuilder::new();
495        let mut suffixes = MultiStrategyBuilder::new();
496        let mut required_exts = RequiredExtensionStrategyBuilder::new();
497        let mut base_regexes = MultiStrategyBuilder::new();
498        let mut regexes = MultiStrategyBuilder::new();
499        for (i, p) in it.enumerate() {
500            len += 1;
501
502            let p = p.as_ref();
503            pats.push(p.clone());
504            match MatchStrategy::new(p) {
505                MatchStrategy::Literal(lit) => {
506                    lits.add(i, lit);
507                }
508                MatchStrategy::BasenameLiteral(lit) => {
509                    base_lits.add(i, lit);
510                }
511                MatchStrategy::Extension(ext) => {
512                    exts.add(i, ext);
513                }
514                MatchStrategy::Prefix(prefix) => {
515                    prefixes.add(i, prefix);
516                }
517                MatchStrategy::Suffix { suffix, component } => {
518                    if component {
519                        lits.add(i, suffix[1..].to_string());
520                    }
521                    suffixes.add(i, suffix);
522                }
523                MatchStrategy::RequiredExtension(ext) => {
524                    required_exts.add(i, ext, p.regex().to_owned());
525                }
526                MatchStrategy::BasenameRegex(re) => {
527                    base_regexes.add(i, re);
528                }
529                MatchStrategy::Regex => {
530                    debug!(
531                        "glob `{:?}` converted to regex: `{:?}`",
532                        p,
533                        p.regex()
534                    );
535                    regexes.add(i, p.regex().to_owned());
536                }
537            }
538        }
539        debug!(
540            "built glob set; {} literals, {} basenames, {} extensions, \
541             {} prefixes, {} suffixes, {} required extensions, \
542             {} basename regexes, {} regexes",
543            lits.literals.len(),
544            base_lits.literals.len(),
545            exts.0.len(),
546            prefixes.literals.len(),
547            suffixes.literals.len(),
548            required_exts.0.len(),
549            base_regexes.literals.len(),
550            regexes.literals.len()
551        );
552        let mut strats = Vec::with_capacity(8);
553        // Only add strategies that are populated
554        if !exts.0.is_empty() {
555            strats.push(GlobSetMatchStrategy::Extension(exts));
556        }
557        if !base_lits.literals.is_empty() {
558            strats.push(GlobSetMatchStrategy::BasenameLiteral(base_lits));
559        }
560        if !lits.literals.is_empty() {
561            strats.push(GlobSetMatchStrategy::Literal(lits));
562        }
563        if !suffixes.is_empty() {
564            strats.push(GlobSetMatchStrategy::Suffix(suffixes.suffix()));
565        }
566        if !prefixes.is_empty() {
567            strats.push(GlobSetMatchStrategy::Prefix(prefixes.prefix()));
568        }
569        if !required_exts.0.is_empty() {
570            strats.push(GlobSetMatchStrategy::RequiredExtension(
571                required_exts.build()?,
572            ));
573        }
574        if !base_regexes.is_empty() {
575            let mut set = base_regexes.regex_set()?;
576            set.basename = true;
577            strats.push(GlobSetMatchStrategy::Regex(set));
578        }
579        if !regexes.is_empty() {
580            strats.push(GlobSetMatchStrategy::Regex(regexes.regex_set()?));
581        }
582
583        Ok(GlobSet { len, strats, pats })
584    }
585}
586
587impl Default for GlobSet {
588    /// Create a default empty GlobSet.
589    fn default() -> Self {
590        GlobSet::empty()
591    }
592}
593
594/// GlobSetBuilder builds a group of patterns that can be used to
595/// simultaneously match a file path.
596#[derive(Clone, Debug)]
597pub struct GlobSetBuilder {
598    pats: Vec<Glob>,
599}
600
601impl GlobSetBuilder {
602    /// Create a new `GlobSetBuilder`. A `GlobSetBuilder` can be used to add new
603    /// patterns. Once all patterns have been added, `build` should be called
604    /// to produce a [`GlobSet`], which can then be used for matching.
605    pub fn new() -> GlobSetBuilder {
606        GlobSetBuilder { pats: vec![] }
607    }
608
609    /// Builds a new matcher from all of the glob patterns added so far.
610    ///
611    /// Once a matcher is built, no new patterns can be added to it.
612    pub fn build(&self) -> Result<GlobSet, Error> {
613        GlobSet::new(self.pats.iter())
614    }
615
616    /// Add a new pattern to this set.
617    pub fn add(&mut self, pat: Glob) -> &mut GlobSetBuilder {
618        self.pats.push(pat);
619        self
620    }
621}
622
623/// A candidate path for matching.
624///
625/// All glob matching in this crate operates on `Candidate` values.
626/// Constructing candidates has a very small cost associated with it, so
627/// callers may find it beneficial to amortize that cost when matching a single
628/// path against multiple globs or sets of globs.
629#[derive(Clone)]
630pub struct Candidate<'a> {
631    path: Cow<'a, [u8]>,
632    basename: Cow<'a, [u8]>,
633    ext: Cow<'a, [u8]>,
634}
635
636impl<'a> std::fmt::Debug for Candidate<'a> {
637    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
638        f.debug_struct("Candidate")
639            .field("path", &self.path.as_bstr())
640            .field("basename", &self.basename.as_bstr())
641            .field("ext", &self.ext.as_bstr())
642            .finish()
643    }
644}
645
646impl<'a> Candidate<'a> {
647    /// Create a new candidate for matching from the given path.
648    pub fn new<P: AsRef<Path> + ?Sized>(path: &'a P) -> Candidate<'a> {
649        Self::from_cow(Vec::from_path_lossy(path.as_ref()))
650    }
651
652    /// Create a new candidate for matching from the given path as a sequence
653    /// of bytes.
654    ///
655    /// Generally speaking, this routine expects the bytes to be
656    /// _conventionally_ UTF-8. It is legal for the byte sequence to contain
657    /// invalid UTF-8. However, if the bytes are in some other encoding that
658    /// isn't ASCII compatible (for example, UTF-16), then the results of
659    /// matching are unspecified.
660    pub fn from_bytes<P: AsRef<[u8]> + ?Sized>(path: &'a P) -> Candidate<'a> {
661        Self::from_cow(Cow::Borrowed(path.as_ref()))
662    }
663
664    fn from_cow(path: Cow<'a, [u8]>) -> Candidate<'a> {
665        let path = normalize_path(path);
666        let basename = file_name(&path).unwrap_or(Cow::Borrowed(B("")));
667        let ext = file_name_ext(&basename).unwrap_or(Cow::Borrowed(B("")));
668        Candidate { path, basename, ext }
669    }
670
671    fn path_prefix(&self, max: usize) -> &[u8] {
672        if self.path.len() <= max { &*self.path } else { &self.path[..max] }
673    }
674
675    /// Returns the final component, including `..` for regex matching.
676    fn basename_for_regex(&self) -> &[u8] {
677        // Literal basename strategies skip `..`, but a regex can match it.
678        if self.basename.is_empty() && self.path.ends_with(b"..") {
679            b".."
680        } else {
681            &self.basename
682        }
683    }
684
685    fn path_suffix(&self, max: usize) -> &[u8] {
686        if self.path.len() <= max {
687            &*self.path
688        } else {
689            &self.path[self.path.len() - max..]
690        }
691    }
692}
693
694#[derive(Clone, Debug)]
695enum GlobSetMatchStrategy {
696    Literal(LiteralStrategy),
697    BasenameLiteral(LiteralStrategy),
698    Extension(ExtensionStrategy),
699    Prefix(PrefixStrategy),
700    Suffix(SuffixStrategy),
701    RequiredExtension(RequiredExtensionStrategy),
702    Regex(RegexSetStrategy),
703}
704
705impl GlobSetMatchStrategy {
706    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
707        use self::GlobSetMatchStrategy::*;
708        match *self {
709            Literal(ref s) => s.is_match(candidate.path.as_bytes()),
710            BasenameLiteral(ref s) => {
711                !candidate.basename.is_empty()
712                    && s.is_match(candidate.basename.as_bytes())
713            }
714            Extension(ref s) => s.is_match(candidate),
715            Prefix(ref s) => s.is_match(candidate),
716            Suffix(ref s) => s.is_match(candidate),
717            RequiredExtension(ref s) => s.is_match(candidate),
718            Regex(ref s) => s.is_match(candidate),
719        }
720    }
721
722    fn matches_into(
723        &self,
724        candidate: &Candidate<'_>,
725        matches: &mut Vec<usize>,
726    ) {
727        use self::GlobSetMatchStrategy::*;
728        match *self {
729            Literal(ref s) => {
730                s.matches_into(candidate.path.as_bytes(), matches)
731            }
732            BasenameLiteral(ref s) => {
733                if !candidate.basename.is_empty() {
734                    s.matches_into(candidate.basename.as_bytes(), matches);
735                }
736            }
737            Extension(ref s) => s.matches_into(candidate, matches),
738            Prefix(ref s) => s.matches_into(candidate, matches),
739            Suffix(ref s) => s.matches_into(candidate, matches),
740            RequiredExtension(ref s) => s.matches_into(candidate, matches),
741            Regex(ref s) => s.matches_into(candidate, matches),
742        }
743    }
744
745    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
746        use self::GlobSetMatchStrategy::*;
747        match *self {
748            Literal(ref s) => s.matches_all(candidate.path.as_bytes()),
749            BasenameLiteral(ref s) => {
750                !candidate.basename.is_empty()
751                    && s.matches_all(candidate.basename.as_bytes())
752            }
753            Extension(ref s) => s.matches_all(candidate),
754            Prefix(ref s) => s.matches_all(candidate),
755            Suffix(ref s) => s.matches_all(candidate),
756            RequiredExtension(ref s) => s.matches_all(candidate),
757            Regex(ref s) => s.matches_all(candidate),
758        }
759    }
760}
761
762#[derive(Clone, Debug)]
763struct LiteralStrategy {
764    literals: fnv::HashMap<Vec<u8>, Vec<usize>>,
765    // Literal byte lengths modulo 64, checked before hashing the path.
766    lengths: u64,
767}
768
769impl LiteralStrategy {
770    fn new() -> LiteralStrategy {
771        LiteralStrategy { literals: fnv::HashMap::default(), lengths: 0 }
772    }
773
774    fn add(&mut self, global_index: usize, lit: String) {
775        self.lengths |= 1 << (lit.len() % 64);
776        self.literals
777            .entry(lit.into_bytes())
778            .or_insert(vec![])
779            .push(global_index);
780    }
781
782    fn is_match(&self, path: &[u8]) -> bool {
783        self.may_match_length(path.len()) && self.literals.contains_key(path)
784    }
785
786    fn matches_all(&self, path: &[u8]) -> bool {
787        self.literals.len() == 1 && self.is_match(path)
788    }
789
790    #[inline(never)]
791    fn matches_into(&self, path: &[u8], matches: &mut Vec<usize>) {
792        if !self.may_match_length(path.len()) {
793            return;
794        }
795        if let Some(hits) = self.literals.get(path) {
796            matches.extend(hits);
797        }
798    }
799
800    /// Returns whether a length could match, allowing collisions modulo 64.
801    fn may_match_length(&self, len: usize) -> bool {
802        self.lengths & (1 << (len % 64)) != 0
803    }
804}
805
806#[derive(Clone, Debug)]
807struct ExtensionStrategy(fnv::HashMap<Vec<u8>, Vec<usize>>);
808
809impl ExtensionStrategy {
810    fn new() -> ExtensionStrategy {
811        ExtensionStrategy(fnv::HashMap::default())
812    }
813
814    fn add(&mut self, global_index: usize, ext: String) {
815        self.0.entry(ext.into_bytes()).or_insert(vec![]).push(global_index);
816    }
817
818    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
819        if candidate.ext.is_empty() {
820            return false;
821        }
822        self.0.contains_key(candidate.ext.as_bytes())
823    }
824
825    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
826        self.0.len() == 1 && self.is_match(candidate)
827    }
828
829    #[inline(never)]
830    fn matches_into(
831        &self,
832        candidate: &Candidate<'_>,
833        matches: &mut Vec<usize>,
834    ) {
835        if candidate.ext.is_empty() {
836            return;
837        }
838        if let Some(hits) = self.0.get(candidate.ext.as_bytes()) {
839            matches.extend(hits);
840        }
841    }
842}
843
844#[derive(Clone, Debug)]
845struct PrefixStrategy {
846    matcher: AhoCorasick,
847    map: Vec<usize>,
848    longest: usize,
849}
850
851impl PrefixStrategy {
852    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
853        let path = candidate.path_prefix(self.longest);
854        for m in self.matcher.find_overlapping_iter(path) {
855            if m.start() == 0 {
856                return true;
857            }
858        }
859        false
860    }
861
862    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
863        let path = candidate.path_prefix(self.longest);
864        let mut count = 0;
865        // If all the prefixes match, we should get exactly one match for each
866        // prefix at the beginning.
867        for m in self.matcher.find_overlapping_iter(path) {
868            if m.start() == 0 {
869                count += 1;
870            }
871        }
872        count == self.map.len()
873    }
874
875    fn matches_into(
876        &self,
877        candidate: &Candidate<'_>,
878        matches: &mut Vec<usize>,
879    ) {
880        let path = candidate.path_prefix(self.longest);
881        for m in self.matcher.find_overlapping_iter(path) {
882            if m.start() == 0 {
883                matches.push(self.map[m.pattern()]);
884            }
885        }
886    }
887}
888
889#[derive(Clone, Debug)]
890struct SuffixStrategy {
891    matcher: AhoCorasick,
892    map: Vec<usize>,
893    longest: usize,
894}
895
896impl SuffixStrategy {
897    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
898        let path = candidate.path_suffix(self.longest);
899        for m in self.matcher.find_overlapping_iter(path) {
900            if m.end() == path.len() {
901                return true;
902            }
903        }
904        false
905    }
906
907    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
908        let path = candidate.path_suffix(self.longest);
909        let mut count = 0;
910        // If all the suffixes match, we should get exactly one match
911        // for each suffix at the end.
912        for m in self.matcher.find_overlapping_iter(path) {
913            if m.end() == path.len() {
914                count += 1;
915            }
916        }
917        count == self.map.len()
918    }
919
920    fn matches_into(
921        &self,
922        candidate: &Candidate<'_>,
923        matches: &mut Vec<usize>,
924    ) {
925        let path = candidate.path_suffix(self.longest);
926        for m in self.matcher.find_overlapping_iter(path) {
927            if m.end() == path.len() {
928                matches.push(self.map[m.pattern()]);
929            }
930        }
931    }
932}
933
934#[derive(Clone, Debug)]
935struct RequiredExtensionStrategy(fnv::HashMap<Vec<u8>, Vec<(usize, Regex)>>);
936
937impl RequiredExtensionStrategy {
938    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
939        if candidate.ext.is_empty() {
940            return false;
941        }
942        match self.0.get(candidate.ext.as_bytes()) {
943            None => false,
944            Some(regexes) => {
945                for &(_, ref re) in regexes {
946                    if re.is_match(candidate.path.as_bytes()) {
947                        return true;
948                    }
949                }
950                false
951            }
952        }
953    }
954
955    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
956        if self.0.len() != 1 || candidate.ext.is_empty() {
957            return false;
958        }
959        if let Some(regexes) = self.0.get(candidate.ext.as_bytes()) {
960            for &(_, ref re) in regexes {
961                if !re.is_match(candidate.path.as_bytes()) {
962                    return false;
963                }
964            }
965            true
966        } else {
967            false
968        }
969    }
970
971    #[inline(never)]
972    fn matches_into(
973        &self,
974        candidate: &Candidate<'_>,
975        matches: &mut Vec<usize>,
976    ) {
977        if candidate.ext.is_empty() {
978            return;
979        }
980        if let Some(regexes) = self.0.get(candidate.ext.as_bytes()) {
981            for &(global_index, ref re) in regexes {
982                if re.is_match(candidate.path.as_bytes()) {
983                    matches.push(global_index);
984                }
985            }
986        }
987    }
988}
989
990#[derive(Clone, Debug)]
991struct RegexSetStrategy {
992    matcher: Regex,
993    map: Vec<usize>,
994    basename: bool,
995    // We use a pool of PatternSets to hopefully allocating a fresh one on each
996    // call.
997    //
998    // TODO: In the next semver breaking release, we should drop this pool and
999    // expose an opaque type that wraps PatternSet. Then callers can provide
1000    // it to `matches_into` directly. Callers might still want to use a pool
1001    // or similar to amortize allocation, but that matches the status quo and
1002    // absolves us of needing to do it here.
1003    patset: Arc<Pool<PatternSet, PatternSetPoolFn>>,
1004}
1005
1006type PatternSetPoolFn =
1007    Box<dyn Fn() -> PatternSet + Send + Sync + UnwindSafe + RefUnwindSafe>;
1008
1009impl RegexSetStrategy {
1010    /// Returns the part of the path matched by these regexes.
1011    fn haystack<'a>(&self, candidate: &'a Candidate<'_>) -> &'a [u8] {
1012        if self.basename {
1013            candidate.basename_for_regex()
1014        } else {
1015            &candidate.path
1016        }
1017    }
1018
1019    fn is_match(&self, candidate: &Candidate<'_>) -> bool {
1020        self.matcher.is_match(self.haystack(candidate))
1021    }
1022
1023    fn find_matches(
1024        &self,
1025        candidate: &Candidate<'_>,
1026    ) -> PoolGuard<'_, PatternSet, PatternSetPoolFn> {
1027        let input = regex_automata::Input::new(self.haystack(candidate));
1028        let mut patset = self.patset.get();
1029        patset.clear();
1030        self.matcher.which_overlapping_matches(&input, &mut patset);
1031        patset
1032    }
1033
1034    fn matches_all(&self, candidate: &Candidate<'_>) -> bool {
1035        let patset = self.find_matches(candidate);
1036        patset.is_full()
1037    }
1038
1039    fn matches_into(
1040        &self,
1041        candidate: &Candidate<'_>,
1042        matches: &mut Vec<usize>,
1043    ) {
1044        let patset = self.find_matches(candidate);
1045        for i in patset.iter() {
1046            matches.push(self.map[i]);
1047        }
1048        PoolGuard::put(patset);
1049    }
1050}
1051
1052#[derive(Clone, Debug)]
1053struct MultiStrategyBuilder {
1054    literals: Vec<String>,
1055    map: Vec<usize>,
1056    longest: usize,
1057}
1058
1059impl MultiStrategyBuilder {
1060    fn new() -> MultiStrategyBuilder {
1061        MultiStrategyBuilder { literals: vec![], map: vec![], longest: 0 }
1062    }
1063
1064    fn add(&mut self, global_index: usize, literal: String) {
1065        if literal.len() > self.longest {
1066            self.longest = literal.len();
1067        }
1068        self.map.push(global_index);
1069        self.literals.push(literal);
1070    }
1071
1072    fn prefix(self) -> PrefixStrategy {
1073        PrefixStrategy {
1074            matcher: AhoCorasick::new(&self.literals).unwrap(),
1075            map: self.map,
1076            longest: self.longest,
1077        }
1078    }
1079
1080    fn suffix(self) -> SuffixStrategy {
1081        SuffixStrategy {
1082            matcher: AhoCorasick::new(&self.literals).unwrap(),
1083            map: self.map,
1084            longest: self.longest,
1085        }
1086    }
1087
1088    fn regex_set(self) -> Result<RegexSetStrategy, Error> {
1089        let matcher = new_regex_set(self.literals)?;
1090        let pattern_len = matcher.pattern_len();
1091        let create: PatternSetPoolFn =
1092            Box::new(move || PatternSet::new(pattern_len));
1093        Ok(RegexSetStrategy {
1094            matcher,
1095            map: self.map,
1096            basename: false,
1097            patset: Arc::new(Pool::new(create)),
1098        })
1099    }
1100
1101    fn is_empty(&self) -> bool {
1102        self.literals.is_empty()
1103    }
1104}
1105
1106#[derive(Clone, Debug)]
1107struct RequiredExtensionStrategyBuilder(
1108    fnv::HashMap<Vec<u8>, Vec<(usize, String)>>,
1109);
1110
1111impl RequiredExtensionStrategyBuilder {
1112    fn new() -> RequiredExtensionStrategyBuilder {
1113        RequiredExtensionStrategyBuilder(fnv::HashMap::default())
1114    }
1115
1116    fn add(&mut self, global_index: usize, ext: String, regex: String) {
1117        self.0
1118            .entry(ext.into_bytes())
1119            .or_insert(vec![])
1120            .push((global_index, regex));
1121    }
1122
1123    fn build(self) -> Result<RequiredExtensionStrategy, Error> {
1124        let mut exts = fnv::HashMap::default();
1125        for (ext, regexes) in self.0.into_iter() {
1126            exts.insert(ext.clone(), vec![]);
1127            for (global_index, regex) in regexes {
1128                let compiled = new_regex(&regex)?;
1129                exts.get_mut(&ext).unwrap().push((global_index, compiled));
1130            }
1131        }
1132        Ok(RequiredExtensionStrategy(exts))
1133    }
1134}
1135
1136/// Escape meta-characters within the given glob pattern.
1137///
1138/// The escaping works by surrounding meta-characters with brackets. For
1139/// example, `*` becomes `[*]`.
1140///
1141/// # Example
1142///
1143/// ```
1144/// use globset::escape;
1145///
1146/// assert_eq!(escape("foo*bar"), "foo[*]bar");
1147/// assert_eq!(escape("foo?bar"), "foo[?]bar");
1148/// assert_eq!(escape("foo[bar"), "foo[[]bar");
1149/// assert_eq!(escape("foo]bar"), "foo[]]bar");
1150/// assert_eq!(escape("foo{bar"), "foo[{]bar");
1151/// assert_eq!(escape("foo}bar"), "foo[}]bar");
1152/// ```
1153pub fn escape(s: &str) -> String {
1154    let mut escaped = String::with_capacity(s.len());
1155    for c in s.chars() {
1156        match c {
1157            // note that ! does not need escaping because it is only special
1158            // inside brackets
1159            '?' | '*' | '[' | ']' | '{' | '}' => {
1160                escaped.push('[');
1161                escaped.push(c);
1162                escaped.push(']');
1163            }
1164            c => {
1165                escaped.push(c);
1166            }
1167        }
1168    }
1169    escaped
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use crate::glob::{Glob, GlobBuilder};
1175
1176    use super::{GlobSet, GlobSetBuilder};
1177
1178    fn build_glob_set(globs: &[&str]) -> GlobSet {
1179        let mut builder = GlobSetBuilder::new();
1180        for glob in globs {
1181            builder.add(Glob::new(glob).unwrap());
1182        }
1183        builder.build().unwrap()
1184    }
1185
1186    #[test]
1187    fn debug_impl_is_concise() {
1188        let set = build_glob_set(&["src/**/*.rs", "*.c"]);
1189        assert_eq!(
1190            format!("{:?}", set),
1191            r#"GlobSet([Glob("src/**/*.rs"), Glob("*.c")])"#
1192        );
1193        assert_eq!(format!("{:?}", GlobSet::empty()), "GlobSet([])");
1194    }
1195
1196    #[test]
1197    fn set_works() {
1198        let set = build_glob_set(&["src/**/*.rs", "*.c", "src/lib.rs"]);
1199
1200        assert!(set.is_match("foo.c"));
1201        assert!(set.is_match("src/foo.c"));
1202        assert!(!set.is_match("foo.rs"));
1203        assert!(!set.is_match("tests/foo.rs"));
1204        assert!(set.is_match("src/foo.rs"));
1205        assert!(set.is_match("src/grep/src/main.rs"));
1206
1207        assert!(!set.matches_all("src/lib.rs"));
1208        assert!(!set.matches_all("src/a/b.c"));
1209
1210        let matches = set.matches("src/lib.rs");
1211        assert_eq!(2, matches.len());
1212        assert_eq!(0, matches[0]);
1213        assert_eq!(2, matches[1]);
1214    }
1215
1216    #[test]
1217    fn empty_set_works() {
1218        let set = GlobSetBuilder::new().build().unwrap();
1219        assert!(!set.is_match(""));
1220        assert!(!set.is_match("a"));
1221        assert!(set.matches_all("a"));
1222    }
1223
1224    #[test]
1225    fn matches_all_literals() {
1226        let set = build_glob_set(&["abc", "def"]);
1227
1228        assert!(!set.matches_all("abc"));
1229        assert!(!set.matches_all("def"));
1230
1231        let set = build_glob_set(&["abc"]);
1232
1233        assert!(set.matches_all("abc"));
1234    }
1235
1236    #[test]
1237    fn matches_all_basename_literals() {
1238        let set = build_glob_set(&["**/abc", "**/a.c"]);
1239
1240        assert!(!set.matches_all("foo/abc"));
1241        assert!(!set.matches_all("foo/a.c"));
1242
1243        let set = build_glob_set(&["**/a.c"]);
1244        assert!(set.matches_all("foo/a.c"));
1245    }
1246
1247    #[test]
1248    fn matches_all_extensions() {
1249        let set = build_glob_set(&["**/*.rs", "**/*.c"]);
1250
1251        assert!(!set.matches_all("foo/a.rs"));
1252        assert!(!set.matches_all("foo/a.c"));
1253
1254        let set = build_glob_set(&["**/*.rs", "*.rs"]);
1255        assert!(set.matches_all("foo/a.rs"));
1256    }
1257
1258    #[test]
1259    fn matches_all_required_extensions() {
1260        let set = build_glob_set(&["*.rs", "**/m*.rs", "a/*.rs"]);
1261
1262        assert!(set.matches_all("a/main.rs"));
1263
1264        assert!(!set.matches_all("main.rs"));
1265        assert!(!set.matches_all("a/lib.rs"));
1266
1267        let set = build_glob_set(&["x/m*.a", "y/n*.b"]);
1268
1269        for (path, index) in [("x/mt.a", 0), ("y/nz.b", 1)] {
1270            assert_eq!(set.matches(path), vec![index]);
1271            assert!(!set.matches_all(path));
1272            assert!(!set.matches_all_candidate(&crate::Candidate::new(path)));
1273        }
1274    }
1275
1276    #[test]
1277    fn matches_all_prefix() {
1278        let set = build_glob_set(&["a*", "ab*", "ab/c*"]);
1279
1280        assert!(set.matches_all("ab/c/def"));
1281        assert!(set.matches_all("ab/cd"));
1282
1283        assert!(!set.matches_all("abc"));
1284        assert!(!set.matches_all("ab/x"));
1285        assert!(!set.matches_all("a"));
1286    }
1287
1288    #[test]
1289    fn matches_all_suffix() {
1290        let set = build_glob_set(&["*.rs", "*s", "*/main.rs"]);
1291
1292        assert!(set.matches_all("a/b/c/main.rs"));
1293
1294        assert!(!set.matches_all("foo.rs"));
1295        assert!(!set.matches_all("as"));
1296    }
1297
1298    #[test]
1299    fn matches_all_regex() {
1300        let set = GlobSet::new(&[
1301            GlobBuilder::new("c*").case_insensitive(true).build().unwrap(),
1302            Glob::new("*{rs,c}").unwrap(),
1303        ])
1304        .unwrap();
1305
1306        assert!(set.matches_all("c/main.rs"));
1307        assert!(set.matches_all("C/main.c"));
1308
1309        assert!(!set.matches_all("Ca"));
1310        assert!(!set.matches_all("foo.c"));
1311    }
1312
1313    #[test]
1314    fn basename_regex_with_path_rules() {
1315        let globs: Vec<_> = ["**/.venv*", "**/*.py[cod]", "src/*"]
1316            .iter()
1317            .map(|pattern| {
1318                GlobBuilder::new(pattern)
1319                    .literal_separator(true)
1320                    .build()
1321                    .unwrap()
1322            })
1323            .collect();
1324        let set = GlobSet::new(globs).unwrap();
1325        assert_eq!(set.matches("src/module.pyc"), vec![1, 2]);
1326        assert_eq!(set.matches("src/nested/module.pyc"), vec![1]);
1327        assert_eq!(set.matches("src/.venv-new"), vec![0, 2]);
1328        assert!(set.matches_all("src/.venv.pyc"));
1329        assert!(!set.matches_all("src/nested/.venv.pyc"));
1330    }
1331
1332    #[test]
1333    fn basename_regex_parent_component() {
1334        let set = GlobSet::new([
1335            GlobBuilder::new("**/.*").literal_separator(true).build().unwrap(),
1336            Glob::new("**/[.][.]").unwrap(),
1337        ])
1338        .unwrap();
1339        for path in ["..", "foo/..", "foo/bar/.."] {
1340            assert!(set.is_match(path), "{path}");
1341            assert!(set.matches_all(path), "{path}");
1342            assert_eq!(set.matches(path), vec![0, 1], "{path}");
1343        }
1344        assert!(!set.matches_all("foo/."));
1345        assert!(!set.matches_all("foo/a.."));
1346    }
1347
1348    #[test]
1349    fn default_set_is_empty_works() {
1350        let set: GlobSet = Default::default();
1351        assert!(!set.is_match(""));
1352        assert!(!set.is_match("a"));
1353    }
1354
1355    #[test]
1356    fn escape() {
1357        use super::escape;
1358        assert_eq!("foo", escape("foo"));
1359        assert_eq!("foo[*]", escape("foo*"));
1360        assert_eq!("[[][]]", escape("[]"));
1361        assert_eq!("[*][?]", escape("*?"));
1362        assert_eq!("src/[*][*]/[*].rs", escape("src/**/*.rs"));
1363        assert_eq!("bar[[]ab[]]baz", escape("bar[ab]baz"));
1364        assert_eq!("bar[[]!![]]!baz", escape("bar[!!]!baz"));
1365    }
1366
1367    // This tests that regex matching doesn't "remember" the results of
1368    // previous searches. That is, if any memory is reused from a previous
1369    // search, then it should be cleared first.
1370    #[test]
1371    fn set_does_not_remember() {
1372        let mut builder = GlobSetBuilder::new();
1373        builder.add(Glob::new("*foo*").unwrap());
1374        builder.add(Glob::new("*bar*").unwrap());
1375        builder.add(Glob::new("*quux*").unwrap());
1376        let set = builder.build().unwrap();
1377
1378        let matches = set.matches("ZfooZquuxZ");
1379        assert_eq!(2, matches.len());
1380        assert_eq!(0, matches[0]);
1381        assert_eq!(2, matches[1]);
1382
1383        let matches = set.matches("nada");
1384        assert_eq!(0, matches.len());
1385    }
1386
1387    #[test]
1388    fn debug() {
1389        let mut builder = GlobSetBuilder::new();
1390        builder.add(Glob::new("*foo*").unwrap());
1391        builder.add(Glob::new("*bar*").unwrap());
1392        builder.add(Glob::new("*quux*").unwrap());
1393        assert_eq!(
1394            format!("{builder:?}"),
1395            "GlobSetBuilder { pats: [Glob(\"*foo*\"), Glob(\"*bar*\"), Glob(\"*quux*\")] }",
1396        );
1397    }
1398    #[test]
1399    fn literal_length_filter() {
1400        let lengths = [0, 1, 63, 64, 65, 127, 128, 129];
1401        let mut patterns: Vec<_> =
1402            lengths.iter().map(|&len| "a".repeat(len)).collect();
1403        patterns.extend(["é.py".to_owned(), r"foo\*bar".to_owned()]);
1404        let set = GlobSet::new(patterns.iter().map(|pattern| {
1405            GlobBuilder::new(pattern).backslash_escape(true).build().unwrap()
1406        }))
1407        .unwrap();
1408        for (i, &len) in lengths.iter().enumerate() {
1409            let path = "a".repeat(len);
1410            assert!(set.is_match(&path));
1411            assert_eq!(set.matches(&path), vec![i]);
1412        }
1413        assert_eq!(set.matches("é.py"), vec![8]);
1414        assert_eq!(set.matches("foo*bar"), vec![9]);
1415        for len in [2, 62, 66, 126, 130] {
1416            assert!(!set.is_match("a".repeat(len)));
1417        }
1418        let literal = "a".repeat(65);
1419        let duplicates = GlobSet::new([
1420            Glob::new(&literal).unwrap(),
1421            Glob::new(&literal).unwrap(),
1422        ])
1423        .unwrap();
1424        assert!(duplicates.matches_all(&literal));
1425        assert_eq!(duplicates.matches(&literal), vec![0, 1]);
1426        assert!(!duplicates.is_match("a"));
1427        assert!(!duplicates.matches_all("a"));
1428        assert!(!duplicates.is_match("b".repeat(65)));
1429    }
1430
1431    #[test]
1432    fn basename_literal_length_filter() {
1433        let lengths = [1, 63, 64, 65, 127, 128, 129];
1434        let mut patterns: Vec<_> = lengths
1435            .iter()
1436            .map(|&len| format!("**/{}", "a".repeat(len)))
1437            .collect();
1438        patterns.extend(["**/é.py".to_owned(), r"**/foo\*bar".to_owned()]);
1439        let set = GlobSet::new(patterns.iter().map(|pattern| {
1440            GlobBuilder::new(pattern).backslash_escape(true).build().unwrap()
1441        }))
1442        .unwrap();
1443        for (i, &len) in lengths.iter().enumerate() {
1444            let path = format!("parent/{}", "a".repeat(len));
1445            assert!(set.is_match(&path));
1446            assert_eq!(set.matches(&path), vec![i]);
1447        }
1448        assert_eq!(set.matches("parent/é.py"), vec![7]);
1449        assert_eq!(set.matches("parent/foo*bar"), vec![8]);
1450        let literal = "a".repeat(65);
1451        let glob = Glob::new(&format!("**/{literal}")).unwrap();
1452        let duplicates = GlobSet::new([&glob, &glob]).unwrap();
1453        let path = format!("parent/{literal}");
1454        assert!(duplicates.matches_all(&path));
1455        assert_eq!(duplicates.matches(&path), vec![0, 1]);
1456        assert!(!duplicates.is_match("parent/a"));
1457        assert!(!duplicates.is_match(format!("parent/{}", "b".repeat(65))));
1458        let parent = GlobSet::new([Glob::new("**/..").unwrap()]).unwrap();
1459        assert!(!parent.is_match("parent/.."));
1460        assert!(!parent.matches_all("parent/.."));
1461    }
1462}