1use std::fs;
34use std::path::Path;
35
36use crate::filter::Glob;
37
38#[derive(Debug, Clone)]
40pub struct IgnorePattern {
41 glob: Glob,
44 negated: bool,
46 dir_only: bool,
48 anchored: bool,
50}
51
52#[derive(Debug, Clone, Default)]
54pub struct IgnoreFile {
55 patterns: Vec<IgnorePattern>,
56}
57
58impl IgnoreFile {
59 pub fn load(path: &Path) -> Result<IgnoreFile, String> {
62 let text = fs::read_to_string(path)
63 .map_err(|e| format!("cannot read ignore file `{}`: {e}", path.display()))?;
64 Self::parse(&text)
65 }
66
67 pub fn parse(text: &str) -> Result<IgnoreFile, String> {
69 let mut patterns = Vec::new();
70 for (idx, raw_line) in text.lines().enumerate() {
71 let line = raw_line.trim();
72 if line.is_empty() || line.starts_with('#') {
73 continue;
74 }
75 let mut rest = line;
76 let negated = rest.starts_with('!');
77 if negated {
78 rest = &rest[1..];
79 }
80 let dir_only = rest.ends_with('/');
81 if dir_only {
82 rest = rest.trim_end_matches('/');
83 }
84 let anchored = rest.contains('/');
85 let rest = rest.trim_start_matches('/');
86 if rest.is_empty() {
87 return Err(format!("ignore file line {}: empty pattern", idx + 1));
88 }
89 let glob = Glob::compile_raw(rest)
90 .map_err(|e| format!("ignore file line {}: {e}", idx + 1))?;
91 patterns.push(IgnorePattern {
92 glob,
93 negated,
94 dir_only,
95 anchored,
96 });
97 }
98 Ok(IgnoreFile { patterns })
99 }
100
101 pub fn ignores(&self, rel: &[&str], is_dir: bool) -> bool {
105 let mut verdict = false;
106 for pat in &self.patterns {
107 if pat.dir_only && !is_dir {
108 continue;
109 }
110 let candidate: Vec<&str> = if pat.anchored {
114 rel.to_vec()
115 } else {
116 match rel.last() {
117 Some(base) => vec![base],
118 None => continue,
119 }
120 };
121 if pat.glob.matches(&candidate) {
122 verdict = !pat.negated;
123 }
124 }
125 verdict
126 }
127
128 pub fn len(&self) -> usize {
130 self.patterns.len()
131 }
132
133 pub fn is_empty(&self) -> bool {
135 self.patterns.is_empty()
136 }
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 fn ign(text: &str, path: &str, is_dir: bool) -> bool {
144 let f = IgnoreFile::parse(text).unwrap();
145 let comps: Vec<&str> = path.split('/').collect();
146 f.ignores(&comps, is_dir)
147 }
148
149 #[test]
150 fn dir_only_pattern_matches_any_depth() {
151 assert!(ign("logs/", "logs", true));
152 assert!(ign("logs/", "a/b/logs", true));
153 assert!(!ign("logs/", "logs/a.cpp", false));
154 assert!(!ign("logs/", "a.cpp", false));
155 }
156
157 #[test]
158 fn basename_pattern_matches_at_any_depth() {
159 assert!(ign("*.log", "x.log", false));
160 assert!(ign("*.log", "a/b/x.log", false));
161 assert!(!ign("*.log", "x.cpp", false));
162 }
163
164 #[test]
165 fn anchored_pattern_matches_only_at_root() {
166 assert!(ign("/Generated", "Generated", true));
167 assert!(!ign("/Generated", "a/Generated", true));
168 assert!(ign("build/*.cpp", "build/x.cpp", false));
169 assert!(!ign("build/*.cpp", "a/build/x.cpp", false));
170 }
171
172 #[test]
173 fn negation_is_last_match_wins() {
174 let text = "*.log\n!keep.log";
175 assert!(ign(text, "a/drop.log", false));
176 assert!(!ign(text, "a/keep.log", false));
177 let text = "build/\n!build/";
178 assert!(!ign(text, "build", true), "negated dir is traversable");
179 }
180
181 #[test]
182 fn parent_dir_exclusion_cannot_be_negated_for_children() {
183 let text = "build/\n!build/keep.cpp";
186 assert!(ign(text, "build", true));
187 }
188
189 #[test]
190 fn comments_blank_lines_and_crlf() {
191 let f = IgnoreFile::parse("# comment\r\n\r\n*.tmp\r\n").unwrap();
192 assert_eq!(f.len(), 1);
193 let comps: Vec<&str> = "x.tmp".split('/').collect();
194 assert!(f.ignores(&comps, false));
195 }
196
197 #[test]
198 fn empty_effective_patterns_are_line_numbered_errors() {
199 assert!(IgnoreFile::parse("/").unwrap_err().contains("line 1"));
200 assert!(IgnoreFile::parse("!").unwrap_err().contains("line 1"));
201 assert!(
202 IgnoreFile::parse("*.tmp\n!")
203 .unwrap_err()
204 .contains("line 2")
205 );
206 }
207
208 #[test]
209 fn backslash_is_a_literal_not_a_separator() {
210 let f = IgnoreFile::parse("a\\b").unwrap();
213 assert_eq!(f.len(), 1);
214 assert!(!ign("a\\b", "a/b", false));
215 }
216
217 #[test]
218 fn double_star_spans_components() {
219 assert!(ign("**/Generated/**", "a/Generated/x.cpp", false));
220 assert!(ign("**/Generated/**", "Generated/y.cpp", false));
221 }
222}