helm_rs/chart/ignore/
mod.rs1pub const HELM_IGNORE: &str = ".helmignore";
9
10#[derive(Debug, thiserror::Error)]
12pub enum IgnoreError {
13 #[error("double-star (**) syntax is not supported")]
15 DoubleStar,
16 #[error("syntax error in pattern: {0:?}")]
18 BadPattern(String),
19}
20
21#[derive(Debug, Default)]
23pub struct Rules {
24 patterns: Vec<Pattern>,
25}
26
27#[derive(Debug)]
29struct Pattern {
30 glob: String,
31 negate: bool,
32 must_dir: bool,
33 scope: Scope,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38enum Scope {
39 Name,
41 Path,
43 Root,
45}
46
47impl Rules {
48 #[must_use]
50 pub fn empty() -> Self {
51 Self::default()
52 }
53
54 pub fn add_defaults(&mut self) {
59 self.parse_rule("templates/.?*")
60 .expect("the default rule is valid");
61 }
62
63 pub fn parse(text: &str) -> Result<Self, IgnoreError> {
68 let mut rules = Self::empty();
69 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
70
71 for line in text.lines() {
72 rules.parse_rule(line)?;
73 }
74
75 Ok(rules)
76 }
77
78 #[must_use]
83 pub fn ignore(&self, path: &str, is_dir: bool) -> bool {
84 if path.is_empty() || path == "." || path == "./" {
85 return false;
86 }
87
88 for pattern in &self.patterns {
89 if pattern.negate {
90 if pattern.must_dir && !is_dir {
91 return true;
92 }
93 if !pattern.matches(path) {
94 return true;
95 }
96
97 continue;
98 }
99 if pattern.must_dir && !is_dir {
100 continue;
101 }
102 if pattern.matches(path) {
103 return true;
104 }
105 }
106
107 false
108 }
109
110 fn parse_rule(&mut self, rule: &str) -> Result<(), IgnoreError> {
112 let rule = rule.trim();
113
114 if rule.is_empty() || rule.starts_with('#') {
115 return Ok(());
116 }
117 if rule.contains("**") {
118 return Err(IgnoreError::DoubleStar);
119 }
120 if glob_match(rule, "abc").is_err() {
121 return Err(IgnoreError::BadPattern(rule.to_owned()));
122 }
123
124 let mut glob = rule;
125 let negate = glob.starts_with('!');
126
127 if negate {
128 glob = &glob[1..];
129 }
130
131 let must_dir = glob.ends_with('/');
132
133 if must_dir {
134 glob = &glob[..glob.len() - 1];
135 }
136
137 let anchored = glob.starts_with('/');
138
139 if anchored {
140 glob = &glob[1..];
141 }
142
143 let scope = match (anchored, glob.contains('/')) {
144 (true, _) => Scope::Root,
145 (false, true) => Scope::Path,
146 (false, false) => Scope::Name,
147 };
148
149 self.patterns.push(Pattern {
150 glob: glob.to_owned(),
151 negate,
152 must_dir,
153 scope,
154 });
155
156 Ok(())
157 }
158}
159
160impl Pattern {
161 fn matches(&self, path: &str) -> bool {
163 let name = if self.scope == Scope::Name {
164 go_base(path)
165 } else {
166 path
167 };
168
169 glob_match(&self.glob, name).unwrap_or(false)
170 }
171}
172
173#[derive(Debug)]
175pub(crate) struct BadPattern;
176
177fn go_base(path: &str) -> &str {
179 let trimmed = path.trim_end_matches('/');
180
181 match trimmed.rsplit('/').next() {
182 Some("") | None if path.is_empty() => ".",
183 Some("") | None => "/",
184 Some(last) => last,
185 }
186}
187
188fn scan_chunk(pattern: &[char]) -> (bool, &[char], &[char]) {
190 let stars = pattern.iter().take_while(|c| **c == '*').count();
191 let pattern = &pattern[stars..];
192 let mut in_range = false;
193 let mut i = 0;
194
195 while i < pattern.len() {
196 match pattern[i] {
197 '\\' if i + 1 < pattern.len() => i += 1,
198 '[' => in_range = true,
199 ']' => in_range = false,
200 '*' if !in_range => break,
201 _ => {}
202 }
203 i += 1;
204 }
205
206 (stars > 0, &pattern[..i], &pattern[i..])
207}
208
209fn get_esc(chunk: &[char]) -> Result<(char, &[char]), BadPattern> {
211 let mut chunk = chunk;
212
213 if chunk.is_empty() || chunk[0] == '-' || chunk[0] == ']' {
214 return Err(BadPattern);
215 }
216 if chunk[0] == '\\' {
217 chunk = &chunk[1..];
218
219 if chunk.is_empty() {
220 return Err(BadPattern);
221 }
222 }
223
224 let rest = &chunk[1..];
225
226 if rest.is_empty() {
227 return Err(BadPattern);
228 }
229
230 Ok((chunk[0], rest))
231}
232
233fn match_chunk<'a>(chunk: &[char], s: &'a [char]) -> Result<Option<&'a [char]>, BadPattern> {
235 let mut chunk = chunk;
236 let mut s = s;
237 let mut failed = false;
238
239 while !chunk.is_empty() {
240 if !failed && s.is_empty() {
241 failed = true;
242 }
243
244 match chunk[0] {
245 '[' => {
246 let mut r = '\0';
247
248 if !failed {
249 r = s[0];
250 s = &s[1..];
251 }
252 chunk = &chunk[1..];
253
254 let negated = chunk.first() == Some(&'^');
255
256 if negated {
257 chunk = &chunk[1..];
258 }
259
260 let mut matched = false;
261 let mut ranges = 0;
262
263 loop {
264 if chunk.first() == Some(&']') && ranges > 0 {
265 chunk = &chunk[1..];
266 break;
267 }
268
269 let (lo, rest) = get_esc(chunk)?;
270 let mut hi = lo;
271
272 chunk = rest;
273 if chunk[0] == '-' {
274 let (h, rest) = get_esc(&chunk[1..])?;
275
276 hi = h;
277 chunk = rest;
278 }
279 if lo <= r && r <= hi {
280 matched = true;
281 }
282 ranges += 1;
283 }
284 if matched == negated {
285 failed = true;
286 }
287 }
288 '?' => {
289 if !failed {
290 if s[0] == '/' {
291 failed = true;
292 }
293 s = &s[1..];
294 }
295 chunk = &chunk[1..];
296 }
297 c => {
298 if c == '\\' {
299 chunk = &chunk[1..];
300
301 if chunk.is_empty() {
302 return Err(BadPattern);
303 }
304 }
305 if !failed {
306 if chunk[0] != s[0] {
307 failed = true;
308 }
309 s = &s[1..];
310 }
311 chunk = &chunk[1..];
312 }
313 }
314 }
315
316 Ok((!failed).then_some(s))
317}
318
319pub(crate) fn glob_match(pattern: &str, name: &str) -> Result<bool, BadPattern> {
321 let mut pattern: &[char] = &pattern.chars().collect::<Vec<_>>();
322 let mut name: &[char] = &name.chars().collect::<Vec<_>>();
323
324 'pattern: while !pattern.is_empty() {
325 let (star, chunk, rest) = scan_chunk(pattern);
326
327 pattern = rest;
328 if star && chunk.is_empty() {
329 return Ok(!name.contains(&'/'));
330 }
331
332 let attempt = match_chunk(chunk, name);
333
334 if let Ok(Some(tail)) = attempt
335 && (tail.is_empty() || !pattern.is_empty())
336 {
337 name = tail;
338 continue;
339 }
340 attempt?;
341 if star {
342 let mut i = 0;
343
344 while i < name.len() && name[i] != '/' {
345 let skipped = match_chunk(chunk, &name[i + 1..]);
346
347 if let Ok(Some(tail)) = skipped {
348 if pattern.is_empty() && !tail.is_empty() {
349 i += 1;
350 continue;
351 }
352 name = tail;
353 continue 'pattern;
354 }
355 skipped?;
356 i += 1;
357 }
358 }
359 while !pattern.is_empty() {
360 let (_, chunk, rest) = scan_chunk(pattern);
361
362 pattern = rest;
363 match_chunk(chunk, &[])?;
364 }
365
366 return Ok(false);
367 }
368
369 Ok(name.is_empty())
370}
371
372#[cfg(test)]
373mod tests;