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