Skip to main content

str_format/
bundle.rs

1//! bundle 遍历与索引。
2//!
3//! 「分支」的唯一判据是**该目录是否含 `._meta`**(规范 3.4 / 4.6);
4//! 层级关系由「目录结构 + 父级 `entries`」唯一决定(规范 5.1)。
5
6use std::collections::{HashMap, VecDeque};
7use std::path::{Path, PathBuf};
8
9use crate::error::{Error, Issue, Result, code};
10use crate::ignore::IgnoreSet;
11use crate::meta::{Meta, MetaLoad, load};
12use crate::util::{self, META_FILE};
13
14/// 下钻硬上限(防止病态目录结构导致遍历失控;策略级 `max_depth` 由校验器判定)。
15pub const HARD_MAX_DEPTH: usize = 128;
16
17/// 一处被访问到的分支目录。
18pub struct Visit {
19    /// 目录绝对/原始路径。
20    pub dir: PathBuf,
21    /// bundle 内相对路径(ROOT 为 `.`)。
22    pub rel: String,
23    /// 深度(ROOT = 0)。
24    pub depth: usize,
25    /// 解析结果;`None` 表示 `._meta` 解析失败。
26    pub meta: Option<Box<Meta>>,
27    /// 父分支在 `visits` 中的下标。
28    pub parent: Option<usize>,
29    /// 原始 `._meta` 文本是否读取成功。
30    pub readable: bool,
31}
32
33/// 一次完整扫描的结果。
34pub struct Scan {
35    /// bundle 根目录。
36    pub root: PathBuf,
37    /// 全部分支目录(下标 0 为 ROOT,若存在)。
38    pub visits: Vec<Visit>,
39    /// 扫描阶段产生的问题(解析层)。
40    pub issues: Vec<Issue>,
41    /// `id` → `visits` 下标列表(用于重复检测与引用解析)。
42    pub by_id: HashMap<String, Vec<usize>>,
43    /// ROOT 是否成功解析。
44    pub root_index: Option<usize>,
45    /// 实测最大深度。
46    pub max_depth: usize,
47    /// 本次扫描生效的忽略名单(`policies.ignore` + `.gitignore`,规范 4.7)。
48    pub ignore: IgnoreSet,
49}
50
51impl Scan {
52    /// 按 `id` 解析分支下标(首次命中)。
53    pub fn resolve(&self, id: &str) -> Option<usize> {
54        self.by_id.get(id).and_then(|v| v.first().copied())
55    }
56
57    /// 分支的完整链条(从 ROOT 到自身)。
58    pub fn ancestors(&self, mut idx: usize) -> Vec<usize> {
59        let mut out = vec![idx];
60        while let Some(p) = self.visits[idx].parent {
61            out.push(p);
62            idx = p;
63        }
64        out.reverse();
65        out
66    }
67}
68
69/// 一个 `.str` bundle。
70#[derive(Debug, Clone)]
71pub struct Bundle {
72    /// 根目录。
73    pub root: PathBuf,
74}
75
76impl Bundle {
77    /// 构造并确认路径存在且为目录。
78    pub fn new(root: impl Into<PathBuf>) -> Result<Self> {
79        let root = root.into();
80        if !root.exists() {
81            return Err(Error::NotFound(root.display().to_string()));
82        }
83        if !root.is_dir() {
84            return Err(Error::BadArg(format!(
85                "{} 不是目录(`.str` 是目录 bundle)",
86                root.display()
87            )));
88        }
89        // 归一化为绝对路径:否则以 `.` / `..` 形式传入时取不到目录名,
90        // 会误报 `W_BUNDLE_SUFFIX`(`str validate .` 的实际场景)。
91        let root = std::fs::canonicalize(&root).map_err(|e| Error::io(&root, e))?;
92        Ok(Self { root })
93    }
94
95    /// bundle 目录名(不含路径)。
96    pub fn name(&self) -> String {
97        self.root
98            .file_name()
99            .map(|s| s.to_string_lossy().to_string())
100            .unwrap_or_else(|| self.root.display().to_string())
101    }
102
103    /// 某目录下 `._meta` 的路径。
104    pub fn meta_path(&self, dir: &Path) -> PathBuf {
105        dir.join(META_FILE)
106    }
107
108    /// 某目录是否含 `._meta`(即是否为分支)。
109    pub fn has_meta(&self, dir: &Path) -> bool {
110        self.meta_path(dir).is_file()
111    }
112
113    /// 相对路径显示。
114    pub fn rel(&self, path: &Path) -> String {
115        util::rel_display(&self.root, path)
116    }
117
118    /// 读取并解析某目录的 `._meta`。
119    pub fn read_meta(&self, dir: &Path) -> Result<MetaLoad> {
120        let p = self.meta_path(dir);
121        let rel = self.rel(&p);
122        load(&p, &rel)
123    }
124
125    /// 列出目录内全部条目 `(名字, 是否目录)`,按名字排序。
126    pub fn list_names(&self, dir: &Path) -> Result<Vec<(String, bool)>> {
127        let mut out = Vec::new();
128        let rd = std::fs::read_dir(dir).map_err(|e| Error::io(dir, e))?;
129        for ent in rd {
130            let ent = ent.map_err(|e| Error::io(dir, e))?;
131            let name = ent.file_name().to_string_lossy().to_string();
132            let is_dir = ent
133                .file_type()
134                .map(|t| t.is_dir())
135                .unwrap_or(false);
136            out.push((name, is_dir));
137        }
138        out.sort();
139        Ok(out)
140    }
141
142    /// 仅列出子目录。
143    pub fn child_dirs(&self, dir: &Path) -> Result<Vec<PathBuf>> {
144        Ok(self
145            .list_names(dir)?
146            .into_iter()
147            .filter(|(_, is_dir)| *is_dir)
148            .map(|(n, _)| dir.join(n))
149            .collect())
150    }
151
152    /// 在**非分支**目录中查找是否藏有 `._meta`(层级异常,规范 4.6)。
153    ///
154    /// `rel_prefix` 为该目录的 bundle 相对路径(ROOT 传 `""`);`ignore` 非空时,
155    /// 被忽略的子项同样剪枝(与分支遍历语义一致)。
156    fn contains_meta_deeper(&self, dir: &Path, rel_prefix: &str, ignore: &IgnoreSet) -> bool {
157        for entry in walkdir::WalkDir::new(dir)
158            .max_depth(8)
159            .into_iter()
160            .filter_entry(|e| {
161                if e.depth() == 0 {
162                    return true;
163                }
164                let name = e.file_name().to_string_lossy().to_string();
165                // 不进入独立子 bundle(`.str` 目录是硬边界,规范 3.5)
166                if util::is_os_noise(&name) || util::is_sub_bundle(&name) {
167                    return false;
168                }
169                if ignore.is_empty() {
170                    return true;
171                }
172                let rel = match util::rel_display(dir, e.path()) {
173                    s if s == "." => rel_prefix.to_string(),
174                    s if rel_prefix.is_empty() => s,
175                    s => format!("{rel_prefix}/{s}"),
176                };
177                let is_dir = e.file_type().is_dir();
178                !ignore.is_ignored(&rel, is_dir)
179            })
180            .flatten()
181        {
182            if entry.depth() == 0 || !entry.file_type().is_dir() {
183                continue;
184            }
185            if entry.path().join(META_FILE).is_file() {
186                return true;
187            }
188        }
189        false
190    }
191
192    /// 构建 bundle 全局的忽略名单(规范 4.7)。
193    ///
194    /// 叠加顺序(由外向内,内层命中覆盖外层):
195    /// ① 外层 git 仓库的 `.gitignore`(自最外层向 bundle 根收集,至 worktree 根为止);
196    /// ② bundle 根的 `.gitignore`;
197    /// ③ ROOT `[policies].ignore`(显式配置,优先级最高)。
198    /// `policies.gitignore = false` 时跳过 ①②(分支目录内的 `.gitignore` 亦不检测)。
199    fn build_ignore(&self, root_meta: Option<&Meta>) -> IgnoreSet {
200        let mut set = IgnoreSet::default();
201        let policies = root_meta.map(|m| &m.policies);
202        let auto = policies.map(|p| p.gitignore).unwrap_or(true);
203        if auto {
204            // 外层 `.gitignore`:自 bundle 父目录向上收集到 worktree 根(含 `.git` 的
205            // 目录仍收集自身),越外层越先入栈 → 越靠近 bundle 的命中越优先。
206            let mut chain: Vec<PathBuf> = Vec::new();
207            let mut cur = self.root.parent();
208            while let Some(d) = cur {
209                chain.push(d.to_path_buf());
210                if d.join(".git").exists() || chain.len() >= 32 {
211                    break;
212                }
213                cur = d.parent();
214            }
215            for d in chain.into_iter().rev() {
216                if let Ok(text) = std::fs::read_to_string(d.join(".gitignore")) {
217                    // prefix = bundle 根相对该 ignore 目录的中间路径。
218                    let prefix = self
219                        .root
220                        .strip_prefix(d)
221                        .map(|p| p.to_string_lossy().to_string())
222                        .unwrap_or_default();
223                    set.push_outer(&prefix, &text);
224                }
225            }
226            if let Ok(text) = std::fs::read_to_string(self.root.join(".gitignore")) {
227                set.push_layer("", &text);
228            }
229        }
230        if let Some(p) = policies {
231            if !p.ignore.is_empty() {
232                set.push_layer("", &p.ignore.join("\n"));
233            }
234        }
235        // 系统级忽略层恒为最内层:`._meta` / `._schema/` / `._cache/` / `._` 保留
236        // 命名空间与 OS / VCS 元数据不受任何用户模式(含 `!` 取反)影响。
237        set.push_system_layer();
238        set
239    }
240
241    /// 扫描整棵分支树。
242    pub fn scan(&self) -> Result<Scan> {
243        let mut visits: Vec<Visit> = Vec::new();
244        let mut issues: Vec<Issue> = Vec::new();
245        let mut by_id: HashMap<String, Vec<usize>> = HashMap::new();
246
247        let root_meta = self.meta_path(&self.root);
248        if !root_meta.is_file() {
249            issues.push(Issue::error(
250                code::META_MISSING,
251                ".",
252                "bundle 根目录缺少 `._meta`",
253            ));
254            return Ok(Scan {
255                root: self.root.clone(),
256                visits,
257                issues,
258                by_id,
259                root_index: None,
260                max_depth: 0,
261                ignore: IgnoreSet::default(),
262            });
263        }
264
265        let (root_parsed, mut root_issues) = match self.read_meta(&self.root)? {
266            MetaLoad::Ok(m, i) => (Some(m), i),
267            MetaLoad::Failed(i) => (None, i),
268        };
269        let mut ignore = self.build_ignore(root_parsed.as_deref());
270        issues.append(&mut root_issues);
271        if let Some(m) = &root_parsed {
272            if let Some(id) = &m.id {
273                by_id.entry(id.clone()).or_default().push(0);
274            }
275        }
276        visits.push(Visit {
277            dir: self.root.clone(),
278            rel: ".".to_string(),
279            depth: 0,
280            meta: root_parsed,
281            parent: None,
282            readable: true,
283        });
284
285        let mut queue: VecDeque<usize> = VecDeque::from([0usize]);
286        let mut max_depth = 0usize;
287
288        while let Some(cur) = queue.pop_front() {
289            let dir = visits[cur].dir.clone();
290            let depth = visits[cur].depth;
291            if depth >= HARD_MAX_DEPTH {
292                continue;
293            }
294            // 分支目录内的 `.gitignore` 动态入栈(BFS 深度序天然满足「内层覆盖外层」)。
295            if depth >= 1 && !visits[cur].rel.is_empty() {
296                if let Ok(text) = std::fs::read_to_string(dir.join(".gitignore")) {
297                    ignore.push_layer(&visits[cur].rel, &text);
298                }
299            }
300            for child in self.child_dirs(&dir)? {
301                let name = child
302                    .file_name()
303                    .map(|s| s.to_string_lossy().to_string())
304                    .unwrap_or_default();
305                if util::is_os_noise(&name) {
306                    continue;
307                }
308                if util::is_sub_bundle(&name) {
309                    // 独立子 bundle:硬边界,父 bundle 不进入、不参与分支树
310                    continue;
311                }
312                let rel = self.rel(&child);
313                // 忽略名单命中(含目录专用模式):不遍历、不参与清单比对(规范 4.7)。
314                if !ignore.is_empty() && ignore.is_ignored(&rel, true) {
315                    continue;
316                }
317                if !self.has_meta(&child) {
318                    // 普通内容容器;若其中藏有分支则层级无法建立
319                    if !util::is_reserved_name(&name) && self.contains_meta_deeper(&child, &rel, &ignore) {
320                        issues.push(Issue::error(
321                            code::META_MISSING,
322                            rel,
323                            "父目录不是分支(缺少 `._meta`),其内出现 `._meta`,无法建立分支层级",
324                        ));
325                    }
326                    continue;
327                }
328                let d = depth + 1;
329                let (parsed, mut iss) = match self.read_meta(&child)? {
330                    MetaLoad::Ok(m, i) => (Some(m), i),
331                    MetaLoad::Failed(i) => (None, i),
332                };
333                issues.append(&mut iss);
334                let idx = visits.len();
335                if let Some(m) = &parsed {
336                    if let Some(id) = &m.id {
337                        by_id.entry(id.clone()).or_default().push(idx);
338                    }
339                }
340                visits.push(Visit {
341                    dir: child.clone(),
342                    rel,
343                    depth: d,
344                    meta: parsed,
345                    parent: Some(cur),
346                    readable: true,
347                });
348                max_depth = max_depth.max(d);
349                queue.push_back(idx);
350            }
351        }
352
353        Ok(Scan {
354            root: self.root.clone(),
355            visits,
356            issues,
357            by_id,
358            root_index: Some(0),
359            max_depth,
360            ignore,
361        })
362    }
363}