Skip to main content

str_format/
error.rs

1//! 错误码与校验报告。
2//!
3//! 错误码与规范第 6.1 章一一对应。清单类问题(`E_MANIFEST_*`)在
4//! `policies.manifest = "advisory"` 时降级为对应的 `W_MANIFEST_*`。
5
6use serde::Serialize;
7
8/// 问题级别。
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
10#[serde(rename_all = "lowercase")]
11pub enum Level {
12    /// 阻断性错误。
13    Error,
14    /// 非阻断性告警。
15    Warn,
16}
17
18impl Level {
19    /// 输出用字符串。
20    pub fn as_str(self) -> &'static str {
21        match self {
22            Level::Error => "error",
23            Level::Warn => "warn",
24        }
25    }
26}
27
28/// 规范 6.1 章的错误码常量。
29pub mod code {
30    // ── 结构 / 身份 ──────────────────────────────────────────
31    /// `.str.toml` 非法 TOML / 编码非 UTF-8 / 含 BOM / 时间未带时区偏移。
32    pub const PARSE: &str = "E_PARSE";
33    /// 分支目录缺失 `.str.toml`。
34    pub const META_MISSING: &str = "E_META_MISSING";
35    /// `str` 主版本不受支持。
36    pub const SPEC_UNSUPPORTED: &str = "E_SPEC_UNSUPPORTED";
37    /// `kind` 非法。
38    pub const KIND_INVALID: &str = "E_KIND_INVALID";
39    /// `kind` 与所在深度不符。
40    pub const KIND_DEPTH: &str = "E_KIND_DEPTH";
41    /// 必填字段缺失 / 类型不符 / 未知字段。
42    pub const SCHEMA_FIELD: &str = "E_SCHEMA_FIELD";
43    /// `id` 与所在目录名不一致。
44    pub const ID_MISMATCH: &str = "E_ID_MISMATCH";
45    /// 分支目录名不是合法 UUID。
46    pub const ID_NOT_UUID: &str = "E_ID_NOT_UUID";
47    /// UUID 版本与 `policies.id_version` 不符。
48    pub const ID_VERSION: &str = "E_ID_VERSION";
49    /// 同一 bundle 内出现重复分支 `id`。
50    pub const ID_DUP: &str = "E_ID_DUP";
51    /// 父级 `entries[].role` 与子目录实际内容或深度不符。
52    pub const ENTRY_ROLE_DEPTH: &str = "E_ENTRY_ROLE_DEPTH";
53    /// `entries[].id` 与子目录名不一致。
54    pub const ENTRY_ID_MISMATCH: &str = "E_ENTRY_ID_MISMATCH";
55    /// 分支树深度超过 `max_depth`。
56    pub const DEPTH_EXCEEDED: &str = "E_DEPTH_EXCEEDED";
57
58    // ── 引用 ────────────────────────────────────────────────
59    /// `refs[].target` 无法解析。
60    pub const REF_NO_TARGET: &str = "E_REF_NO_TARGET";
61    /// `refs[].target` 指向自身。
62    pub const REF_SELF: &str = "E_REF_SELF";
63    /// `refs` 关联图成环。
64    pub const REF_CYCLE: &str = "E_REF_CYCLE";
65
66    // ── 软连接(`role = "link"`,规范 §4.6.1)────────────────────
67    /// `entries[role=link].target` 无法在本 bundle 内解析。
68    pub const LINK_NO_TARGET: &str = "E_LINK_NO_TARGET";
69    /// 软连接的目标是 ROOT,或不是可挂载的 `node` / `branch`。
70    pub const LINK_TARGET_INVALID: &str = "E_LINK_TARGET_INVALID";
71    /// 软连接条目携带了 `id` / `size` / `sha256` / `count` / `media_type` / `schema`。
72    pub const LINK_HAS_PAYLOAD: &str = "E_LINK_HAS_PAYLOAD";
73    /// 软连接挂载图成环(含自我挂载)。
74    pub const LINK_CYCLE: &str = "E_LINK_CYCLE";
75    /// 同一父分支内重复挂载同一目标。
76    pub const LINK_DUP: &str = "E_LINK_DUP";
77    /// 硬链接分支登记了内容条目(内容所有权唯一在目标分支,自有 entries 只允许子分支)。
78    pub const LINK_OWN_CONTENT: &str = "E_LINK_OWN_CONTENT";
79
80    // ── 清单 ────────────────────────────────────────────────
81    /// 磁盘存在但 `entries` 未登记。
82    pub const MANIFEST_MISSING: &str = "E_MANIFEST_MISSING";
83    /// `entries` 登记但磁盘不存在。
84    pub const MANIFEST_GHOST: &str = "E_MANIFEST_GHOST";
85    /// `size` / `sha256` 与实际不符。
86    pub const MANIFEST_HASH: &str = "E_MANIFEST_HASH";
87    /// 文件类条目缺少 `size` / `sha256`。
88    pub const MANIFEST_DIGEST_MISSING: &str = "E_MANIFEST_DIGEST_MISSING";
89    /// `entries[].path` 重复。
90    pub const MANIFEST_DUP: &str = "E_MANIFEST_DUP";
91    /// 业务条目使用 `.str.` 保留命名空间或 AppleDouble `._` 命名模式。
92    pub const RESERVED_NAME: &str = "E_RESERVED_NAME";
93    /// `revision` 非递增整数,或 `updated_at` 早于 `created_at`。
94    pub const REVISION_STALE: &str = "E_REVISION_STALE";
95    /// payload 不满足其声明的 JSON Schema。
96    pub const SCHEMA_FAIL: &str = "E_SCHEMA_FAIL";
97
98    // ── 告警 ────────────────────────────────────────────────
99    /// 根目录名未以 `.str` 结尾。
100    pub const BUNDLE_SUFFIX: &str = "W_BUNDLE_SUFFIX";
101    /// 出现非 `.str.toml` / `.lock` 的点文件。
102    pub const DOTFILE: &str = "W_DOTFILE";
103    /// ROOT 下出现既非分支目录也非保留名的条目。
104    pub const ROOT_STRAY: &str = "W_ROOT_STRAY";
105    /// 缺 `summary`。
106    pub const NO_SUMMARY: &str = "W_NO_SUMMARY";
107    /// 缺 `type`。
108    pub const NO_TYPE: &str = "W_NO_TYPE";
109    /// 分支树深度超过 `deep_tree_warn`。
110    pub const DEEP_TREE: &str = "W_DEEP_TREE";
111    /// 单文件超过 `large_asset_bytes`。
112    pub const LARGE_ASSET: &str = "W_LARGE_ASSET";
113    /// `optional: true` 的条目实际缺失。
114    pub const OPTIONAL_MISSING: &str = "W_OPTIONAL_MISSING";
115    /// `manifest = advisory` 时的未登记条目。
116    pub const MANIFEST_MISSING_W: &str = "W_MANIFEST_MISSING";
117    /// `manifest = advisory` 时的幽灵条目。
118    pub const MANIFEST_GHOST_W: &str = "W_MANIFEST_GHOST";
119    /// `manifest = advisory` 时的指纹不符。
120    pub const MANIFEST_HASH_W: &str = "W_MANIFEST_HASH";
121
122    /// 全部错误码(测试矩阵与 `--list-codes` 使用)。
123    pub const ALL: &[&str] = &[
124        PARSE,
125        META_MISSING,
126        SPEC_UNSUPPORTED,
127        KIND_INVALID,
128        KIND_DEPTH,
129        SCHEMA_FIELD,
130        ID_MISMATCH,
131        ID_NOT_UUID,
132        ID_VERSION,
133        ID_DUP,
134        ENTRY_ROLE_DEPTH,
135        ENTRY_ID_MISMATCH,
136        DEPTH_EXCEEDED,
137        REF_NO_TARGET,
138        REF_SELF,
139        REF_CYCLE,
140        MANIFEST_MISSING,
141        MANIFEST_GHOST,
142        MANIFEST_HASH,
143        MANIFEST_DIGEST_MISSING,
144        MANIFEST_DUP,
145        RESERVED_NAME,
146        REVISION_STALE,
147        SCHEMA_FAIL,
148        BUNDLE_SUFFIX,
149        DOTFILE,
150        ROOT_STRAY,
151        NO_SUMMARY,
152        NO_TYPE,
153        DEEP_TREE,
154        LARGE_ASSET,
155        OPTIONAL_MISSING,
156        MANIFEST_MISSING_W,
157        MANIFEST_GHOST_W,
158        MANIFEST_HASH_W,
159    ];
160}
161
162/// 单条校验问题。
163#[derive(Debug, Clone, Serialize)]
164pub struct Issue {
165    /// 错误码。
166    pub code: String,
167    /// 级别。
168    pub level: Level,
169    /// 定位路径(bundle 内相对路径)。
170    pub path: String,
171    /// 人类可读说明。
172    pub message: String,
173}
174
175impl Issue {
176    /// 构造一条问题。
177    pub fn new(
178        code: &'static str,
179        level: Level,
180        path: impl Into<String>,
181        message: impl Into<String>,
182    ) -> Self {
183        Self {
184            code: code.to_string(),
185            level,
186            path: path.into(),
187            message: message.into(),
188        }
189    }
190
191    /// 构造一条 error。
192    pub fn error(code: &'static str, path: impl Into<String>, message: impl Into<String>) -> Self {
193        Self::new(code, Level::Error, path, message)
194    }
195
196    /// 构造一条 warning。
197    pub fn warn(code: &'static str, path: impl Into<String>, message: impl Into<String>) -> Self {
198        Self::new(code, Level::Warn, path, message)
199    }
200}
201
202/// 统计信息。
203#[derive(Debug, Clone, Default, Serialize)]
204pub struct Stats {
205    /// 独立节点数(深度 1 的分支)。
206    pub nodes: usize,
207    /// 关联分支数(深度 ≥2 的分支)。
208    pub branches: usize,
209    /// 已登记条目总数。
210    pub entries: usize,
211    /// 实测分支树最大深度。
212    pub depth: usize,
213}
214
215/// 一次校验 / 遍历的完整报告。
216#[derive(Debug, Clone, Default)]
217pub struct Report {
218    /// bundle 名称。
219    pub bundle: String,
220    /// 全部问题,按产生顺序排列。
221    pub issues: Vec<Issue>,
222    /// 统计信息。
223    pub stats: Stats,
224}
225
226impl Report {
227    /// 追加一条问题。
228    pub fn push(&mut self, issue: Issue) {
229        self.issues.push(issue);
230    }
231
232    /// 全部错误。
233    pub fn errors(&self) -> impl Iterator<Item = &Issue> {
234        self.issues.iter().filter(|i| i.level == Level::Error)
235    }
236
237    /// 全部告警。
238    pub fn warnings(&self) -> impl Iterator<Item = &Issue> {
239        self.issues.iter().filter(|i| i.level == Level::Warn)
240    }
241
242    /// 错误数。
243    pub fn error_count(&self) -> usize {
244        self.errors().count()
245    }
246
247    /// 告警数。
248    pub fn warning_count(&self) -> usize {
249        self.warnings().count()
250    }
251
252    /// 退出码:有 error 为 1,否则 0。
253    pub fn exit_code(&self) -> i32 {
254        if self.error_count() > 0 { 1 } else { 0 }
255    }
256
257    /// 规范 6.2 规定的 `--json` 结构。
258    pub fn to_json(&self) -> serde_json::Value {
259        let conv = |it: &Issue| {
260            serde_json::json!({
261                "code": it.code,
262                "level": it.level.as_str(),
263                "path": it.path,
264                "message": it.message,
265            })
266        };
267        serde_json::json!({
268            "bundle": self.bundle,
269            "errors": self.errors().map(conv).collect::<Vec<_>>(),
270            "warnings": self.warnings().map(conv).collect::<Vec<_>>(),
271            "stats": {
272                "nodes": self.stats.nodes,
273                "branches": self.stats.branches,
274                "entries": self.stats.entries,
275                "depth": self.stats.depth,
276            },
277        })
278    }
279
280    /// 人类可读输出(规范 6.2)。
281    pub fn to_text(&self) -> String {
282        let mut out = String::new();
283        out.push_str(&format!(
284            "{}  {} nodes / {} branches / {} entries  depth={}\n",
285            self.bundle, self.stats.nodes, self.stats.branches, self.stats.entries, self.stats.depth
286        ));
287        for it in &self.issues {
288            let mark = match it.level {
289                Level::Error => "✗",
290                Level::Warn => "⚠",
291            };
292            out.push_str(&format!(
293                "  {} {:<28} {}  {}\n",
294                mark, it.code, it.path, it.message
295            ));
296        }
297        out.push_str(&format!(
298            "{} errors, {} warnings   exit={}",
299            self.error_count(),
300            self.warning_count(),
301            self.exit_code()
302        ));
303        out
304    }
305}
306
307/// 库级错误。
308#[derive(Debug, thiserror::Error)]
309pub enum Error {
310    /// 路径不存在。
311    #[error("路径不存在:{0}")]
312    NotFound(String),
313    /// 参数非法。
314    #[error("参数错误:{0}")]
315    BadArg(String),
316    /// I/O 失败。
317    #[error("I/O 错误({path}):{source}")]
318    Io {
319        /// 出错路径。
320        path: String,
321        /// 底层错误。
322        source: std::io::Error,
323    },
324    /// 校验未通过。
325    #[error("校验未通过:{0} 项错误")]
326    Validation(usize),
327    /// 其它。
328    #[error("{0}")]
329    Other(String),
330}
331
332impl Error {
333    /// 便捷构造 I/O 错误。
334    pub fn io(path: impl AsRef<std::path::Path>, source: std::io::Error) -> Self {
335        Error::Io {
336            path: path.as_ref().display().to_string(),
337            source,
338        }
339    }
340}
341
342/// 库级结果类型。
343pub type Result<T> = std::result::Result<T, Error>;