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