Skip to main content

utf8_forge/
ignorefile.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Gitignore-style exclusion files (`--ignore-file` / auto-discovered
16//! `<root>/.utf8forgeignore`).
17//!
18//! Supported syntax (a deliberate subset, no escapes — a backslash is a
19//! literal character):
20//! - blank lines and `#` comments are skipped;
21//! - a trailing `/` marks a dir-only pattern;
22//! - a leading `/` (or any `/` inside the pattern) anchors it to the
23//!   root-relative path; a pattern without `/` matches the basename at any
24//!   depth;
25//! - `!` negates; the LAST matching pattern wins (gitignore ordering);
26//! - `**` spans path components, `*` / `?` match within one component;
27//!   matching is case-insensitive like every other matcher in this tool.
28//!
29//! Limitation inherited from git: a file cannot be re-included (`!`) when its
30//! parent directory is excluded — the walker prunes the subtree on the
31//! directory verdict and children are never evaluated.
32
33use std::fs;
34use std::path::Path;
35
36use crate::filter::Glob;
37
38/// One compiled ignore-file line.
39#[derive(Debug, Clone)]
40pub struct IgnorePattern {
41    /// Compiled matcher for the effective pattern (negation / dir marker
42    /// stripped, leading `/` removed, lowercased, star-collapsed).
43    glob: Glob,
44    /// `!pattern` — flips the verdict when this is the last match.
45    negated: bool,
46    /// `pattern/` — applies to directories only.
47    dir_only: bool,
48    /// Pattern is anchored to the root-relative path (leading or inner `/`).
49    anchored: bool,
50}
51
52/// A parsed ignore file: patterns in file order, last-match-wins.
53#[derive(Debug, Clone, Default)]
54pub struct IgnoreFile {
55    patterns: Vec<IgnorePattern>,
56}
57
58impl IgnoreFile {
59    /// Parse and compile the file at `path`. `Err` names the 1-based line
60    /// number for invalid patterns (empty effective pattern, lone `/` or `!`).
61    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    /// Parse ignore rules from raw text (exposed for tests).
68    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    /// Last-match-wins verdict for a root-relative path split into
102    /// components. `true` = ignored, `false` = kept (including "no pattern
103    /// matched").
104    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            // Gitignore anchoring: a pattern without any `/` matches the
111            // basename at any depth; an anchored pattern matches the full
112            // root-relative path.
113            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
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    fn ign(text: &str, path: &str, is_dir: bool) -> bool {
134        let f = IgnoreFile::parse(text).unwrap();
135        let comps: Vec<&str> = path.split('/').collect();
136        f.ignores(&comps, is_dir)
137    }
138
139    #[test]
140    fn dir_only_pattern_matches_any_depth() {
141        assert!(ign("logs/", "logs", true));
142        assert!(ign("logs/", "a/b/logs", true));
143        assert!(!ign("logs/", "logs/a.cpp", false));
144        assert!(!ign("logs/", "a.cpp", false));
145    }
146
147    #[test]
148    fn basename_pattern_matches_at_any_depth() {
149        assert!(ign("*.log", "x.log", false));
150        assert!(ign("*.log", "a/b/x.log", false));
151        assert!(!ign("*.log", "x.cpp", false));
152    }
153
154    #[test]
155    fn anchored_pattern_matches_only_at_root() {
156        assert!(ign("/Generated", "Generated", true));
157        assert!(!ign("/Generated", "a/Generated", true));
158        assert!(ign("build/*.cpp", "build/x.cpp", false));
159        assert!(!ign("build/*.cpp", "a/build/x.cpp", false));
160    }
161
162    #[test]
163    fn negation_is_last_match_wins() {
164        let text = "*.log\n!keep.log";
165        assert!(ign(text, "a/drop.log", false));
166        assert!(!ign(text, "a/keep.log", false));
167        let text = "build/\n!build/";
168        assert!(!ign(text, "build", true), "negated dir is traversable");
169    }
170
171    #[test]
172    fn parent_dir_exclusion_cannot_be_negated_for_children() {
173        // Documented git parity: children under an ignored dir are never
174        // re-included — the walker prunes on the dir verdict.
175        let text = "build/\n!build/keep.cpp";
176        assert!(ign(text, "build", true));
177    }
178
179    #[test]
180    fn comments_blank_lines_and_crlf() {
181        let f = IgnoreFile::parse("# comment\r\n\r\n*.tmp\r\n").unwrap();
182        // The comment line produced no pattern: a non-matching path stays
183        // kept while the *.tmp rule still applies.
184        assert!(!f.ignores(&["keep.txt"], false));
185        let comps: Vec<&str> = "x.tmp".split('/').collect();
186        assert!(f.ignores(&comps, false));
187    }
188
189    #[test]
190    fn empty_effective_patterns_are_line_numbered_errors() {
191        assert!(IgnoreFile::parse("/").unwrap_err().contains("line 1"));
192        assert!(IgnoreFile::parse("!").unwrap_err().contains("line 1"));
193        assert!(
194            IgnoreFile::parse("*.tmp\n!")
195                .unwrap_err()
196                .contains("line 2")
197        );
198    }
199
200    #[test]
201    fn backslash_is_a_literal_not_a_separator() {
202        // compile_raw keeps `\` literal; this pattern can never match a
203        // normal component, but it must COMPILE (no normalization).
204        assert!(IgnoreFile::parse("a\\b").is_ok());
205        assert!(!ign("a\\b", "a/b", false));
206    }
207
208    #[test]
209    fn negation_and_dir_only_patterns_honor_crlf() {
210        let text = "*.log\r\n!keep.log\r\n";
211        assert!(ign(text, "drop.log", false));
212        assert!(!ign(text, "keep.log", false));
213        assert!(ign("logs/\r\n", "logs", true));
214        assert!(!ign("logs/\r\n", "logs/a.cpp", 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}