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    /// 按 `id` 插入或替换一条 `[[authors]]`,返回 `true` 表示新增。
273    pub fn upsert_author(&mut self, a: &Author) -> bool {
274        let new_table = author_to_table(a);
275        let mut aot = self
276            .doc
277            .as_table()
278            .get("authors")
279            .and_then(|i| i.as_array_of_tables())
280            .cloned()
281            .unwrap_or_default();
282        let mut replaced = false;
283        for t in aot.iter_mut() {
284            if t.get("id").and_then(|v| v.as_str()) == Some(a.id.as_str()) {
285                *t = new_table.clone();
286                replaced = true;
287                break;
288            }
289        }
290        if !replaced {
291            aot.push(new_table);
292        }
293        self.place_table("authors", Item::ArrayOfTables(aot));
294        self.resync();
295        !replaced
296    }
297
298    /// 按 `id` 删除 `[[authors]]`。
299    pub fn remove_author(&mut self, id: &str) -> bool {
300        let Some(aot) = self
301            .doc
302            .as_table_mut()
303            .get_mut("authors")
304            .and_then(|i| i.as_array_of_tables_mut())
305        else {
306            return false;
307        };
308        let before = aot.len();
309        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
310        let changed = aot.len() != before;
311        if changed {
312            self.resync();
313        }
314        changed
315    }
316
317    /// 在**指定分支**的 `entries[path]` 上设置字符串字段(保注释,键序由规范化收口)。
318    ///
319    /// `key` 限 `ENTRY_KEYS` 中的字符串字段;`v` 为空串则移除该键。
320    /// 返回 `false` 表示该分支没有 `path` 对应的条目。
321    pub fn set_entry_str(&mut self, path: &str, key: &str, v: &str) -> bool {
322        self.with_entry(path, |t| {
323            if v.is_empty() {
324                t.remove(key);
325            } else {
326                t.insert(key, value(v.to_string()));
327            }
328        })
329    }
330
331    /// 在 `entries[path]` 上设置整数字段(如 `order`)。`None` 表示移除。
332    pub fn set_entry_int(&mut self, path: &str, key: &str, v: Option<i64>) -> bool {
333        self.with_entry(path, |t| match v {
334            Some(n) => {
335                t.insert(key, value(n));
336            }
337            None => {
338                t.remove(key);
339            }
340        })
341    }
342
343    /// 对 `entries[path]` 施加一次就地编辑。
344    fn with_entry(&mut self, path: &str, edit: impl FnOnce(&mut Table)) -> bool {
345        let Some(aot) = self
346            .doc
347            .as_table_mut()
348            .get_mut("entries")
349            .and_then(|i| i.as_array_of_tables_mut())
350        else {
351            return false;
352        };
353        let mut hit = false;
354        for t in aot.iter_mut() {
355            if t.get("path").and_then(|v| v.as_str()) == Some(path) {
356                edit(t);
357                hit = true;
358                break;
359            }
360        }
361        if hit {
362            self.resync();
363        }
364        hit
365    }
366
367    /// 插入或替换一条 `[[entries]]`,返回 `true` 表示新增。
368    pub fn upsert_entry(&mut self, e: &Entry) -> bool {
369        let new_table = entry_to_table(e);
370        let mut aot = self
371            .doc
372            .as_table()
373            .get("entries")
374            .and_then(|i| i.as_array_of_tables())
375            .cloned()
376            .unwrap_or_default();
377
378        let mut replaced = false;
379        for t in aot.iter_mut() {
380            if t.get("path").and_then(|v| v.as_str()) == Some(e.path.as_str()) {
381                *t = new_table.clone();
382                replaced = true;
383                break;
384            }
385        }
386        if !replaced {
387            aot.push(new_table);
388        }
389        self.place_table("entries", Item::ArrayOfTables(aot));
390        self.resync();
391        !replaced
392    }
393
394    /// 删除指定 `path` 的 `[[entries]]` 元素。
395    pub fn remove_entry_path(&mut self, path: &str) -> bool {
396        let Some(aot) = self
397            .doc
398            .as_table_mut()
399            .get_mut("entries")
400            .and_then(|i| i.as_array_of_tables_mut())
401        else {
402            return false;
403        };
404        let before = aot.len();
405        aot.retain(|t| t.get("path").and_then(|v| v.as_str()) != Some(path));
406        let changed = aot.len() != before;
407        if changed {
408            self.resync();
409        }
410        changed
411    }
412
413    /// 追加一条 `[[refs]]`。
414    pub fn push_ref(&mut self, r: &RefItem) {
415        let mut aot = self
416            .doc
417            .as_table()
418            .get("refs")
419            .and_then(|i| i.as_array_of_tables())
420            .cloned()
421            .unwrap_or_default();
422        aot.push(ref_to_table(r));
423        self.place_table("refs", Item::ArrayOfTables(aot));
424        self.resync();
425    }
426
427    /// 按 id 删除 `[[refs]]`。
428    pub fn remove_ref(&mut self, id: &str) -> bool {
429        let Some(aot) = self
430            .doc
431            .as_table_mut()
432            .get_mut("refs")
433            .and_then(|i| i.as_array_of_tables_mut())
434        else {
435            return false;
436        };
437        let before = aot.len();
438        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
439        let changed = aot.len() != before;
440        if changed {
441            self.resync();
442        }
443        changed
444    }
445
446    /// 规范 §4.9 归一化后的 TOML 文本(键序 / 表序固定,注释保留)。
447    ///
448    /// 属性是只读的派生视图:这里在**副本**上做规范化,不改动 `self.doc`。
449    pub fn canonical_text(&self, strip_comments: bool) -> String {
450        let mut doc = self.doc.clone();
451        crate::meta::canonicalize_doc(&mut doc);
452        let mut text = doc.to_string();
453        if !text.ends_with('\n') {
454            text.push('\n');
455        }
456        if strip_comments {
457            text = strip_line_comments(&text);
458        }
459        text
460    }
461
462    /// 保注释写回磁盘(写出的字节一律是 §4.9 规范形式)。
463    pub fn save(&self, path: &Path) -> Result<()> {
464        let text = self.canonical_text(false);
465        std::fs::write(path, text).map_err(|e| Error::io(path, e))
466    }
467}