Skip to main content

str_format/
meta_edit.rs

1//! `._meta` 的**保注释写回**与新建模板渲染。
2//!
3//! 写回直接基于 `toml_edit::DocumentMut`,因此已有的 `#` 注释与键的书写顺序都会被保留
4//! (规范硬性约束 6、DoD 16)。
5
6use std::path::Path;
7
8use toml_edit::{DocumentMut, Item, Table, value};
9
10use crate::error::{Error, Result};
11use crate::meta::{Author, Entry, Kind, Meta, RefItem, extract};
12use crate::util;
13
14/// TOML 基本字符串转义。
15pub fn toml_str(s: &str) -> String {
16    let mut out = String::with_capacity(s.len() + 2);
17    out.push('"');
18    for c in s.chars() {
19        match c {
20            '"' => out.push_str("\\\""),
21            '\\' => out.push_str("\\\\"),
22            '\n' => out.push_str("\\n"),
23            '\r' => out.push_str("\\r"),
24            '\t' => out.push_str("\\t"),
25            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04X}", c as u32)),
26            c => out.push(c),
27        }
28    }
29    out.push('"');
30    out
31}
32
33/// 从 TOML 文本构建 `Meta`(模板渲染后使用)。
34pub fn meta_from_text(text: &str) -> Result<Meta> {
35    let doc: DocumentMut = text
36        .parse()
37        .map_err(|e| Error::Other(format!("内部模板 TOML 解析失败:{e}")))?;
38    let (meta, _issues) = extract(doc, "<template>");
39    Ok(meta)
40}
41
42/// 渲染 root `._meta` 模板。
43pub fn render_root_meta(
44    name: &str,
45    title: Option<&str>,
46    summary: Option<&str>,
47    root_id: &str,
48    created: &str,
49    id_version: usize,
50) -> String {
51    let mut s = String::new();
52    s.push_str("# ── STR bundle 根元数据 ──────────────────────────────────────────\n");
53    s.push_str("# ROOT 的 [[entries]] 中 role = \"node\" 的条目即一级分支结构。\n");
54    s.push_str(&format!("str = {}\n", crate::STR_MAJOR));
55    s.push_str(&format!("spec = {}\n", toml_str(crate::SPEC_VERSION)));
56    s.push_str("kind = \"root\"\n");
57    s.push_str(&format!("id = {}\n", toml_str(root_id)));
58    s.push_str(&format!("name = {}\n", toml_str(name)));
59    if let Some(t) = title {
60        s.push_str(&format!("title = {}\n", toml_str(t)));
61    }
62    if let Some(t) = summary {
63        s.push_str(&format!("summary = {}\n", toml_str(t)));
64    }
65    s.push_str("tags = []\n");
66    s.push_str("revision = 1\n");
67    s.push_str(&format!("created_at = {created}\n"));
68    s.push_str(&format!("updated_at = {created}\n"));
69    s.push('\n');
70    s.push_str("[policies]\n");
71    s.push_str(&format!("id_version = {id_version}\n"));
72    s.push_str("max_depth = 32\n");
73    s.push_str("manifest = \"strict\"\n");
74    s.push_str("sha256 = \"required\"\n");
75    s.push_str("large_asset_bytes = 10485760\n");
76    s.push_str("deep_tree_warn = 16\n");
77    // v1.12.0:不再登记 `._schema` —— 保留目录免登记(规范 §1.3 约束 5 / §4.8)。
78    // `._schema/` 目录本身仍由 init 创建并写入三份 Schema,只是不再出现在 `entries[]`。
79    s.push('\n');
80    s.push_str("[ext]\n");
81    s
82}
83
84/// 渲染 node / branch `._meta` 模板。
85pub fn render_branch_meta(
86    kind: Kind,
87    id: &str,
88    type_: Option<&str>,
89    title: Option<&str>,
90    summary: Option<&str>,
91    created: &str,
92) -> String {
93    let mut s = String::new();
94    s.push_str(&format!("str = {}\n", crate::STR_MAJOR));
95    s.push_str(&format!("spec = {}\n", toml_str(crate::SPEC_VERSION)));
96    s.push_str(&format!("kind = {}\n", toml_str(kind.as_str())));
97    s.push_str(&format!("id = {}\n", toml_str(id)));
98    if let Some(t) = type_ {
99        s.push_str(&format!("type = {}\n", toml_str(t)));
100    }
101    if let Some(t) = title {
102        s.push_str(&format!("title = {}\n", toml_str(t)));
103    }
104    if let Some(t) = summary {
105        s.push_str(&format!("summary = {}\n", toml_str(t)));
106    }
107    s.push_str("tags = []\n");
108    s.push_str("revision = 1\n");
109    s.push_str(&format!("created_at = {created}\n"));
110    s.push_str(&format!("updated_at = {created}\n"));
111    s.push('\n');
112    s.push_str("[ext]\n");
113    s
114}
115
116/// `[[entries]]` 元素 → TOML 表(按规范键序)。
117pub fn entry_to_table(e: &Entry) -> Table {
118    let mut t = Table::new();
119    t.insert("path", value(e.path.clone()));
120    t.insert("role", value(e.role.clone()));
121    if let Some(v) = &e.id {
122        t.insert("id", value(v.clone()));
123    }
124    if let Some(v) = &e.r#type {
125        t.insert("type", value(v.clone()));
126    }
127    if let Some(v) = &e.title {
128        t.insert("title", value(v.clone()));
129    }
130    if let Some(v) = &e.summary {
131        t.insert("summary", value(v.clone()));
132    }
133    if let Some(v) = e.order {
134        t.insert("order", value(v));
135    }
136    if let Some(v) = &e.media_type {
137        t.insert("media_type", value(v.clone()));
138    }
139    if let Some(v) = e.size {
140        t.insert("size", value(v));
141    }
142    if let Some(v) = &e.sha256 {
143        t.insert("sha256", value(v.clone()));
144    }
145    if let Some(v) = e.count {
146        t.insert("count", value(v));
147    }
148    if let Some(v) = &e.schema {
149        t.insert("schema", value(v.clone()));
150    }
151    if e.optional {
152        t.insert("optional", value(true));
153    }
154    if let Some(v) = &e.note {
155        t.insert("note", value(v.clone()));
156    }
157    t
158}
159
160/// `[[refs]]` 元素 → TOML 表(按规范键序)。
161pub fn ref_to_table(r: &RefItem) -> Table {
162    let mut t = Table::new();
163    t.insert("id", value(r.id.clone()));
164    t.insert("target", value(r.target.clone()));
165    t.insert("rel", value(r.rel.clone()));
166    if let Some(v) = &r.title {
167        t.insert("title", value(v.clone()));
168    }
169    if let Some(v) = r.order {
170        t.insert("order", value(v));
171    }
172    if let Some(v) = &r.note {
173        t.insert("note", value(v.clone()));
174    }
175    t
176}
177
178/// `[[authors]]` 元素 → TOML 表(按规范键序)。
179pub fn author_to_table(a: &Author) -> Table {
180    let mut t = Table::new();
181    t.insert("id", value(a.id.clone()));
182    if let Some(v) = &a.name {
183        t.insert("name", value(v.clone()));
184    }
185    t.insert("role", value(a.role.clone()));
186    if let Some(at) = &a.at
187        && let Ok(dt) = at.parse::<toml_edit::Datetime>()
188    {
189        t.insert("at", value(dt));
190    }
191    t
192}
193
194/// 去掉整行 `#` 注释(不处理字符串内的 `#`);`str fmt --strip-comments` 的唯一入口。
195pub fn strip_line_comments(text: &str) -> String {
196    let mut out = String::with_capacity(text.len());
197    for line in text.lines() {
198        if line.trim_start().starts_with('#') {
199            continue;
200        }
201        out.push_str(line);
202        out.push('\n');
203    }
204    out
205}
206
207impl Meta {
208    /// 写操作后重新同步类型化视图(`doc` 为准)。
209    pub fn resync(&mut self) {
210        let doc = std::mem::replace(&mut self.doc, DocumentMut::new());
211        let (meta, _issues) = extract(doc, "<resync>");
212        *self = meta;
213    }
214
215    /// 按规范表序(`policies → authors → refs → entries → ext`)安置一张表 / 数组表。
216    fn place_table(&mut self, key: &'static str, item: Item) {
217        let order = crate::meta::TABLE_ORDER;
218        let pos = order.iter().position(|k| *k == key).unwrap_or(order.len());
219        let table = self.doc.as_table_mut();
220        let mut moved: Vec<(String, Item)> = Vec::new();
221        for k in order.iter().skip(pos + 1) {
222            if let Some(it) = table.remove(k) {
223                moved.push(((*k).to_string(), it));
224            }
225        }
226        table.insert(key, item);
227        for (k, it) in moved {
228            table.insert(&k, it);
229        }
230    }
231
232    /// `revision + 1` 并刷新 `updated_at`。
233    ///
234    /// `updated_at` 一律写成 TOML **原生 offset date-time**(规范 4.1),不得是字符串。
235    pub fn touch(&mut self) {
236        let next = self.revision.unwrap_or(0) + 1;
237        let now = util::now_rfc3339();
238        let table = self.doc.as_table_mut();
239        table.insert("revision", value(next));
240        if let Ok(dt) = now.parse::<toml_edit::Datetime>() {
241            table.insert("updated_at", value(dt));
242        }
243        self.resync();
244    }
245
246    /// 设置顶层字符串字段(保注释)。
247    pub fn set_str(&mut self, key: &str, v: &str) {
248        self.doc.as_table_mut().insert(key, value(v.to_string()));
249        self.resync();
250    }
251
252    /// 设置顶层字符串字段;`v` 为空串则**移除**该字段。
253    pub fn set_str_or_remove(&mut self, key: &str, v: &str) {
254        if v.is_empty() {
255            self.doc.as_table_mut().remove(key);
256        } else {
257            self.doc.as_table_mut().insert(key, value(v.to_string()));
258        }
259        self.resync();
260    }
261
262    /// 设置顶层字符串数组字段(如 `tags`)。
263    pub fn set_str_array(&mut self, key: &str, values: &[String]) {
264        let arr: toml_edit::Array = values
265            .iter()
266            .map(|s| toml_edit::Value::from(s.clone()))
267            .collect();
268        self.doc.as_table_mut().insert(key, value(arr));
269        self.resync();
270    }
271
272    /// 设置 `[policies]` 内的单个键(仅 root;保注释,键序随后由 `canonicalize()` 收口)。
273    ///
274    /// `None` 移除该键;`[policies]` 表不存在时创建。原本不存在且落完是空表时不产生改动。
275    pub fn set_policies_value(&mut self, key: &str, v: Option<toml_edit::Item>) {
276        let existing = self
277            .doc
278            .as_table()
279            .get("policies")
280            .and_then(|i| i.as_table().cloned());
281        let created = existing.is_none();
282        let mut pt = existing.unwrap_or_default();
283        match v {
284            Some(item) => {
285                pt.insert(key, item);
286            }
287            None => {
288                pt.remove(key);
289            }
290        }
291        if created && pt.is_empty() {
292            return;
293        }
294        self.place_table("policies", toml_edit::Item::Table(pt));
295        self.resync();
296    }
297
298    /// 设置 `[policies]` 内的字符串数组键(如 `ignore`);空数组即移除该键。
299    pub fn set_policies_str_array(&mut self, key: &str, values: &[String]) {
300        if values.is_empty() {
301            self.set_policies_value(key, None);
302            return;
303        }
304        let arr: toml_edit::Array = values
305            .iter()
306            .map(|s| toml_edit::Value::from(s.clone()))
307            .collect();
308        self.set_policies_value(key, Some(toml_edit::value(arr)));
309    }
310
311    /// 按 `id` 插入或替换一条 `[[authors]]`,返回 `true` 表示新增。
312    pub fn upsert_author(&mut self, a: &Author) -> bool {
313        let new_table = author_to_table(a);
314        let mut aot = self
315            .doc
316            .as_table()
317            .get("authors")
318            .and_then(|i| i.as_array_of_tables())
319            .cloned()
320            .unwrap_or_default();
321        let mut replaced = false;
322        for t in aot.iter_mut() {
323            if t.get("id").and_then(|v| v.as_str()) == Some(a.id.as_str()) {
324                *t = new_table.clone();
325                replaced = true;
326                break;
327            }
328        }
329        if !replaced {
330            aot.push(new_table);
331        }
332        self.place_table("authors", Item::ArrayOfTables(aot));
333        self.resync();
334        !replaced
335    }
336
337    /// 按 `id` 删除 `[[authors]]`。
338    pub fn remove_author(&mut self, id: &str) -> bool {
339        let Some(aot) = self
340            .doc
341            .as_table_mut()
342            .get_mut("authors")
343            .and_then(|i| i.as_array_of_tables_mut())
344        else {
345            return false;
346        };
347        let before = aot.len();
348        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
349        let changed = aot.len() != before;
350        if changed {
351            self.resync();
352        }
353        changed
354    }
355
356    /// 在**指定分支**的 `entries[path]` 上设置字符串字段(保注释,键序由规范化收口)。
357    ///
358    /// `key` 限 `ENTRY_KEYS` 中的字符串字段;`v` 为空串则移除该键。
359    /// 返回 `false` 表示该分支没有 `path` 对应的条目。
360    pub fn set_entry_str(&mut self, path: &str, key: &str, v: &str) -> bool {
361        self.with_entry(path, |t| {
362            if v.is_empty() {
363                t.remove(key);
364            } else {
365                t.insert(key, value(v.to_string()));
366            }
367        })
368    }
369
370    /// 在 `entries[path]` 上设置整数字段(如 `order`)。`None` 表示移除。
371    pub fn set_entry_int(&mut self, path: &str, key: &str, v: Option<i64>) -> bool {
372        self.with_entry(path, |t| match v {
373            Some(n) => {
374                t.insert(key, value(n));
375            }
376            None => {
377                t.remove(key);
378            }
379        })
380    }
381
382    /// 对 `entries[path]` 施加一次就地编辑。
383    fn with_entry(&mut self, path: &str, edit: impl FnOnce(&mut Table)) -> bool {
384        let Some(aot) = self
385            .doc
386            .as_table_mut()
387            .get_mut("entries")
388            .and_then(|i| i.as_array_of_tables_mut())
389        else {
390            return false;
391        };
392        let mut hit = false;
393        for t in aot.iter_mut() {
394            if t.get("path").and_then(|v| v.as_str()) == Some(path) {
395                edit(t);
396                hit = true;
397                break;
398            }
399        }
400        if hit {
401            self.resync();
402        }
403        hit
404    }
405
406    /// 插入或替换一条 `[[entries]]`,返回 `true` 表示新增。
407    pub fn upsert_entry(&mut self, e: &Entry) -> bool {
408        let new_table = entry_to_table(e);
409        let mut aot = self
410            .doc
411            .as_table()
412            .get("entries")
413            .and_then(|i| i.as_array_of_tables())
414            .cloned()
415            .unwrap_or_default();
416
417        let mut replaced = false;
418        for t in aot.iter_mut() {
419            if t.get("path").and_then(|v| v.as_str()) == Some(e.path.as_str()) {
420                *t = new_table.clone();
421                replaced = true;
422                break;
423            }
424        }
425        if !replaced {
426            aot.push(new_table);
427        }
428        self.place_table("entries", Item::ArrayOfTables(aot));
429        self.resync();
430        !replaced
431    }
432
433    /// 删除指定 `path` 的 `[[entries]]` 元素。
434    pub fn remove_entry_path(&mut self, path: &str) -> bool {
435        let Some(aot) = self
436            .doc
437            .as_table_mut()
438            .get_mut("entries")
439            .and_then(|i| i.as_array_of_tables_mut())
440        else {
441            return false;
442        };
443        let before = aot.len();
444        aot.retain(|t| t.get("path").and_then(|v| v.as_str()) != Some(path));
445        let changed = aot.len() != before;
446        if changed {
447            self.resync();
448        }
449        changed
450    }
451
452    /// 追加一条 `[[refs]]`。
453    pub fn push_ref(&mut self, r: &RefItem) {
454        let mut aot = self
455            .doc
456            .as_table()
457            .get("refs")
458            .and_then(|i| i.as_array_of_tables())
459            .cloned()
460            .unwrap_or_default();
461        aot.push(ref_to_table(r));
462        self.place_table("refs", Item::ArrayOfTables(aot));
463        self.resync();
464    }
465
466    /// 按 id 删除 `[[refs]]`。
467    pub fn remove_ref(&mut self, id: &str) -> bool {
468        let Some(aot) = self
469            .doc
470            .as_table_mut()
471            .get_mut("refs")
472            .and_then(|i| i.as_array_of_tables_mut())
473        else {
474            return false;
475        };
476        let before = aot.len();
477        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
478        let changed = aot.len() != before;
479        if changed {
480            self.resync();
481        }
482        changed
483    }
484
485    /// 规范 §4.9 归一化后的 TOML 文本(键序 / 表序固定,注释保留)。
486    ///
487    /// 属性是只读的派生视图:这里在**副本**上做规范化,不改动 `self.doc`。
488    pub fn canonical_text(&self, strip_comments: bool) -> String {
489        let mut doc = self.doc.clone();
490        crate::meta::canonicalize_doc(&mut doc);
491        let mut text = doc.to_string();
492        if !text.ends_with('\n') {
493            text.push('\n');
494        }
495        if strip_comments {
496            text = strip_line_comments(&text);
497        }
498        text
499    }
500
501    /// 保注释写回磁盘(写出的字节一律是 §4.9 规范形式)。
502    pub fn save(&self, path: &Path) -> Result<()> {
503        let text = self.canonical_text(false);
504        std::fs::write(path, text).map_err(|e| Error::io(path, e))
505    }
506}