Skip to content
Myr

lib.rs

This file

Path

crates/ignore/src/lib.rs

549 lines · 18.2 KiB · Rust

Last changed by

ignore: add incremental checkingAndrew Gallantbefore adoptionb621e65

History of this file

Take it

1/*!2The ignore crate provides a fast recursive directory iterator that respects3various filters such as globs, file types and `.gitignore` files. The precise4matching rules and precedence is explained in the documentation for5`WalkBuilder`.67Secondarily, this crate exposes gitignore and file type matchers for use cases8that demand more fine-grained control.910# Example1112This example shows the most basic usage of this crate. This code will13recursively traverse the current directory while automatically filtering out14files and directories according to ignore globs found in files like15`.ignore` and `.gitignore`:161718```rust,no_run19use ignore::Walk;2021for result in Walk::new("./") {22    // Each item yielded by the iterator is either a directory entry or an23    // error, so either print the path or the error.24    match result {25        Ok(entry) => println!("{}", entry.path().display()),26        Err(err) => println!("ERROR: {}", err),27    }28}29```3031# Example: advanced3233By default, the recursive directory iterator will ignore hidden files and34directories. This can be disabled by building the iterator with `WalkBuilder`:3536```rust,no_run37use ignore::WalkBuilder;3839for result in WalkBuilder::new("./").hidden(false).build() {40    println!("{:?}", result);41}42```4344See the documentation for `WalkBuilder` for many other options.45*/4647#![deny(missing_docs)]4849use std::path::{Path, PathBuf};5051pub use crate::incremental::{IncrementalIgnore, IncrementalMatch};52pub use crate::walk::{53    DirEntry, ParallelVisitor, ParallelVisitorBuilder, Walk, WalkBuilder,54    WalkParallel, WalkState,55};5657mod default_types;58mod dir;59pub mod gitignore;60mod incremental;61pub mod overrides;62mod pathutil;63pub mod types;64mod walk;6566/// Represents an error that can occur when parsing a gitignore file.67#[derive(Debug)]68pub enum Error {69    /// A collection of "soft" errors. These occur when adding an ignore70    /// file partially succeeded.71    Partial(Vec<Error>),72    /// An error associated with a specific line number.73    WithLineNumber {74        /// The line number.75        line: u64,76        /// The underlying error.77        err: Box<Error>,78    },79    /// An error associated with a particular file path.80    WithPath {81        /// The file path.82        path: PathBuf,83        /// The underlying error.84        err: Box<Error>,85    },86    /// An error associated with a particular directory depth when recursively87    /// walking a directory.88    WithDepth {89        /// The directory depth.90        depth: usize,91        /// The underlying error.92        err: Box<Error>,93    },94    /// An error that occurs when a file loop is detected when traversing95    /// symbolic links.96    Loop {97        /// The ancestor file path in the loop.98        ancestor: PathBuf,99        /// The child file path in the loop.100        child: PathBuf,101    },102    /// An error that occurs when doing I/O, such as reading an ignore file.103    Io(std::io::Error),104    /// An error that occurs when trying to parse a glob.105    Glob {106        /// The original glob that caused this error. This glob, when107        /// available, always corresponds to the glob provided by an end user.108        /// e.g., It is the glob as written in a `.gitignore` file.109        ///110        /// (This glob may be distinct from the glob that is actually111        /// compiled, after accounting for `gitignore` semantics.)112        glob: Option<String>,113        /// The underlying glob error as a string.114        err: String,115    },116    /// A type selection for a file type that is not defined.117    UnrecognizedFileType(String),118    /// A user specified file type definition could not be parsed.119    InvalidDefinition,120}121122impl Clone for Error {123    fn clone(&self) -> Error {124        match *self {125            Error::Partial(ref errs) => Error::Partial(errs.clone()),126            Error::WithLineNumber { line, ref err } => {127                Error::WithLineNumber { line, err: err.clone() }128            }129            Error::WithPath { ref path, ref err } => {130                Error::WithPath { path: path.clone(), err: err.clone() }131            }132            Error::WithDepth { depth, ref err } => {133                Error::WithDepth { depth, err: err.clone() }134            }135            Error::Loop { ref ancestor, ref child } => Error::Loop {136                ancestor: ancestor.clone(),137                child: child.clone(),138            },139            Error::Io(ref err) => match err.raw_os_error() {140                Some(e) => Error::Io(std::io::Error::from_raw_os_error(e)),141                None => {142                    Error::Io(std::io::Error::new(err.kind(), err.to_string()))143                }144            },145            Error::Glob { ref glob, ref err } => {146                Error::Glob { glob: glob.clone(), err: err.clone() }147            }148            Error::UnrecognizedFileType(ref err) => {149                Error::UnrecognizedFileType(err.clone())150            }151            Error::InvalidDefinition => Error::InvalidDefinition,152        }153    }154}155156impl Error {157    /// Returns true if this is a partial error.158    ///159    /// A partial error occurs when only some operations failed while others160    /// may have succeeded. For example, an ignore file may contain an invalid161    /// glob among otherwise valid globs.162    pub fn is_partial(&self) -> bool {163        match *self {164            Error::Partial(_) => true,165            Error::WithLineNumber { ref err, .. } => err.is_partial(),166            Error::WithPath { ref err, .. } => err.is_partial(),167            Error::WithDepth { ref err, .. } => err.is_partial(),168            _ => false,169        }170    }171172    /// Returns true if this error is exclusively an I/O error.173    pub fn is_io(&self) -> bool {174        match *self {175            Error::Partial(ref errs) => errs.len() == 1 && errs[0].is_io(),176            Error::WithLineNumber { ref err, .. } => err.is_io(),177            Error::WithPath { ref err, .. } => err.is_io(),178            Error::WithDepth { ref err, .. } => err.is_io(),179            Error::Loop { .. } => false,180            Error::Io(_) => true,181            Error::Glob { .. } => false,182            Error::UnrecognizedFileType(_) => false,183            Error::InvalidDefinition => false,184        }185    }186187    /// Inspect the original [`std::io::Error`] if there is one.188    ///189    /// [`None`] is returned if the [`Error`] doesn't correspond to an190    /// [`std::io::Error`]. This might happen, for example, when the error was191    /// produced because a cycle was found in the directory tree while192    /// following symbolic links.193    ///194    /// This method returns a borrowed value that is bound to the lifetime of the [`Error`]. To195    /// obtain an owned value, the [`into_io_error`] can be used instead.196    ///197    /// > This is the original [`std::io::Error`] and is _not_ the same as198    /// > [`impl From<Error> for std::io::Error`][impl] which contains199    /// > additional context about the error.200    ///201    /// [`None`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None202    /// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html203    /// [`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html204    /// [`Error`]: struct.Error.html205    /// [`into_io_error`]: struct.Error.html#method.into_io_error206    /// [impl]: struct.Error.html#impl-From%3CError%3E207    pub fn io_error(&self) -> Option<&std::io::Error> {208        match *self {209            Error::Partial(ref errs) => {210                if errs.len() == 1 {211                    errs[0].io_error()212                } else {213                    None214                }215            }216            Error::WithLineNumber { ref err, .. } => err.io_error(),217            Error::WithPath { ref err, .. } => err.io_error(),218            Error::WithDepth { ref err, .. } => err.io_error(),219            Error::Loop { .. } => None,220            Error::Io(ref err) => Some(err),221            Error::Glob { .. } => None,222            Error::UnrecognizedFileType(_) => None,223            Error::InvalidDefinition => None,224        }225    }226227    /// Similar to [`io_error`] except consumes self to convert to the original228    /// [`std::io::Error`] if one exists.229    ///230    /// [`io_error`]: struct.Error.html#method.io_error231    /// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html232    pub fn into_io_error(self) -> Option<std::io::Error> {233        match self {234            Error::Partial(mut errs) => {235                if errs.len() == 1 {236                    errs.remove(0).into_io_error()237                } else {238                    None239                }240            }241            Error::WithLineNumber { err, .. } => err.into_io_error(),242            Error::WithPath { err, .. } => err.into_io_error(),243            Error::WithDepth { err, .. } => err.into_io_error(),244            Error::Loop { .. } => None,245            Error::Io(err) => Some(err),246            Error::Glob { .. } => None,247            Error::UnrecognizedFileType(_) => None,248            Error::InvalidDefinition => None,249        }250    }251252    /// Returns a depth associated with recursively walking a directory (if253    /// this error was generated from a recursive directory iterator).254    pub fn depth(&self) -> Option<usize> {255        match *self {256            Error::WithPath { ref err, .. } => err.depth(),257            Error::WithDepth { depth, .. } => Some(depth),258            _ => None,259        }260    }261262    /// Turn an error into a tagged error with the given file path.263    fn with_path<P: AsRef<Path>>(self, path: P) -> Error {264        Error::WithPath {265            path: path.as_ref().to_path_buf(),266            err: Box::new(self),267        }268    }269270    /// Turn an error into a tagged error with the given depth.271    fn with_depth(self, depth: usize) -> Error {272        Error::WithDepth { depth, err: Box::new(self) }273    }274275    /// Turn an error into a tagged error with the given file path and line276    /// number. If path is empty, then it is omitted from the error.277    fn tagged<P: AsRef<Path>>(self, path: P, lineno: u64) -> Error {278        let errline =279            Error::WithLineNumber { line: lineno, err: Box::new(self) };280        if path.as_ref().as_os_str().is_empty() {281            return errline;282        }283        errline.with_path(path)284    }285286    /// Build an error from a walkdir error.287    fn from_walkdir(err: walkdir::Error) -> Error {288        let depth = err.depth();289        if let (Some(anc), Some(child)) = (err.loop_ancestor(), err.path()) {290            return Error::WithDepth {291                depth,292                err: Box::new(Error::Loop {293                    ancestor: anc.to_path_buf(),294                    child: child.to_path_buf(),295                }),296            };297        }298        let path = err.path().map(|p| p.to_path_buf());299        let mut ig_err = Error::WithDepth {300            depth,301            err: Box::new(Error::Io(std::io::Error::from(err))),302        };303        if let Some(path) = path {304            ig_err = Error::WithPath { path, err: Box::new(ig_err) };305        }306        ig_err307    }308}309310impl std::error::Error for Error {311    #[allow(deprecated)]312    fn description(&self) -> &str {313        match *self {314            Error::Partial(_) => "partial error",315            Error::WithLineNumber { ref err, .. } => err.description(),316            Error::WithPath { ref err, .. } => err.description(),317            Error::WithDepth { ref err, .. } => err.description(),318            Error::Loop { .. } => "file system loop found",319            Error::Io(ref err) => err.description(),320            Error::Glob { ref err, .. } => err,321            Error::UnrecognizedFileType(_) => "unrecognized file type",322            Error::InvalidDefinition => "invalid definition",323        }324    }325}326327impl std::fmt::Display for Error {328    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {329        match *self {330            Error::Partial(ref errs) => {331                let msgs: Vec<String> =332                    errs.iter().map(|err| err.to_string()).collect();333                write!(f, "{}", msgs.join("\n"))334            }335            Error::WithLineNumber { line, ref err } => {336                write!(f, "line {}: {}", line, err)337            }338            Error::WithPath { ref path, ref err } => {339                write!(f, "{}: {}", path.display(), err)340            }341            Error::WithDepth { ref err, .. } => err.fmt(f),342            Error::Loop { ref ancestor, ref child } => write!(343                f,344                "File system loop found: \345                           {} points to an ancestor {}",346                child.display(),347                ancestor.display()348            ),349            Error::Io(ref err) => err.fmt(f),350            Error::Glob { glob: None, ref err } => write!(f, "{}", err),351            Error::Glob { glob: Some(ref glob), ref err } => {352                write!(f, "error parsing glob '{}': {}", glob, err)353            }354            Error::UnrecognizedFileType(ref ty) => {355                write!(f, "unrecognized file type: {}", ty)356            }357            Error::InvalidDefinition => write!(358                f,359                "invalid definition (format is type:glob, e.g., \360                           html:*.html)"361            ),362        }363    }364}365366impl From<std::io::Error> for Error {367    fn from(err: std::io::Error) -> Error {368        Error::Io(err)369    }370}371372#[derive(Debug, Default)]373struct PartialErrorBuilder(Vec<Error>);374375impl PartialErrorBuilder {376    fn push(&mut self, err: Error) {377        self.0.push(err);378    }379380    fn push_ignore_io(&mut self, err: Error) {381        if !err.is_io() {382            self.push(err);383        }384    }385386    fn maybe_push(&mut self, err: Option<Error>) {387        if let Some(err) = err {388            self.push(err);389        }390    }391392    fn maybe_push_ignore_io(&mut self, err: Option<Error>) {393        if let Some(err) = err {394            self.push_ignore_io(err);395        }396    }397398    fn into_error_option(mut self) -> Option<Error> {399        if self.0.is_empty() {400            None401        } else if self.0.len() == 1 {402            Some(self.0.pop().unwrap())403        } else {404            Some(Error::Partial(self.0))405        }406    }407}408409/// The result of a glob match.410///411/// The type parameter `T` typically refers to a type that provides more412/// information about a particular match. For example, it might identify413/// the specific gitignore file and the specific glob pattern that caused414/// the match.415#[derive(Clone, Debug)]416pub enum Match<T> {417    /// The path didn't match any glob.418    None,419    /// The highest precedent glob matched indicates the path should be420    /// ignored.421    Ignore(T),422    /// The highest precedent glob matched indicates the path should be423    /// whitelisted.424    Whitelist(T),425}426427impl<T> Match<T> {428    /// Returns true if the match result didn't match any globs.429    pub fn is_none(&self) -> bool {430        match *self {431            Match::None => true,432            Match::Ignore(_) | Match::Whitelist(_) => false,433        }434    }435436    /// Returns true if the match result implies the path should be ignored.437    pub fn is_ignore(&self) -> bool {438        match *self {439            Match::Ignore(_) => true,440            Match::None | Match::Whitelist(_) => false,441        }442    }443444    /// Returns true if the match result implies the path should be445    /// whitelisted.446    pub fn is_whitelist(&self) -> bool {447        match *self {448            Match::Whitelist(_) => true,449            Match::None | Match::Ignore(_) => false,450        }451    }452453    /// Inverts the match so that `Ignore` becomes `Whitelist` and454    /// `Whitelist` becomes `Ignore`. A non-match remains the same.455    pub fn invert(self) -> Match<T> {456        match self {457            Match::None => Match::None,458            Match::Ignore(t) => Match::Whitelist(t),459            Match::Whitelist(t) => Match::Ignore(t),460        }461    }462463    /// Return the value inside this match if it exists.464    pub fn inner(&self) -> Option<&T> {465        match *self {466            Match::None => None,467            Match::Ignore(ref t) => Some(t),468            Match::Whitelist(ref t) => Some(t),469        }470    }471472    /// Apply the given function to the value inside this match.473    ///474    /// If the match has no value, then return the match unchanged.475    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Match<U> {476        match self {477            Match::None => Match::None,478            Match::Ignore(t) => Match::Ignore(f(t)),479            Match::Whitelist(t) => Match::Whitelist(f(t)),480        }481    }482483    /// Return the match if it is not none. Otherwise, return other.484    pub fn or(self, other: Self) -> Self {485        if self.is_none() { other } else { self }486    }487}488489#[cfg(test)]490mod tests {491    use std::{492        env, fs,493        path::{Path, PathBuf},494    };495496    /// A convenient result type alias.497    pub(crate) type Result<T> =498        std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;499500    macro_rules! err {501        ($($tt:tt)*) => {502            Box::<dyn std::error::Error + Send + Sync>::from(format!($($tt)*))503        }504    }505506    /// A simple wrapper for creating a temporary directory that is507    /// automatically deleted when it's dropped.508    ///509    /// We use this in lieu of tempfile because tempfile brings in too many510    /// dependencies.511    #[derive(Debug)]512    pub struct TempDir(PathBuf);513514    impl Drop for TempDir {515        fn drop(&mut self) {516            fs::remove_dir_all(&self.0).unwrap();517        }518    }519520    impl TempDir {521        /// Create a new empty temporary directory under the system's configured522        /// temporary directory.523        pub fn new() -> Result<TempDir> {524            use std::sync::atomic::{AtomicUsize, Ordering};525526            static TRIES: usize = 100;527            static COUNTER: AtomicUsize = AtomicUsize::new(0);528529            let tmpdir = env::temp_dir();530            for _ in 0..TRIES {531                let count = COUNTER.fetch_add(1, Ordering::Relaxed);532                let path = tmpdir.join("rust-ignore").join(count.to_string());533                if path.is_dir() {534                    continue;535                }536                fs::create_dir_all(&path).map_err(|e| {537                    err!("failed to create {}: {}", path.display(), e)538                })?;539                return Ok(TempDir(path));540            }541            Err(err!("failed to create temp dir after {} tries", TRIES))542        }543544        /// Return the underlying path to this temporary directory.545        pub fn path(&self) -> &Path {546            &self.0547        }548    }549}