]> git.lizzy.rs Git - rust.git/blob - src/ignore_path.rs
Merge pull request #3511 from topecongiro/issue3498
[rust.git] / src / ignore_path.rs
1 use ignore::{self, gitignore};
2 use std::path::PathBuf;
3
4 use crate::config::{FileName, IgnoreList};
5
6 pub struct IgnorePathSet {
7     ignore_set: gitignore::Gitignore,
8 }
9
10 impl IgnorePathSet {
11     pub fn from_ignore_list(ignore_list: &IgnoreList) -> Result<Self, ignore::Error> {
12         let mut ignore_builder = gitignore::GitignoreBuilder::new(PathBuf::from(""));
13
14         for ignore_path in ignore_list {
15             ignore_builder.add_line(None, ignore_path.to_str().unwrap())?;
16         }
17
18         Ok(IgnorePathSet {
19             ignore_set: ignore_builder.build()?,
20         })
21     }
22
23     pub fn is_match(&self, file_name: &FileName) -> bool {
24         match file_name {
25             FileName::Stdin => false,
26             FileName::Real(p) => self
27                 .ignore_set
28                 .matched_path_or_any_parents(p, false)
29                 .is_ignore(),
30         }
31     }
32 }
33
34 #[cfg(test)]
35 mod test {
36     use crate::config::{Config, FileName};
37     use crate::ignore_path::IgnorePathSet;
38     use std::path::PathBuf;
39
40     #[test]
41     fn test_ignore_path_set() {
42         match option_env!("CFG_RELEASE_CHANNEL") {
43             // this test requires nightly
44             None | Some("nightly") => {
45                 let config = Config::from_toml(r#"ignore = ["foo.rs", "bar_dir/*"]"#).unwrap();
46                 let ignore_path_set = IgnorePathSet::from_ignore_list(&config.ignore()).unwrap();
47
48                 assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/foo.rs"))));
49                 assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/baz.rs"))));
50                 assert!(!ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/bar.rs"))));
51             }
52             _ => (),
53         };
54     }
55 }