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    /// Number of compiled patterns (used to detect "comments only" files).
129    pub fn len(&self) -> usize {
130        self.patterns.len()
131    }
132
133    /// True when no patterns were compiled.
134    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        // Documented git parity: children under an ignored dir are never
184        // re-included — the walker prunes on the dir verdict.
185        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        // compile_raw keeps `\` literal; this pattern can never match a
211        // normal component, but it must COMPILE (no normalization).
212        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}