rustfmt_nightly/
ignore_path.rs

1use ignore::gitignore;
2
3use crate::config::{FileName, IgnoreList};
4
5pub(crate) struct IgnorePathSet {
6    ignore_set: gitignore::Gitignore,
7}
8
9impl 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)]
34mod test {
35    use rustfmt_config_proc_macro::nightly_only_test;
36
37    #[nightly_only_test]
38    #[test]
39    fn test_ignore_path_set() {
40        use crate::config::{Config, FileName};
41        use crate::ignore_path::IgnorePathSet;
42        use std::path::{Path, PathBuf};
43
44        let config = Config::from_toml(
45            r#"ignore = ["foo.rs", "bar_dir/*"]"#,
46            Path::new("./rustfmt.toml"),
47        )
48        .unwrap();
49        let ignore_path_set = IgnorePathSet::from_ignore_list(&config.ignore()).unwrap();
50
51        assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/foo.rs"))));
52        assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/baz.rs"))));
53        assert!(!ignore_path_set.is_match(&FileName::Real(PathBuf::from("src/bar.rs"))));
54    }
55
56    #[nightly_only_test]
57    #[test]
58    fn test_negated_ignore_path_set() {
59        use crate::config::{Config, FileName};
60        use crate::ignore_path::IgnorePathSet;
61        use std::path::{Path, PathBuf};
62
63        let config = Config::from_toml(
64            r#"ignore = ["foo.rs", "bar_dir/*", "!bar_dir/*/what.rs"]"#,
65            Path::new("./rustfmt.toml"),
66        )
67        .unwrap();
68        let ignore_path_set = IgnorePathSet::from_ignore_list(&config.ignore()).unwrap();
69        assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/what.rs"))));
70        assert!(ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/baz/a.rs"))));
71        assert!(!ignore_path_set.is_match(&FileName::Real(PathBuf::from("bar_dir/baz/what.rs"))));
72    }
73}