Skip to main content

nu_glob/
lib.rs

1// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Copyright 2022 The Nushell Project Developers.
6//
7// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10// option. This file may not be copied, modified, or distributed
11// except according to those terms.
12
13//! Support for matching file paths against Unix shell style patterns.
14//!
15//! The `glob` and `glob_with` functions allow querying the filesystem for all
16//! files that match a particular pattern (similar to the libc `glob` function).
17//! The methods on the `Pattern` type provide functionality for checking if
18//! individual paths match a particular pattern (similar to the libc `fnmatch`
19//! function).
20//!
21//! For consistency across platforms, and for Windows support, this module
22//! is implemented entirely in Rust rather than deferring to the libc
23//! `glob`/`fnmatch` functions.
24//!
25//! # Examples
26//!
27//! To print all jpg files in `/media/` and all of its subdirectories.
28//!
29//! ```rust,no_run
30//! use nu_glob::{glob, Uninterruptible};
31//!
32//! for entry in glob("/media/**/*.jpg", Uninterruptible).expect("Failed to read glob pattern") {
33//!     match entry {
34//!         Ok(path) => println!("{:?}", path.display()),
35//!         Err(e) => println!("{:?}", e),
36//!     }
37//! }
38//! ```
39//!
40//! To print all files containing the letter "a", case insensitive, in a `local`
41//! directory relative to the current working directory. This ignores errors
42//! instead of printing them.
43//!
44//! ```rust,no_run
45//! use nu_glob::{glob_with, MatchOptions, Uninterruptible};
46//!
47//! let options = MatchOptions {
48//!     case_sensitive: false,
49//!     require_literal_separator: false,
50//!     require_literal_leading_dot: false,
51//!     recursive_match_hidden_dir: true,
52//! };
53//! for entry in glob_with("local/*a*", options, Uninterruptible).unwrap() {
54//!     if let Ok(path) = entry {
55//!         println!("{:?}", path.display())
56//!     }
57//! }
58//! ```
59
60#![doc(
61    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
62    html_favicon_url = "https://www.rust-lang.org/favicon.ico",
63    html_root_url = "https://docs.rs/glob/0.3.1"
64)]
65#![deny(missing_docs)]
66
67pub mod dc_glob;
68
69#[cfg(test)]
70#[macro_use]
71extern crate doc_comment;
72
73#[cfg(test)]
74doctest!("../README.md");
75
76use std::cmp;
77use std::cmp::Ordering;
78use std::error::Error;
79use std::fmt;
80use std::fs;
81use std::io;
82use std::path::{self, Component, Path, PathBuf};
83use std::str::FromStr;
84
85use CharSpecifier::{CharRange, SingleChar};
86use MatchResult::{EntirePatternDoesntMatch, Match, SubPatternDoesntMatch};
87use PatternToken::AnyExcept;
88use PatternToken::{AnyChar, AnyRecursiveSequence, AnySequence, AnyWithin, Char};
89
90/// A trait for types that can be periodically polled to check whether to cancel an operation.
91pub trait Interruptible {
92    /// Returns whether the current operation should be cancelled.
93    fn interrupted(&self) -> bool;
94}
95
96impl<I: Interruptible> Interruptible for &I {
97    #[inline]
98    fn interrupted(&self) -> bool {
99        (*self).interrupted()
100    }
101}
102
103/// A no-op implementor of [`Interruptible`] that always returns `false` for [`interrupted`](Interruptible::interrupted).
104pub struct Uninterruptible;
105
106impl Interruptible for Uninterruptible {
107    #[inline]
108    fn interrupted(&self) -> bool {
109        false
110    }
111}
112
113/// An iterator that yields `Path`s from the filesystem that match a particular
114/// pattern.
115///
116/// Note that it yields `GlobResult` in order to report any `IoErrors` that may
117/// arise during iteration. If a directory matches but is unreadable,
118/// thereby preventing its contents from being checked for matches, a
119/// `GlobError` is returned to express this.
120///
121/// See the `glob` function for more details.
122#[derive(Debug)]
123pub struct Paths<I = Uninterruptible> {
124    dir_patterns: Vec<Pattern>,
125    require_dir: bool,
126    options: MatchOptions,
127    todo: Vec<Result<(PathBuf, usize), GlobError>>,
128    scope: Option<PathBuf>,
129    interrupt: I,
130}
131
132impl Paths<Uninterruptible> {
133    /// An iterator representing a single path.
134    pub fn single(path: &Path, relative_to: &Path) -> Self {
135        Paths {
136            dir_patterns: vec![Pattern::new("*").expect("hard coded pattern")],
137            require_dir: false,
138            options: MatchOptions::default(),
139            todo: vec![Ok((path.to_path_buf(), 0))],
140            scope: Some(relative_to.into()),
141            interrupt: Uninterruptible,
142        }
143    }
144}
145
146/// Return an iterator that produces all the `Path`s that match the given
147/// pattern using default match options, which may be absolute or relative to
148/// the current working directory.
149///
150/// This may return an error if the pattern is invalid.
151///
152/// This method uses the default match options and is equivalent to calling
153/// `glob_with(pattern, MatchOptions::default())`. Use `glob_with` directly if you
154/// want to use non-default match options.
155///
156/// When iterating, each result is a `GlobResult` which expresses the
157/// possibility that there was an `IoError` when attempting to read the contents
158/// of the matched path. In other words, each item returned by the iterator
159/// will either be an `Ok(Path)` if the path matched, or an `Err(GlobError)` if
160/// the path (partially) matched _but_ its contents could not be read in order
161/// to determine if its contents matched.
162///
163/// See the `Paths` documentation for more information.
164///
165/// # Examples
166///
167/// Consider a directory `/media/pictures` containing only the files
168/// `kittens.jpg`, `puppies.jpg` and `hamsters.gif`:
169///
170/// ```rust,no_run
171/// use nu_glob::{glob, Uninterruptible};
172///
173/// for entry in glob("/media/pictures/*.jpg", Uninterruptible).unwrap() {
174///     match entry {
175///         Ok(path) => println!("{:?}", path.display()),
176///
177///         // if the path matched but was unreadable,
178///         // thereby preventing its contents from matching
179///         Err(e) => println!("{:?}", e),
180///     }
181/// }
182/// ```
183///
184/// The above code will print:
185///
186/// ```ignore
187/// /media/pictures/kittens.jpg
188/// /media/pictures/puppies.jpg
189/// ```
190///
191/// If you want to ignore unreadable paths, you can use something like
192/// `filter_map`:
193///
194/// ```rust
195/// use nu_glob::{glob, Uninterruptible};
196/// use std::result::Result;
197///
198/// for path in glob("/media/pictures/*.jpg", Uninterruptible).unwrap().filter_map(Result::ok) {
199///     println!("{}", path.display());
200/// }
201/// ```
202/// Paths are yielded in alphabetical order.
203pub fn glob<I: Interruptible>(pattern: &str, interrupt: I) -> Result<Paths<I>, PatternError> {
204    glob_with(pattern, MatchOptions::default(), interrupt)
205}
206
207/// Return an iterator that produces all the `Path`s that match the given
208/// pattern using the specified match options, which may be absolute or relative
209/// to the current working directory.
210///
211/// This may return an error if the pattern is invalid.
212///
213/// This function accepts Unix shell style patterns as described by
214/// `Pattern::new(..)`.  The options given are passed through unchanged to
215/// `Pattern::matches_with(..)` with the exception that
216/// `require_literal_separator` is always set to `true` regardless of the value
217/// passed to this function.
218///
219/// Paths are yielded in alphabetical order.
220pub fn glob_with<I: Interruptible>(
221    pattern: &str,
222    options: MatchOptions,
223    interrupt: I,
224) -> Result<Paths<I>, PatternError> {
225    #[cfg(windows)]
226    fn check_windows_verbatim(p: &Path) -> bool {
227        match p.components().next() {
228            Some(Component::Prefix(ref p)) => {
229                // Allow VerbatimDisk paths. std canonicalize() generates them, and they work fine
230                p.kind().is_verbatim() && !matches!(p.kind(), std::path::Prefix::VerbatimDisk(_))
231            }
232            _ => false,
233        }
234    }
235    #[cfg(not(windows))]
236    fn check_windows_verbatim(_: &Path) -> bool {
237        false
238    }
239
240    #[cfg(windows)]
241    fn to_scope(p: &Path) -> PathBuf {
242        // FIXME handle volume relative paths here
243        p.to_path_buf()
244    }
245    #[cfg(not(windows))]
246    fn to_scope(p: &Path) -> PathBuf {
247        p.to_path_buf()
248    }
249
250    // make sure that the pattern is valid first, else early return with error
251    Pattern::new(pattern)?;
252
253    let mut components = Path::new(pattern).components().peekable();
254    while let Some(&Component::Prefix(..)) | Some(&Component::RootDir) = components.peek() {
255        components.next();
256    }
257
258    let rest = components.map(|s| s.as_os_str()).collect::<PathBuf>();
259    let normalized_pattern = Path::new(pattern).iter().collect::<PathBuf>();
260    let root_len = normalized_pattern
261        .to_str()
262        .expect("internal error: expected string")
263        .len()
264        - rest
265            .to_str()
266            .expect("internal error: expected string")
267            .len();
268    let root = if root_len > 0 {
269        Some(Path::new(&pattern[..root_len]))
270    } else {
271        None
272    };
273
274    if root_len > 0
275        && check_windows_verbatim(root.expect("internal error: already checked for len > 0"))
276    {
277        // FIXME: How do we want to handle verbatim paths? I'm inclined to
278        // return nothing, since we can't very well find all UNC shares with a
279        // 1-letter server name.
280        return Ok(Paths {
281            dir_patterns: Vec::new(),
282            require_dir: false,
283            options,
284            todo: Vec::new(),
285            scope: None,
286            interrupt,
287        });
288    }
289
290    let scope = root.map_or_else(|| PathBuf::from("."), to_scope);
291
292    let mut dir_patterns = Vec::new();
293    let components =
294        pattern[cmp::min(root_len, pattern.len())..].split_terminator(path::is_separator);
295
296    for component in components {
297        dir_patterns.push(Pattern::new(component)?);
298    }
299
300    if root_len == pattern.len() {
301        dir_patterns.push(Pattern {
302            original: "".to_string(),
303            tokens: Vec::new(),
304            is_recursive: false,
305        });
306    }
307
308    let last_is_separator = pattern.chars().next_back().map(path::is_separator);
309    let require_dir = last_is_separator == Some(true);
310    let todo = Vec::new();
311
312    Ok(Paths {
313        dir_patterns,
314        require_dir,
315        options,
316        todo,
317        scope: Some(scope),
318        interrupt,
319    })
320}
321
322/// Return an iterator that produces all the `Path`s that match the given
323/// pattern relative to a specified parent directory and using specified match options.
324/// Paths may be absolute or relative to the current working directory.
325///
326/// This is provided primarily for testability, so multithreaded test runners can
327/// test pattern matches in different test directories at the same time without
328/// having to append the parent to the pattern under test.
329pub fn glob_with_parent<I: Interruptible>(
330    pattern: &str,
331    options: MatchOptions,
332    parent: &Path,
333    interrupt: I,
334) -> Result<Paths<I>, PatternError> {
335    match glob_with(pattern, options, interrupt) {
336        Ok(mut p) => {
337            p.scope = match p.scope {
338                None => Some(parent.to_path_buf()),
339                Some(s) if &s.to_string_lossy() == "." => Some(parent.to_path_buf()),
340                Some(s) => Some(s),
341            };
342            Ok(p)
343        }
344        Err(e) => Err(e),
345    }
346}
347
348const GLOB_CHARS: &[char] = &['*', '?', '['];
349
350/// Returns true if the given pattern is a glob, false if it's merely text to be
351/// matched exactly.
352///
353/// ```rust
354/// assert!(nu_glob::is_glob("foo/*"));
355/// assert!(nu_glob::is_glob("foo/**/bar"));
356/// assert!(nu_glob::is_glob("foo?"));
357/// assert!(nu_glob::is_glob("foo[A]"));
358///
359/// assert!(!nu_glob::is_glob("foo"));
360/// // nu_glob will ignore an unmatched ']'
361/// assert!(!nu_glob::is_glob("foo]"));
362/// // nu_glob doesn't expand {}
363/// assert!(!nu_glob::is_glob("foo.{txt,png}"));
364/// ```
365pub fn is_glob(pattern: &str) -> bool {
366    pattern.contains(GLOB_CHARS)
367}
368
369/// Returns true if the given pattern contains glob metacharacters, selecting
370/// the active backend via the `dc-glob` experimental option.
371pub fn is_glob_with_backend(pattern: &str) -> bool {
372    if nu_experimental::DC_GLOB.get() {
373        dc_glob::is_glob(pattern)
374    } else {
375        is_glob(pattern)
376    }
377}
378
379/// Returns true if a path component of a glob pattern has pattern syntax, so the walk has to
380/// match it rather than start below it, selecting the active backend via the `dc-glob`
381/// experimental option.
382pub fn is_glob_component_with_backend(component: &str) -> bool {
383    if nu_experimental::DC_GLOB.get() {
384        dc_glob::is_glob_component(component)
385    } else {
386        is_glob(component)
387    }
388}
389
390/// Escapes glob metacharacters for literal path matching, selecting the active
391/// backend via the `dc-glob` experimental option.
392pub fn escape_with_backend(pattern: &str) -> String {
393    if nu_experimental::DC_GLOB.get() {
394        dc_glob::escape(pattern)
395    } else {
396        Pattern::escape(pattern)
397    }
398}
399
400/// A glob iteration error.
401///
402/// This is typically returned when a particular path cannot be read
403/// to determine if its contents match the glob pattern. This is possible
404/// if the program lacks the appropriate permissions, for example.
405#[derive(Debug)]
406pub struct GlobError {
407    path: PathBuf,
408    error: io::Error,
409}
410
411impl GlobError {
412    /// The Path that the error corresponds to.
413    pub fn path(&self) -> &Path {
414        &self.path
415    }
416
417    /// The error in question.
418    pub fn error(&self) -> &io::Error {
419        &self.error
420    }
421
422    /// Consumes self, returning the _raw_ underlying `io::Error`
423    pub fn into_error(self) -> io::Error {
424        self.error
425    }
426}
427
428impl Error for GlobError {
429    #[allow(deprecated)]
430    fn description(&self) -> &str {
431        self.error.description()
432    }
433
434    fn cause(&self) -> Option<&dyn Error> {
435        Some(&self.error)
436    }
437}
438
439impl fmt::Display for GlobError {
440    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441        write!(
442            f,
443            "attempting to read `{}` resulted in an error: {}",
444            self.path.display(),
445            self.error
446        )
447    }
448}
449
450fn is_dir(p: &Path) -> bool {
451    fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false)
452}
453
454/// An alias for a glob iteration result.
455///
456/// This represents either a matched path or a glob iteration error,
457/// such as failing to read a particular directory's contents.
458pub type GlobResult = Result<PathBuf, GlobError>;
459
460impl<I: Interruptible> Iterator for Paths<I> {
461    type Item = GlobResult;
462
463    fn next(&mut self) -> Option<GlobResult> {
464        // the todo buffer hasn't been initialized yet, so it's done at this
465        // point rather than in glob() so that the errors are unified that is,
466        // failing to fill the buffer is an iteration error construction of the
467        // iterator (i.e. glob()) only fails if it fails to compile the Pattern
468        if let Some(scope) = self.scope.take()
469            && !self.dir_patterns.is_empty()
470        {
471            // Shouldn't happen, but we're using -1 as a special index.
472            assert!(self.dir_patterns.len() < !0);
473
474            // if there's one prefilled result, take it, otherwise fill the todo buffer
475            if self.todo.len() != 1 {
476                fill_todo(
477                    &mut self.todo,
478                    &self.dir_patterns,
479                    0,
480                    &scope,
481                    self.options,
482                    &self.interrupt,
483                );
484            }
485        }
486
487        loop {
488            if self.dir_patterns.is_empty() || self.todo.is_empty() {
489                return None;
490            }
491
492            let (path, mut idx) = match self
493                .todo
494                .pop()
495                .expect("internal error: already checked for non-empty")
496            {
497                Ok(pair) => pair,
498                Err(e) => return Some(Err(e)),
499            };
500
501            // idx -1: was already checked by fill_todo, maybe path was '.' or
502            // '..' that we can't match here because of normalization.
503            if idx == !0 {
504                if self.require_dir && !is_dir(&path) {
505                    continue;
506                }
507                return Some(Ok(path));
508            }
509
510            if self.dir_patterns[idx].is_recursive {
511                let mut next = idx;
512
513                // collapse consecutive recursive patterns
514                while (next + 1) < self.dir_patterns.len()
515                    && self.dir_patterns[next + 1].is_recursive
516                {
517                    next += 1;
518                }
519
520                if is_dir(&path) {
521                    // the path is a directory, check if matched according
522                    // to `hidden_dir_recursive` option.
523                    if !self.options.recursive_match_hidden_dir
524                        && path
525                            .file_name()
526                            .map(|name| name.to_string_lossy().starts_with('.'))
527                            .unwrap_or(false)
528                    {
529                        continue;
530                    }
531
532                    // push this directory's contents
533                    fill_todo(
534                        &mut self.todo,
535                        &self.dir_patterns,
536                        next,
537                        &path,
538                        self.options,
539                        &self.interrupt,
540                    );
541
542                    if next == self.dir_patterns.len() - 1 {
543                        // pattern ends in recursive pattern, so return this
544                        // directory as a result
545                        return Some(Ok(path));
546                    } else {
547                        // advanced to the next pattern for this path
548                        idx = next + 1;
549                    }
550                } else if next == self.dir_patterns.len() - 1 {
551                    // not a directory and it's the last pattern, meaning no
552                    // match
553                    continue;
554                } else {
555                    // advanced to the next pattern for this path
556                    idx = next + 1;
557                }
558            }
559
560            // not recursive, so match normally
561            if self.dir_patterns[idx].matches_with(
562                {
563                    match path.file_name().and_then(|s| s.to_str()) {
564                        // FIXME (#9639): How do we handle non-utf8 filenames?
565                        // Ignore them for now; ideally we'd still match them
566                        // against a *
567                        None => {
568                            println!("warning: get non-utf8 filename {path:?}, ignored.");
569                            continue;
570                        }
571                        Some(x) => x,
572                    }
573                },
574                self.options,
575            ) {
576                if idx == self.dir_patterns.len() - 1 {
577                    // it is not possible for a pattern to match a directory
578                    // *AND* its children so we don't need to check the
579                    // children
580
581                    if !self.require_dir || is_dir(&path) {
582                        return Some(Ok(path));
583                    }
584                } else {
585                    fill_todo(
586                        &mut self.todo,
587                        &self.dir_patterns,
588                        idx + 1,
589                        &path,
590                        self.options,
591                        &self.interrupt,
592                    );
593                }
594            }
595        }
596    }
597}
598
599/// A pattern parsing error.
600#[derive(Debug)]
601pub struct PatternError {
602    /// The approximate character index of where the error occurred.
603    pub pos: usize,
604
605    /// A message describing the error.
606    pub msg: &'static str,
607}
608
609impl Error for PatternError {
610    fn description(&self) -> &str {
611        self.msg
612    }
613}
614
615impl fmt::Display for PatternError {
616    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
617        write!(
618            f,
619            "Pattern syntax error near position {}: {}",
620            self.pos, self.msg
621        )
622    }
623}
624
625/// A compiled Unix shell style pattern.
626///
627/// - `?` matches any single character.
628///
629/// - `*` matches any (possibly empty) sequence of characters.
630///
631/// - `**` matches the current directory and arbitrary subdirectories. This
632///   sequence **must** form a single path component, so both `**a` and `b**`
633///   are invalid and will result in an error.  A sequence of more than two
634///   consecutive `*` characters is also invalid.
635///
636/// - `[...]` matches any character inside the brackets.  Character sequences
637///   can also specify ranges of characters, as ordered by Unicode, so e.g.
638///   `[0-9]` specifies any character between 0 and 9 inclusive. An unclosed
639///   bracket is invalid.
640///
641/// - `[!...]` is the negation of `[...]`, i.e. it matches any characters
642///   **not** in the brackets.
643///
644/// - The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets
645///   (e.g. `[?]`).  When a `]` occurs immediately following `[` or `[!` then it
646///   is interpreted as being part of, rather then ending, the character set, so
647///   `]` and NOT `]` can be matched by `[]]` and `[!]]` respectively.  The `-`
648///   character can be specified inside a character sequence pattern by placing
649///   it at the start or the end, e.g. `[abc-]`.
650#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
651pub struct Pattern {
652    original: String,
653    tokens: Vec<PatternToken>,
654    is_recursive: bool,
655}
656
657/// Show the original glob pattern.
658impl fmt::Display for Pattern {
659    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660        self.original.fmt(f)
661    }
662}
663
664impl FromStr for Pattern {
665    type Err = PatternError;
666
667    fn from_str(s: &str) -> Result<Self, PatternError> {
668        Self::new(s)
669    }
670}
671
672#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
673enum PatternToken {
674    Char(char),
675    AnyChar,
676    AnySequence,
677    AnyRecursiveSequence,
678    AnyWithin(Vec<CharSpecifier>),
679    AnyExcept(Vec<CharSpecifier>),
680}
681
682#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
683enum CharSpecifier {
684    SingleChar(char),
685    CharRange(char, char),
686}
687
688#[derive(Copy, Clone, PartialEq)]
689enum MatchResult {
690    Match,
691    SubPatternDoesntMatch,
692    EntirePatternDoesntMatch,
693}
694
695const ERROR_WILDCARDS: &str = "wildcards are either regular `*` or recursive `**`";
696const ERROR_RECURSIVE_WILDCARDS: &str = "recursive wildcards must form a single path \
697                                         component";
698const ERROR_INVALID_RANGE: &str = "invalid range pattern";
699
700impl Pattern {
701    /// This function compiles Unix shell style patterns.
702    ///
703    /// An invalid glob pattern will yield a `PatternError`.
704    pub fn new(pattern: &str) -> Result<Self, PatternError> {
705        let chars = pattern.chars().collect::<Vec<_>>();
706        let mut tokens = Vec::new();
707        let mut is_recursive = false;
708        let mut i = 0;
709
710        while i < chars.len() {
711            match chars[i] {
712                '?' => {
713                    tokens.push(AnyChar);
714                    i += 1;
715                }
716                '*' => {
717                    let old = i;
718
719                    while i < chars.len() && chars[i] == '*' {
720                        i += 1;
721                    }
722
723                    let count = i - old;
724
725                    match count.cmp(&2) {
726                        Ordering::Greater => {
727                            return Err(PatternError {
728                                pos: old + 2,
729                                msg: ERROR_WILDCARDS,
730                            });
731                        }
732                        Ordering::Equal => {
733                            // ** can only be an entire path component
734                            // i.e. a/**/b is valid, but a**/b or a/**b is not
735                            // invalid matches are treated literally
736                            let is_valid = if i == 2 || path::is_separator(chars[i - count - 1]) {
737                                // it ends in a '/'
738                                if i < chars.len() && path::is_separator(chars[i]) {
739                                    i += 1;
740                                    true
741                                // or the pattern ends here
742                                // this enables the existing globbing mechanism
743                                } else if i == chars.len() {
744                                    true
745                                // `**` ends in non-separator
746                                } else {
747                                    return Err(PatternError {
748                                        pos: i,
749                                        msg: ERROR_RECURSIVE_WILDCARDS,
750                                    });
751                                }
752                            // `**` begins with non-separator
753                            } else {
754                                return Err(PatternError {
755                                    pos: old - 1,
756                                    msg: ERROR_RECURSIVE_WILDCARDS,
757                                });
758                            };
759
760                            if is_valid {
761                                // collapse consecutive AnyRecursiveSequence to a
762                                // single one
763
764                                let tokens_len = tokens.len();
765
766                                if !(tokens_len > 1
767                                    && tokens[tokens_len - 1] == AnyRecursiveSequence)
768                                {
769                                    is_recursive = true;
770                                    tokens.push(AnyRecursiveSequence);
771                                }
772                            }
773                        }
774                        Ordering::Less => {
775                            tokens.push(AnySequence);
776                        }
777                    }
778                }
779                '[' => {
780                    if i + 4 <= chars.len() && chars[i + 1] == '!' {
781                        match chars[i + 3..].iter().position(|x| *x == ']') {
782                            None => (),
783                            Some(j) => {
784                                let chars = &chars[i + 2..i + 3 + j];
785                                let cs = parse_char_specifiers(chars);
786                                tokens.push(AnyExcept(cs));
787                                i += j + 4;
788                                continue;
789                            }
790                        }
791                    } else if i + 3 <= chars.len() && chars[i + 1] != '!' {
792                        match chars[i + 2..].iter().position(|x| *x == ']') {
793                            None => (),
794                            Some(j) => {
795                                let cs = parse_char_specifiers(&chars[i + 1..i + 2 + j]);
796                                tokens.push(AnyWithin(cs));
797                                i += j + 3;
798                                continue;
799                            }
800                        }
801                    }
802
803                    // if we get here then this is not a valid range pattern
804                    return Err(PatternError {
805                        pos: i,
806                        msg: ERROR_INVALID_RANGE,
807                    });
808                }
809                c => {
810                    tokens.push(Char(c));
811                    i += 1;
812                }
813            }
814        }
815
816        Ok(Self {
817            tokens,
818            original: pattern.to_string(),
819            is_recursive,
820        })
821    }
822
823    /// Escape metacharacters within the given string by surrounding them in
824    /// brackets. The resulting string will, when compiled into a `Pattern`,
825    /// match the input string and nothing else.
826    pub fn escape(s: &str) -> String {
827        let mut escaped = String::new();
828        for c in s.chars() {
829            match c {
830                // note that ! does not need escaping because it is only special
831                // inside brackets
832                '?' | '*' | '[' | ']' => {
833                    escaped.push('[');
834                    escaped.push(c);
835                    escaped.push(']');
836                }
837                c => {
838                    escaped.push(c);
839                }
840            }
841        }
842        escaped
843    }
844
845    /// Return if the given `str` matches this `Pattern` using the default
846    /// match options (i.e. `MatchOptions::default()`).
847    ///
848    /// # Examples
849    ///
850    /// ```rust
851    /// use nu_glob::Pattern;
852    ///
853    /// assert!(Pattern::new("c?t").unwrap().matches("cat"));
854    /// assert!(Pattern::new("k[!e]tteh").unwrap().matches("kitteh"));
855    /// assert!(Pattern::new("d*g").unwrap().matches("doog"));
856    /// ```
857    pub fn matches(&self, str: &str) -> bool {
858        self.matches_with(str, MatchOptions::default())
859    }
860
861    /// Return if the given `Path`, when converted to a `str`, matches this
862    /// `Pattern` using the default match options (i.e. `MatchOptions::default()`).
863    pub fn matches_path(&self, path: &Path) -> bool {
864        // FIXME (#9639): This needs to handle non-utf8 paths
865        path.to_str().is_some_and(|s| self.matches(s))
866    }
867
868    /// Return if the given `str` matches this `Pattern` using the specified
869    /// match options.
870    pub fn matches_with(&self, str: &str, options: MatchOptions) -> bool {
871        self.matches_from(true, str.chars(), 0, options) == Match
872    }
873
874    /// Return if the given `Path`, when converted to a `str`, matches this
875    /// `Pattern` using the specified match options.
876    pub fn matches_path_with(&self, path: &Path, options: MatchOptions) -> bool {
877        // FIXME (#9639): This needs to handle non-utf8 paths
878        path.to_str().is_some_and(|s| self.matches_with(s, options))
879    }
880
881    /// Access the original glob pattern.
882    pub fn as_str(&self) -> &str {
883        &self.original
884    }
885
886    fn matches_from(
887        &self,
888        mut follows_separator: bool,
889        mut file: std::str::Chars,
890        i: usize,
891        options: MatchOptions,
892    ) -> MatchResult {
893        for (ti, token) in self.tokens[i..].iter().enumerate() {
894            match *token {
895                AnySequence | AnyRecursiveSequence => {
896                    // ** must be at the start.
897                    debug_assert!(match *token {
898                        AnyRecursiveSequence => follows_separator,
899                        _ => true,
900                    });
901
902                    // Empty match
903                    match self.matches_from(follows_separator, file.clone(), i + ti + 1, options) {
904                        SubPatternDoesntMatch => (), // keep trying
905                        m => return m,
906                    };
907
908                    while let Some(c) = file.next() {
909                        if follows_separator && options.require_literal_leading_dot && c == '.' {
910                            return SubPatternDoesntMatch;
911                        }
912                        follows_separator = path::is_separator(c);
913                        match *token {
914                            AnyRecursiveSequence if !follows_separator => continue,
915                            AnySequence
916                                if options.require_literal_separator && follows_separator =>
917                            {
918                                return SubPatternDoesntMatch;
919                            }
920                            _ => (),
921                        }
922                        match self.matches_from(
923                            follows_separator,
924                            file.clone(),
925                            i + ti + 1,
926                            options,
927                        ) {
928                            SubPatternDoesntMatch => (), // keep trying
929                            m => return m,
930                        }
931                    }
932                }
933                _ => {
934                    let c = match file.next() {
935                        Some(c) => c,
936                        None => return EntirePatternDoesntMatch,
937                    };
938
939                    let is_sep = path::is_separator(c);
940
941                    if !match *token {
942                        AnyChar | AnyWithin(..) | AnyExcept(..)
943                            if (options.require_literal_separator && is_sep)
944                                || (follows_separator
945                                    && options.require_literal_leading_dot
946                                    && c == '.') =>
947                        {
948                            false
949                        }
950                        AnyChar => true,
951                        AnyWithin(ref specifiers) => in_char_specifiers(specifiers, c, options),
952                        AnyExcept(ref specifiers) => !in_char_specifiers(specifiers, c, options),
953                        Char(c2) => chars_eq(c, c2, options.case_sensitive),
954                        AnySequence | AnyRecursiveSequence => unreachable!(),
955                    } {
956                        return SubPatternDoesntMatch;
957                    }
958                    follows_separator = is_sep;
959                }
960            }
961        }
962
963        // Iter is fused.
964        if file.next().is_none() {
965            Match
966        } else {
967            SubPatternDoesntMatch
968        }
969    }
970}
971
972// Fills `todo` with paths under `path` to be matched by `patterns[idx]`,
973// special-casing patterns to match `.` and `..`, and avoiding `readdir()`
974// calls when there are no metacharacters in the pattern.
975fn fill_todo(
976    todo: &mut Vec<Result<(PathBuf, usize), GlobError>>,
977    patterns: &[Pattern],
978    idx: usize,
979    path: &Path,
980    options: MatchOptions,
981    interrupt: &impl Interruptible,
982) {
983    // convert a pattern that's just many Char(_) to a string
984    fn pattern_as_str(pattern: &Pattern) -> Option<String> {
985        let mut s = String::new();
986        for token in &pattern.tokens {
987            match *token {
988                Char(c) => s.push(c),
989                _ => return None,
990            }
991        }
992
993        Some(s)
994    }
995
996    let add = |todo: &mut Vec<_>, next_path: PathBuf| {
997        if idx + 1 == patterns.len() {
998            // We know it's good, so don't make the iterator match this path
999            // against the pattern again. In particular, it can't match
1000            // . or .. globs since these never show up as path components.
1001            todo.push(Ok((next_path, !0)));
1002        } else {
1003            fill_todo(todo, patterns, idx + 1, &next_path, options, interrupt);
1004        }
1005    };
1006
1007    let pattern = &patterns[idx];
1008    let is_dir = is_dir(path);
1009    let curdir = path == Path::new(".");
1010    match pattern_as_str(pattern) {
1011        Some(s) => {
1012            // This pattern component doesn't have any metacharacters, so we
1013            // don't need to read the current directory to know where to
1014            // continue. So instead of passing control back to the iterator,
1015            // we can just check for that one entry and potentially recurse
1016            // right away.
1017            let special = "." == s || ".." == s;
1018            let next_path = if curdir {
1019                PathBuf::from(s)
1020            } else {
1021                path.join(&s)
1022            };
1023            if (special && is_dir)
1024                || (!special
1025                    && (fs::metadata(&next_path).is_ok()
1026                        || fs::symlink_metadata(&next_path).is_ok()))
1027            {
1028                add(todo, next_path);
1029            }
1030        }
1031        None if is_dir => {
1032            let dirs = fs::read_dir(path).and_then(|d| {
1033                d.map(|e| {
1034                    if interrupt.interrupted() {
1035                        return Err(io::Error::from(io::ErrorKind::Interrupted));
1036                    }
1037                    e.map(|e| {
1038                        if curdir {
1039                            PathBuf::from(
1040                                e.path()
1041                                    .file_name()
1042                                    .expect("internal error: missing filename"),
1043                            )
1044                        } else {
1045                            e.path()
1046                        }
1047                    })
1048                })
1049                .collect::<Result<Vec<_>, _>>()
1050            });
1051            match dirs {
1052                Ok(mut children) => {
1053                    // FIXME: This check messes up a lot of tests for some reason
1054                    // if options.require_literal_leading_dot {
1055                    //     children.retain(|x| {
1056                    //         !x.file_name()
1057                    //             .expect("internal error: getting filename")
1058                    //             .to_str()
1059                    //             .expect("internal error: filename to_str")
1060                    //             .starts_with('.')
1061                    //     });
1062                    // }
1063                    children.sort_by(|p1, p2| p2.file_name().cmp(&p1.file_name()));
1064                    todo.extend(children.into_iter().map(|x| Ok((x, idx))));
1065
1066                    // Matching the special directory entries . and .. that
1067                    // refer to the current and parent directory respectively
1068                    // requires that the pattern has a leading dot, even if the
1069                    // `MatchOptions` field `require_literal_leading_dot` is not
1070                    // set.
1071                    if !pattern.tokens.is_empty() && pattern.tokens[0] == Char('.') {
1072                        for &special in &[".", ".."] {
1073                            if pattern.matches_with(special, options) {
1074                                add(todo, path.join(special));
1075                            }
1076                        }
1077                    }
1078                }
1079                Err(e) => {
1080                    todo.push(Err(GlobError {
1081                        path: path.to_path_buf(),
1082                        error: e,
1083                    }));
1084                }
1085            }
1086        }
1087        None => {
1088            // not a directory, nothing more to find
1089        }
1090    }
1091}
1092
1093fn parse_char_specifiers(s: &[char]) -> Vec<CharSpecifier> {
1094    let mut cs = Vec::new();
1095    let mut i = 0;
1096    while i < s.len() {
1097        if i + 3 <= s.len() && s[i + 1] == '-' {
1098            cs.push(CharRange(s[i], s[i + 2]));
1099            i += 3;
1100        } else {
1101            cs.push(SingleChar(s[i]));
1102            i += 1;
1103        }
1104    }
1105    cs
1106}
1107
1108fn in_char_specifiers(specifiers: &[CharSpecifier], c: char, options: MatchOptions) -> bool {
1109    for &specifier in specifiers.iter() {
1110        match specifier {
1111            SingleChar(sc) => {
1112                if chars_eq(c, sc, options.case_sensitive) {
1113                    return true;
1114                }
1115            }
1116            CharRange(start, end) => {
1117                // FIXME: work with non-ascii chars properly (issue #1347)
1118                if !options.case_sensitive && c.is_ascii() && start.is_ascii() && end.is_ascii() {
1119                    // only allow case insensitive matching when
1120                    // both start and end are within a-z or A-Z
1121                    if start.is_ascii_alphabetic() && end.is_ascii_alphabetic() {
1122                        let start = start.to_ascii_lowercase();
1123                        let end = end.to_ascii_lowercase();
1124                        let c = c.to_ascii_lowercase();
1125                        if (start..=end).contains(&c) {
1126                            return true;
1127                        }
1128                    }
1129                }
1130
1131                if (start..=end).contains(&c) {
1132                    return true;
1133                }
1134            }
1135        }
1136    }
1137
1138    false
1139}
1140
1141/// A helper function to determine if two chars are (possibly case-insensitively) equal.
1142fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool {
1143    if cfg!(windows) && path::is_separator(a) && path::is_separator(b) {
1144        true
1145    } else if !case_sensitive && a.is_ascii() && b.is_ascii() {
1146        // FIXME: work with non-ascii chars properly (issue #9084)
1147        a.eq_ignore_ascii_case(&b)
1148    } else {
1149        a == b
1150    }
1151}
1152
1153/// Configuration options to modify the behaviour of `Pattern::matches_with(..)`.
1154#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1155pub struct MatchOptions {
1156    /// Whether or not patterns should be matched in a case-sensitive manner.
1157    /// This currently only considers upper/lower case relationships between
1158    /// ASCII characters, but in future this might be extended to work with
1159    /// Unicode.
1160    pub case_sensitive: bool,
1161
1162    /// Whether or not path-component separator characters (e.g. `/` on
1163    /// Posix) must be matched by a literal `/`, rather than by `*` or `?` or
1164    /// `[...]`.
1165    pub require_literal_separator: bool,
1166
1167    /// Whether or not paths that contain components that start with a `.`
1168    /// will require that `.` appears literally in the pattern; `*`, `?`, `**`,
1169    /// or `[...]` will not match. This is useful because such files are
1170    /// conventionally considered hidden on Unix systems and it might be
1171    /// desirable to skip them when listing files.
1172    pub require_literal_leading_dot: bool,
1173
1174    /// if given pattern contains `**`, this flag check if `**` matches hidden directory.
1175    /// For example: if true, `**` will match `.abcdef/ghi`.
1176    pub recursive_match_hidden_dir: bool,
1177}
1178
1179// Overwrite default behavior, because we want to make `recursive_match_hidden_dir` to true.
1180impl Default for MatchOptions {
1181    fn default() -> Self {
1182        Self {
1183            case_sensitive: true,
1184            require_literal_separator: false,
1185            require_literal_leading_dot: false,
1186            recursive_match_hidden_dir: true,
1187        }
1188    }
1189}
1190
1191#[cfg(test)]
1192mod test {
1193    use crate::{Paths, PatternError, Uninterruptible};
1194
1195    use super::{MatchOptions, Pattern, glob as glob_with_signals};
1196    use std::path::Path;
1197
1198    fn glob(pattern: &str) -> Result<Paths, PatternError> {
1199        glob_with_signals(pattern, Uninterruptible)
1200    }
1201
1202    #[test]
1203    fn test_pattern_from_str() {
1204        assert!("a*b".parse::<Pattern>().unwrap().matches("a_b"));
1205        assert_eq!("a/**b".parse::<Pattern>().unwrap_err().pos, 4);
1206    }
1207
1208    #[test]
1209    fn test_wildcard_errors() {
1210        assert!(Pattern::new("a/**b").unwrap_err().pos == 4);
1211        assert!(Pattern::new("a/bc**").unwrap_err().pos == 3);
1212        assert!(Pattern::new("a/*****").unwrap_err().pos == 4);
1213        assert!(Pattern::new("a/b**c**d").unwrap_err().pos == 2);
1214        assert!(Pattern::new("a**b").unwrap_err().pos == 0);
1215    }
1216
1217    #[test]
1218    fn test_unclosed_bracket_errors() {
1219        assert!(Pattern::new("abc[def").unwrap_err().pos == 3);
1220        assert!(Pattern::new("abc[!def").unwrap_err().pos == 3);
1221        assert!(Pattern::new("abc[").unwrap_err().pos == 3);
1222        assert!(Pattern::new("abc[!").unwrap_err().pos == 3);
1223        assert!(Pattern::new("abc[d").unwrap_err().pos == 3);
1224        assert!(Pattern::new("abc[!d").unwrap_err().pos == 3);
1225        assert!(Pattern::new("abc[]").unwrap_err().pos == 3);
1226        assert!(Pattern::new("abc[!]").unwrap_err().pos == 3);
1227    }
1228
1229    #[test]
1230    fn test_glob_errors() {
1231        assert!(glob("a/**b").err().unwrap().pos == 4);
1232        assert!(glob("abc[def").err().unwrap().pos == 3);
1233    }
1234
1235    // this test assumes that there is a /root directory and that
1236    // the user running this test is not root or otherwise doesn't
1237    // have permission to read its contents
1238    #[cfg(all(
1239        unix,
1240        not(target_os = "macos"),
1241        not(target_os = "android"),
1242        not(target_os = "ios")
1243    ))]
1244    #[test]
1245    fn test_iteration_errors() {
1246        use std::io;
1247        let mut iter = glob("/root/*").unwrap();
1248
1249        match std::fs::read_dir("/root/") {
1250            // skip if running with permissions to read /root
1251            Ok(_) => {}
1252
1253            // skip if /root doesn't exist
1254            Err(err) if err.kind() == io::ErrorKind::NotFound => {
1255                assert!(iter.count() == 0);
1256            }
1257
1258            // should otherwise return a single match with permission error
1259            Err(_) => {
1260                // GlobErrors shouldn't halt iteration
1261                let next = iter.next();
1262                assert!(next.is_some());
1263
1264                let err = next.unwrap();
1265                assert!(err.is_err());
1266
1267                let err = err.err().unwrap();
1268                assert!(err.path() == Path::new("/root"));
1269                assert!(err.error().kind() == io::ErrorKind::PermissionDenied);
1270            }
1271        }
1272    }
1273
1274    #[test]
1275    fn test_absolute_pattern() {
1276        assert!(glob("/").unwrap().next().is_some());
1277        assert!(glob("//").unwrap().next().is_some());
1278
1279        // assume that the filesystem is not empty!
1280        assert!(glob("/*").unwrap().next().is_some());
1281
1282        #[cfg(not(windows))]
1283        fn win() {}
1284
1285        #[cfg(windows)]
1286        fn win() {
1287            use std::env::current_dir;
1288            use std::path::Component;
1289
1290            // check windows absolute paths with host/device components
1291            let root_with_device = current_dir()
1292                .ok()
1293                .map(|p| match p.components().next().unwrap() {
1294                    Component::Prefix(prefix_component) => {
1295                        Path::new(prefix_component.as_os_str()).join("*")
1296                    }
1297                    _ => panic!("no prefix in this path"),
1298                })
1299                .unwrap();
1300            // FIXME (#9639): This needs to handle non-utf8 paths
1301            assert!(
1302                glob(root_with_device.as_os_str().to_str().unwrap())
1303                    .unwrap()
1304                    .next()
1305                    .is_some()
1306            );
1307        }
1308        win()
1309    }
1310
1311    #[test]
1312    fn test_wildcards() {
1313        assert!(Pattern::new("a*b").unwrap().matches("a_b"));
1314        assert!(Pattern::new("a*b*c").unwrap().matches("abc"));
1315        assert!(!Pattern::new("a*b*c").unwrap().matches("abcd"));
1316        assert!(Pattern::new("a*b*c").unwrap().matches("a_b_c"));
1317        assert!(Pattern::new("a*b*c").unwrap().matches("a___b___c"));
1318        assert!(
1319            Pattern::new("abc*abc*abc")
1320                .unwrap()
1321                .matches("abcabcabcabcabcabcabc")
1322        );
1323        assert!(
1324            !Pattern::new("abc*abc*abc")
1325                .unwrap()
1326                .matches("abcabcabcabcabcabcabca")
1327        );
1328        assert!(
1329            Pattern::new("a*a*a*a*a*a*a*a*a")
1330                .unwrap()
1331                .matches("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
1332        );
1333        assert!(Pattern::new("a*b[xyz]c*d").unwrap().matches("abxcdbxcddd"));
1334    }
1335
1336    #[test]
1337    fn test_recursive_wildcards() {
1338        let pat = Pattern::new("some/**/needle.txt").unwrap();
1339        assert!(pat.matches("some/needle.txt"));
1340        assert!(pat.matches("some/one/needle.txt"));
1341        assert!(pat.matches("some/one/two/needle.txt"));
1342        assert!(pat.matches("some/other/needle.txt"));
1343        assert!(!pat.matches("some/other/notthis.txt"));
1344
1345        // a single ** should be valid, for globs
1346        // Should accept anything
1347        let pat = Pattern::new("**").unwrap();
1348        assert!(pat.is_recursive);
1349        assert!(pat.matches("abcde"));
1350        assert!(pat.matches(""));
1351        assert!(pat.matches(".asdf"));
1352        assert!(pat.matches("/x/.asdf"));
1353
1354        // collapse consecutive wildcards
1355        let pat = Pattern::new("some/**/**/needle.txt").unwrap();
1356        assert!(pat.matches("some/needle.txt"));
1357        assert!(pat.matches("some/one/needle.txt"));
1358        assert!(pat.matches("some/one/two/needle.txt"));
1359        assert!(pat.matches("some/other/needle.txt"));
1360        assert!(!pat.matches("some/other/notthis.txt"));
1361
1362        // ** can begin the pattern
1363        let pat = Pattern::new("**/test").unwrap();
1364        assert!(pat.matches("one/two/test"));
1365        assert!(pat.matches("one/test"));
1366        assert!(pat.matches("test"));
1367
1368        // /** can begin the pattern
1369        let pat = Pattern::new("/**/test").unwrap();
1370        assert!(pat.matches("/one/two/test"));
1371        assert!(pat.matches("/one/test"));
1372        assert!(pat.matches("/test"));
1373        assert!(!pat.matches("/one/notthis"));
1374        assert!(!pat.matches("/notthis"));
1375
1376        // Only start sub-patterns on start of path segment.
1377        let pat = Pattern::new("**/.*").unwrap();
1378        assert!(pat.matches(".abc"));
1379        assert!(pat.matches("abc/.abc"));
1380        assert!(!pat.matches("ab.c"));
1381        assert!(!pat.matches("abc/ab.c"));
1382    }
1383
1384    #[test]
1385    fn test_lots_of_files() {
1386        // this is a good test because it touches lots of differently named files
1387        glob("/*/*/*/*").unwrap().nth(10000);
1388    }
1389
1390    #[test]
1391    fn test_range_pattern() {
1392        let pat = Pattern::new("a[0-9]b").unwrap();
1393        for i in 0..10 {
1394            assert!(pat.matches(&format!("a{i}b")), "a{i}b =~ a[0-9]b");
1395        }
1396        assert!(!pat.matches("a_b"));
1397
1398        let pat = Pattern::new("a[!0-9]b").unwrap();
1399        for i in 0..10 {
1400            assert!(!pat.matches(&format!("a{i}b")));
1401        }
1402        assert!(pat.matches("a_b"));
1403
1404        let pats = ["[a-z123]", "[1a-z23]", "[123a-z]"];
1405        for &p in pats.iter() {
1406            let pat = Pattern::new(p).unwrap();
1407            for c in "abcdefghijklmnopqrstuvwxyz".chars() {
1408                assert!(pat.matches(&c.to_string()));
1409            }
1410            for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() {
1411                let options = MatchOptions {
1412                    case_sensitive: false,
1413                    ..MatchOptions::default()
1414                };
1415                assert!(pat.matches_with(&c.to_string(), options));
1416            }
1417            assert!(pat.matches("1"));
1418            assert!(pat.matches("2"));
1419            assert!(pat.matches("3"));
1420        }
1421
1422        let pats = ["[abc-]", "[-abc]", "[a-c-]"];
1423        for &p in pats.iter() {
1424            let pat = Pattern::new(p).unwrap();
1425            assert!(pat.matches("a"));
1426            assert!(pat.matches("b"));
1427            assert!(pat.matches("c"));
1428            assert!(pat.matches("-"));
1429            assert!(!pat.matches("d"));
1430        }
1431
1432        let pat = Pattern::new("[2-1]").unwrap();
1433        assert!(!pat.matches("1"));
1434        assert!(!pat.matches("2"));
1435
1436        assert!(Pattern::new("[-]").unwrap().matches("-"));
1437        assert!(!Pattern::new("[!-]").unwrap().matches("-"));
1438    }
1439
1440    #[test]
1441    fn test_pattern_matches() {
1442        let txt_pat = Pattern::new("*hello.txt").unwrap();
1443        assert!(txt_pat.matches("hello.txt"));
1444        assert!(txt_pat.matches("gareth_says_hello.txt"));
1445        assert!(txt_pat.matches("some/path/to/hello.txt"));
1446        assert!(txt_pat.matches("some\\path\\to\\hello.txt"));
1447        assert!(txt_pat.matches("/an/absolute/path/to/hello.txt"));
1448        assert!(!txt_pat.matches("hello.txt-and-then-some"));
1449        assert!(!txt_pat.matches("goodbye.txt"));
1450
1451        let dir_pat = Pattern::new("*some/path/to/hello.txt").unwrap();
1452        assert!(dir_pat.matches("some/path/to/hello.txt"));
1453        assert!(dir_pat.matches("a/bigger/some/path/to/hello.txt"));
1454        assert!(!dir_pat.matches("some/path/to/hello.txt-and-then-some"));
1455        assert!(!dir_pat.matches("some/other/path/to/hello.txt"));
1456    }
1457
1458    #[test]
1459    fn test_pattern_escape() {
1460        let s = "_[_]_?_*_!_";
1461        assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_string());
1462        assert!(Pattern::new(&Pattern::escape(s)).unwrap().matches(s));
1463    }
1464
1465    #[test]
1466    fn test_pattern_matches_case_insensitive() {
1467        let pat = Pattern::new("aBcDeFg").unwrap();
1468        let options = MatchOptions {
1469            case_sensitive: false,
1470            require_literal_separator: false,
1471            require_literal_leading_dot: false,
1472            recursive_match_hidden_dir: true,
1473        };
1474
1475        assert!(pat.matches_with("aBcDeFg", options));
1476        assert!(pat.matches_with("abcdefg", options));
1477        assert!(pat.matches_with("ABCDEFG", options));
1478        assert!(pat.matches_with("AbCdEfG", options));
1479    }
1480
1481    #[test]
1482    fn test_pattern_matches_case_insensitive_range() {
1483        let pat_within = Pattern::new("[a]").unwrap();
1484        let pat_except = Pattern::new("[!a]").unwrap();
1485
1486        let options_case_insensitive = MatchOptions {
1487            case_sensitive: false,
1488            require_literal_separator: false,
1489            require_literal_leading_dot: false,
1490            recursive_match_hidden_dir: false,
1491        };
1492        let options_case_sensitive = MatchOptions {
1493            case_sensitive: true,
1494            require_literal_separator: false,
1495            require_literal_leading_dot: false,
1496            recursive_match_hidden_dir: false,
1497        };
1498
1499        assert!(pat_within.matches_with("a", options_case_insensitive));
1500        assert!(pat_within.matches_with("A", options_case_insensitive));
1501        assert!(!pat_within.matches_with("A", options_case_sensitive));
1502
1503        assert!(!pat_except.matches_with("a", options_case_insensitive));
1504        assert!(!pat_except.matches_with("A", options_case_insensitive));
1505        assert!(pat_except.matches_with("A", options_case_sensitive));
1506    }
1507
1508    #[test]
1509    fn test_pattern_matches_require_literal_separator() {
1510        let options_require_literal = MatchOptions {
1511            case_sensitive: true,
1512            require_literal_separator: true,
1513            require_literal_leading_dot: false,
1514            recursive_match_hidden_dir: true,
1515        };
1516        let options_not_require_literal = MatchOptions {
1517            case_sensitive: true,
1518            require_literal_separator: false,
1519            require_literal_leading_dot: false,
1520            recursive_match_hidden_dir: true,
1521        };
1522
1523        assert!(
1524            Pattern::new("abc/def")
1525                .unwrap()
1526                .matches_with("abc/def", options_require_literal)
1527        );
1528        assert!(
1529            !Pattern::new("abc?def")
1530                .unwrap()
1531                .matches_with("abc/def", options_require_literal)
1532        );
1533        assert!(
1534            !Pattern::new("abc*def")
1535                .unwrap()
1536                .matches_with("abc/def", options_require_literal)
1537        );
1538        assert!(
1539            !Pattern::new("abc[/]def")
1540                .unwrap()
1541                .matches_with("abc/def", options_require_literal)
1542        );
1543
1544        assert!(
1545            Pattern::new("abc/def")
1546                .unwrap()
1547                .matches_with("abc/def", options_not_require_literal)
1548        );
1549        assert!(
1550            Pattern::new("abc?def")
1551                .unwrap()
1552                .matches_with("abc/def", options_not_require_literal)
1553        );
1554        assert!(
1555            Pattern::new("abc*def")
1556                .unwrap()
1557                .matches_with("abc/def", options_not_require_literal)
1558        );
1559        assert!(
1560            Pattern::new("abc[/]def")
1561                .unwrap()
1562                .matches_with("abc/def", options_not_require_literal)
1563        );
1564    }
1565
1566    #[test]
1567    fn test_pattern_matches_require_literal_leading_dot() {
1568        let options_require_literal_leading_dot = MatchOptions {
1569            case_sensitive: true,
1570            require_literal_separator: false,
1571            require_literal_leading_dot: true,
1572            recursive_match_hidden_dir: true,
1573        };
1574        let options_not_require_literal_leading_dot = MatchOptions {
1575            case_sensitive: true,
1576            require_literal_separator: false,
1577            require_literal_leading_dot: false,
1578            recursive_match_hidden_dir: true,
1579        };
1580
1581        let f = |options| {
1582            Pattern::new("*.txt")
1583                .unwrap()
1584                .matches_with(".hello.txt", options)
1585        };
1586        assert!(f(options_not_require_literal_leading_dot));
1587        assert!(!f(options_require_literal_leading_dot));
1588
1589        let f = |options| {
1590            Pattern::new(".*.*")
1591                .unwrap()
1592                .matches_with(".hello.txt", options)
1593        };
1594        assert!(f(options_not_require_literal_leading_dot));
1595        assert!(f(options_require_literal_leading_dot));
1596
1597        let f = |options| {
1598            Pattern::new("aaa/bbb/*")
1599                .unwrap()
1600                .matches_with("aaa/bbb/.ccc", options)
1601        };
1602        assert!(f(options_not_require_literal_leading_dot));
1603        assert!(!f(options_require_literal_leading_dot));
1604
1605        let f = |options| {
1606            Pattern::new("aaa/bbb/*")
1607                .unwrap()
1608                .matches_with("aaa/bbb/c.c.c.", options)
1609        };
1610        assert!(f(options_not_require_literal_leading_dot));
1611        assert!(f(options_require_literal_leading_dot));
1612
1613        let f = |options| {
1614            Pattern::new("aaa/bbb/.*")
1615                .unwrap()
1616                .matches_with("aaa/bbb/.ccc", options)
1617        };
1618        assert!(f(options_not_require_literal_leading_dot));
1619        assert!(f(options_require_literal_leading_dot));
1620
1621        let f = |options| {
1622            Pattern::new("aaa/?bbb")
1623                .unwrap()
1624                .matches_with("aaa/.bbb", options)
1625        };
1626        assert!(f(options_not_require_literal_leading_dot));
1627        assert!(!f(options_require_literal_leading_dot));
1628
1629        let f = |options| {
1630            Pattern::new("aaa/[.]bbb")
1631                .unwrap()
1632                .matches_with("aaa/.bbb", options)
1633        };
1634        assert!(f(options_not_require_literal_leading_dot));
1635        assert!(!f(options_require_literal_leading_dot));
1636
1637        let f = |options| Pattern::new("**/*").unwrap().matches_with(".bbb", options);
1638        assert!(f(options_not_require_literal_leading_dot));
1639        assert!(!f(options_require_literal_leading_dot));
1640    }
1641
1642    #[test]
1643    fn test_matches_path() {
1644        // on windows, (Path::new("a/b").as_str().unwrap() == "a\\b"), so this
1645        // tests that / and \ are considered equivalent on windows
1646        assert!(Pattern::new("a/b").unwrap().matches_path(Path::new("a/b")));
1647    }
1648
1649    #[test]
1650    fn test_path_join() {
1651        let pattern = Path::new("one").join(Path::new("**/*.rs"));
1652        assert!(Pattern::new(pattern.to_str().unwrap()).is_ok());
1653    }
1654}