1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#![doc = include_str!("../README.md")]

use {
    anyhow::{anyhow, Result},
    ignore::gitignore::{gitconfig_excludes_path, Gitignore, GitignoreBuilder},
    std::{
        collections::BTreeSet,
        path::{Path, PathBuf},
    },
};

/// Check if a path is ignored
pub fn ignored(path: impl AsRef<Path>) -> Result<bool> {
    Ok(Ignore::new(path.as_ref().parent().unwrap())?.check(path))
}

pub struct Ignore {
    matcher: Gitignore,
}

impl Default for Ignore {
    fn default() -> Ignore {
        Ignore::new("").unwrap()
    }
}

impl Ignore {
    pub fn new(root: impl AsRef<Path>) -> Result<Ignore> {
        let mut builder = GitignoreBuilder::new(&root);

        // Add local `.gitignore` file(s)
        let mut added = BTreeSet::new();
        let mut dir = root.as_ref().to_path_buf();
        loop {
            add_path(dir.join(".gitignore"), &mut builder, &mut added)?;

            if let Some(parent) = dir.parent() {
                dir = parent.to_path_buf();
            } else {
                break;
            }
        }

        // Add global (user) excludes path (`~/.gitignore`)
        if let Some(path) = gitconfig_excludes_path() {
            add_path(path, &mut builder, &mut added)?;
        }

        Ok(Ignore {
            matcher: builder.build()?,
        })
    }

    pub fn check(&self, path: impl AsRef<Path>) -> bool {
        self.matcher
            .matched_path_or_any_parents(&path, path.as_ref().is_dir())
            .is_ignore()
    }
}

fn add_path(
    path: PathBuf,
    builder: &mut GitignoreBuilder,
    added: &mut BTreeSet<PathBuf>,
) -> Result<()> {
    if path.exists() && !added.contains(&path) {
        match builder.add(&path) {
            Some(e) => Err(anyhow!("Failed to add {path:?}: {e}")),
            None => {
                added.insert(path);
                Ok(())
            }
        }
    } else {
        Ok(())
    }
}