]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/ignore_path.rs
Rollup merge of #84758 - ChrisDenton:dllimport, r=dtolnay
[rust.git] / src / tools / rustfmt / src / ignore_path.rs
1 use ignore::{self, gitignore};
2
3 use crate::config::{FileName, IgnoreList};
4
5 pub(crate) struct IgnorePathSet {
6     ignore_set: gitignore::Gitignore,
7 }
8
9 impl IgnorePathSet {
10     pub(crate) fn from_ignore_list(ignore_list: &IgnoreList) -> Result<Self, ignore::Error> {
11         let mut ignore_builder = gitignore::GitignoreBuilder::new(ignore_list.rustfmt_toml_path());
12
13         for ignore_path in ignore_list {
14             ignore_builder.add_line(None, ignore_path.to_str().unwrap())?;
15         }
16
17         Ok(IgnorePathSet {
18             ignore_set: ignore_builder.build()?,
19         })
20     }
21
22     pub(crate) fn is_match(&self, file_name: &FileName) -> bool {
23         match file_name {
24             FileName::Stdin => false,
25             FileName::Real(p) => self
26                 .ignore_set
27                 .matched_path_or_any_parents(p, false)
28                 .is_ignore(),
29         }
30     }
31 }
32
33 #[cfg(test)]
34 mod test {
35     use std::path::{Path, PathBuf};
36
37     use crate::config::{Config, FileName};
38     use crate::ignore_path::IgnorePathSet;
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 =
46                     Config::from_toml(r#"ignore = ["foo.rs", "bar_dir/*"]"#, Path::new(""))
47                         .unwrap();
48                 let ignore_path_set = IgnorePathSet::from_ignore_list(&config.ignore()).unwrap();
49
50                 assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/foo.rs"))));
51                 assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/baz.rs"))));
52                 assert!(!ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/bar.rs"))));
53             }
54             _ => (),
55         };
56     }
57 }