Skip to main content

str_format/
ignore.rs

1//! 忽略名单(规范 4.7 `policies.ignore` + `.gitignore` 自动检测)。
2//!
3//! 语义与 gitignore 对齐:
4//! - `#` 注释、空行跳过;`\#` / `\!` 转义;
5//! - `!` 前缀 = 取消忽略(negation);
6//! - 尾随 `/` = 仅匹配目录;
7//! - 模式含 `/`(尾随除外)= 锚定到该 ignore 文件所在目录,否则匹配任意深度的同名条目;
8//! - 同一文件内「最后一条命中的模式」决定结果;
9//! - 多层 ignore 文件(外层 git 仓库 → bundle 根 → 分支目录 → `policies.ignore`)
10//!   由外向内叠加,**内层(更靠近条目 / 显式策略)的命中覆盖外层**。
11//!
12//! 所有匹配均以 **bundle 内相对路径**(`/` 分隔)进行:外层 ignore 文件的锚定模式
13//! 天然只在其覆盖范围内生效(bundle 相对路径是其真路径的后缀),与 git 行为一致。
14
15use globset::{GlobBuilder, GlobMatcher};
16
17/// 单条忽略模式。
18#[derive(Debug, Clone)]
19struct Pattern {
20    /// `!` 前缀:命中则取消忽略。
21    negated: bool,
22    /// 尾随 `/`:仅匹配目录(目录内部由遍历剪枝覆盖)。
23    dir_only: bool,
24    matcher: GlobMatcher,
25}
26
27/// 一份 ignore 来源(`.gitignore` 文件或 `policies.ignore`)的模式表。
28#[derive(Debug, Clone)]
29struct Layer {
30    /// 作用域:bundle 内相对目录(`""` = bundle 根 / 外层仓库层)。分支目录层用。
31    scope: String,
32    /// 外层仓库层专用:bundle 根相对该 ignore 文件所在目录的路径
33    /// (如 bundle 位于 `<repo>/bundles/x.str`、文件在 `<repo>/.gitignore` 时为
34    /// `bundles/x.str`),用于把锚定模式正确翻译到 bundle 相对坐标。
35    prefix: String,
36    patterns: Vec<Pattern>,
37}
38
39/// 系统级忽略层的固定模式(规范 3.4 豁免清单 + `._` 保留命名空间 + `.lock`)。
40const SYSTEM_IGNORE_PATTERNS: &str = "\
41._*
42.lock
43.DS_Store
44Thumbs.db
45desktop.ini
46.git
47.gitignore
48.gitattributes
49.gitmodules
50.gitkeep
51.github
52.hg
53.hgignore
54.svn
55.jj
56";
57
58/// 解析一份 ignore 文本为模式表(gitignore 语义)。
59fn parse_patterns(text: &str) -> Vec<Pattern> {
60    let mut out = Vec::new();
61    for raw in text.lines() {
62        // 去掉行尾空白(git:除非反斜杠转义,此处按常见实现简化为直接去除)。
63        let line = raw.trim_end_matches([' ', '\t']);
64        if line.is_empty() || line.starts_with('#') {
65            continue;
66        }
67        // `\#` / `\!` 转义:去掉反斜杠,保留字面 `#` / `!` 起始的名字。
68        let line = if line.starts_with("\\#") || line.starts_with("\\!") {
69            &line[1..]
70        } else {
71            line
72        };
73        let (negated, line) = match line.strip_prefix('!') {
74            Some(rest) => (true, rest),
75            None => (false, line),
76        };
77        // 尾随 `/` → 仅目录;`/` 去重。
78        let (dir_only, line) = match line.strip_suffix('/') {
79            Some(rest) => (true, rest),
80            None => (false, line),
81        };
82        if line.is_empty() {
83            continue;
84        }
85        // 含 `/`(去掉尾随后)→ 锚定;否则匹配任意深度的同名条目。
86        let anchored = line.contains('/');
87        let line = line.strip_prefix('/').unwrap_or(line);
88        if line.is_empty() {
89            continue;
90        }
91        let glob = if anchored {
92            line.to_string()
93        } else {
94            format!("**/{line}")
95        };
96        if let Ok(m) = GlobBuilder::new(&glob)
97            .literal_separator(true)
98            .case_insensitive(false)
99            .build()
100        {
101            out.push(Pattern {
102                negated,
103                dir_only,
104                matcher: m.compile_matcher(),
105            });
106        }
107    }
108    out
109}
110
111/// bundle 全局的忽略判定器。
112#[derive(Debug, Clone, Default)]
113pub struct IgnoreSet {
114    /// 由外向内叠加的 ignore 层(内层命中覆盖外层)。
115    layers: Vec<Layer>,
116}
117
118impl IgnoreSet {
119    /// 追加一层 bundle 内的 ignore(`scope` = 所在分支目录的 bundle 相对路径,
120    /// bundle 根传 `""`),`text` 为文件内容。
121    pub fn push_layer(&mut self, scope: &str, text: &str) {
122        self.layers.push(Layer {
123            scope: scope.trim_matches('/').to_string(),
124            prefix: String::new(),
125            patterns: parse_patterns(text),
126        });
127    }
128
129    /// 追加一层 bundle 外的 ignore(如外层 git 仓库的 `.gitignore`)。
130    /// `prefix` = bundle 根相对该文件所在目录的路径(ignore 目录为 bundle 祖先时
131    /// 即中间路径;空串表示就是 bundle 根)。
132    pub fn push_outer(&mut self, prefix: &str, text: &str) {
133        self.layers.push(Layer {
134            scope: String::new(),
135            prefix: prefix.trim_matches('/').to_string(),
136            patterns: parse_patterns(text),
137        });
138    }
139
140    /// 追加**系统级忽略层**(规范 4.7):`._meta` / `._schema/` / `._cache/` 与整个
141    /// `._` 保留命名空间、`.lock`,以及 OS / VCS 元数据。该层必须**最后**入栈
142    /// (恒为最内层):不受 `policies.gitignore` 开关影响,用户 `.gitignore` /
143    /// `policies.ignore` 的 `!` 取反**不能**恢复这些条目。
144    pub fn push_system_layer(&mut self) {
145        self.push_layer("", SYSTEM_IGNORE_PATTERNS);
146    }
147
148    /// 是否没有任何生效模式(调用方可据此跳过匹配)。
149    pub fn is_empty(&self) -> bool {
150        self.layers.iter().all(|l| l.patterns.is_empty())
151    }
152
153    /// 判定 bundle 内相对路径 `rel`(`/` 分隔)是否被忽略。
154    pub fn is_ignored(&self, rel: &str, is_dir: bool) -> bool {
155        let mut ignored = false;
156        for layer in &self.layers {
157            // 外层文件:锚定模式相对其所在目录解析 → 加回 bundle 根前缀;
158            // 分支目录层:模式相对该目录解析 → 剥掉作用域前缀。
159            let sub: String = if !layer.prefix.is_empty() {
160                format!("{}/{}", layer.prefix, rel)
161            } else if layer.scope.is_empty() {
162                rel.to_string()
163            } else {
164                let scope = format!("{}/", layer.scope);
165                match rel.strip_prefix(scope.as_str()) {
166                    Some(s) if !s.is_empty() => s.to_string(),
167                    _ => continue,
168                }
169            };
170            // git 语义:同一文件内「最后一条命中的模式」决定;内层文件覆盖外层。
171            let mut decided: Option<bool> = None;
172            for p in &layer.patterns {
173                if p.dir_only && !is_dir {
174                    continue;
175                }
176                if p.matcher.is_match(&sub) {
177                    decided = Some(!p.negated);
178                }
179            }
180            if let Some(d) = decided {
181                ignored = d;
182            }
183        }
184        ignored
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    fn set(layers: &[(&str, &str)]) -> IgnoreSet {
193        let mut s = IgnoreSet::default();
194        for (scope, text) in layers {
195            s.push_layer(scope, text);
196        }
197        s
198    }
199
200    #[test]
201    fn basename_matches_any_depth() {
202        let s = set(&[("", "*.log\nbuild\n")]);
203        assert!(s.is_ignored("a.log", false));
204        assert!(s.is_ignored("x/y/a.log", false));
205        assert!(s.is_ignored("build", true));
206        assert!(s.is_ignored("x/build", true));
207        assert!(!s.is_ignored("builder", true));
208    }
209
210    #[test]
211    fn anchored_and_dir_only() {
212        let s = set(&[("", "logs/\n/foo\nsub/bar.txt\n")]);
213        assert!(s.is_ignored("logs", true));
214        assert!(s.is_ignored("a/logs", true));
215        assert!(!s.is_ignored("logs", false)); // 目录专用模式不匹配文件
216        assert!(s.is_ignored("foo", false));
217        assert!(!s.is_ignored("x/foo", false)); // 锚定:仅 bundle 根下的 foo
218        assert!(s.is_ignored("sub/bar.txt", false));
219        assert!(!s.is_ignored("other/bar.txt", false));
220    }
221
222    #[test]
223    fn last_match_and_negation() {
224        let s = set(&[("", "*.log\n!keep.log\n")]);
225        assert!(s.is_ignored("a.log", false));
226        assert!(!s.is_ignored("keep.log", false));
227    }
228
229    #[test]
230    fn inner_layer_overrides_outer() {
231        // 外层忽略全部 .tmp;bundle 根的 .gitignore 取消忽略 final.tmp。
232        let s = set(&[("", "*.tmp\n"), ("", "!final.tmp\n")]);
233        assert!(s.is_ignored("a.tmp", false));
234        assert!(!s.is_ignored("final.tmp", false));
235    }
236
237    #[test]
238    fn scope_limits_layer() {
239        // 作用域在分支 a/b/ 的层只影响其子树。
240        let s = set(&[("a/b", "cache\n")]);
241        assert!(s.is_ignored("a/b/cache", true));
242        assert!(!s.is_ignored("a/cache", true));
243        assert!(!s.is_ignored("cache", true));
244    }
245
246    #[test]
247    fn comments_and_escapes() {
248        let s = set(&[("", "# 注释\n\\#hash.txt\n")]);
249        assert!(!s.is_ignored("hash.txt", false));
250        assert!(s.is_ignored("#hash.txt", false));
251    }
252
253    #[test]
254    fn system_layer_is_innermost_and_unresurrectable() {
255        let mut s = IgnoreSet::default();
256        // 用户层尝试用取反恢复系统条目 → 系统层(最内层)覆盖回来。
257        s.push_layer("", "!._cache\n!._meta\n!._schema\n");
258        s.push_system_layer();
259        assert!(s.is_ignored("._meta", false));
260        assert!(s.is_ignored("._schema", true));
261        assert!(s.is_ignored("._cache", true));
262        assert!(s.is_ignored("a/._cache", true));
263        assert!(s.is_ignored(".DS_Store", false));
264        assert!(s.is_ignored(".git", true));
265        assert!(s.is_ignored("x/.lock", false));
266        // 系统层不影响普通条目判定。
267        assert!(!s.is_ignored("data.json", false));
268    }
269
270    #[test]
271    fn outer_layer_anchoring() {
272        let mut s = IgnoreSet::default();
273        // bundle 在 <repo>/bundles/x.str;repo 根 .gitignore 有锚定 /target 与 basename *.log。
274        s.push_outer("bundles/x.str", "/target\n*.log\n");
275        // 锚定模式只作用于 <repo>/target,不影响 bundle 内的 target。
276        assert!(!s.is_ignored("target", true));
277        // basename 模式任意深度生效。
278        assert!(s.is_ignored("a/b/c.log", false));
279        // 锚定模式命中 bundle 内条目(真实路径 <repo>/bundles/x.str/foo)。
280        let mut s2 = IgnoreSet::default();
281        s2.push_outer("bundles/x.str", "/bundles/x.str/foo\n");
282        assert!(s2.is_ignored("foo", false));
283    }
284}