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
use std::path::Path;

pub struct Ignorer {
    ignorer: ignore::gitignore::Gitignore,
}

static AUTOCORRECTIGNORE: &str = ".autocorrectignore";
static GITIGNORE: &str = ".gitignore";

impl Ignorer {
    pub fn new(work_dir: &str) -> Ignorer {
        let mut builder = ignore::gitignore::GitignoreBuilder::new(work_dir);
        builder.add(Path::join(Path::new(work_dir), AUTOCORRECTIGNORE));
        builder.add(Path::join(Path::new(work_dir), GITIGNORE));
        let ignorer = builder.build().unwrap();

        // println!("---- {:?}", ignorer.len());

        Ignorer { ignorer }
    }

    pub fn is_ignored(&self, path: &str) -> bool {
        self.ignorer
            .matched_path_or_any_parents(path, false)
            .is_ignore()
            || self
                .ignorer
                .matched_path_or_any_parents(path, true)
                .is_ignore()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_ignored() {
        let current_dir = std::env::current_dir().unwrap();
        let work_dir = current_dir.parent().unwrap().to_str().unwrap();
        // println!("-- work_dir: {:?}", work_dir);
        let ignorer = Ignorer::new(work_dir);
        assert!(ignorer.is_ignored("src/main.rs"));
        assert!(ignorer.is_ignored("pkg/foo/bar"));
        assert!(ignorer.is_ignored("node_modules/@huacnlee/autocorrect/index.js"));
        assert!(!ignorer.is_ignored("example/index.js"));
        assert!(!ignorer.is_ignored("example/package.json"));
        assert!(ignorer.is_ignored("test/fixtures/this-file-will-ignore.rs"));
    }
}