Skip to main content

str_format/
meta_edit.rs

1//! `.str.toml` 的**保注释写回**与新建模板渲染。
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 `.str.toml` 模板。
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:不再登记 `.str.schema` —— 保留目录免登记(规范 §1.3 约束 5 / §4.8)。
78    // `.str.schema/` 目录本身仍由 init 创建并写入三份 Schema,只是不再出现在 `entries[]`。
79    s.push('\n');
80    s.push_str("[ext]\n");
81    s
82}
83
84/// 渲染 node / branch `.str.toml` 模板。
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.target {
125        t.insert("target", value(v.clone()));
126    }
127    if let Some(v) = &e.mode {
128        t.insert("mode", value(v.clone()));
129    }
130    if let Some(v) = &e.r#type {
131        t.insert("type", value(v.clone()));
132    }
133    if let Some(v) = &e.title {
134        t.insert("title", value(v.clone()));
135    }
136    if let Some(v) = &e.summary {
137        t.insert("summary", value(v.clone()));
138    }
139    if let Some(v) = e.order {
140        t.insert("order", value(v));
141    }
142    if let Some(v) = &e.media_type {
143        t.insert("media_type", value(v.clone()));
144    }
145    if let Some(v) = e.size {
146        t.insert("size", value(v));
147    }
148    if let Some(v) = &e.sha256 {
149        t.insert("sha256", value(v.clone()));
150    }
151    if let Some(v) = e.count {
152        t.insert("count", value(v));
153    }
154    if let Some(v) = &e.schema {
155        t.insert("schema", value(v.clone()));
156    }
157    if e.optional {
158        t.insert("optional", value(true));
159    }
160    if let Some(v) = &e.note {
161        t.insert("note", value(v.clone()));
162    }
163    t
164}
165
166/// `[[refs]]` 元素 → TOML 表(按规范键序)。
167pub fn ref_to_table(r: &RefItem) -> Table {
168    let mut t = Table::new();
169    t.insert("id", value(r.id.clone()));
170    t.insert("target", value(r.target.clone()));
171    t.insert("rel", value(r.rel.clone()));
172    if let Some(v) = &r.title {
173        t.insert("title", value(v.clone()));
174    }
175    if let Some(v) = r.order {
176        t.insert("order", value(v));
177    }
178    if let Some(v) = &r.note {
179        t.insert("note", value(v.clone()));
180    }
181    t
182}
183
184/// `[[authors]]` 元素 → TOML 表(按规范键序)。
185pub fn author_to_table(a: &Author) -> Table {
186    let mut t = Table::new();
187    t.insert("id", value(a.id.clone()));
188    if let Some(v) = &a.name {
189        t.insert("name", value(v.clone()));
190    }
191    t.insert("role", value(a.role.clone()));
192    if let Some(at) = &a.at
193        && let Ok(dt) = at.parse::<toml_edit::Datetime>()
194    {
195        t.insert("at", value(dt));
196    }
197    t
198}
199
200/// 去掉整行 `#` 注释(不处理字符串内的 `#`);`str fmt --strip-comments` 的唯一入口。
201pub fn strip_line_comments(text: &str) -> String {
202    let mut out = String::with_capacity(text.len());
203    for line in text.lines() {
204        if line.trim_start().starts_with('#') {
205            continue;
206        }
207        out.push_str(line);
208        out.push('\n');
209    }
210    out
211}
212
213impl Meta {
214    /// 写操作后重新同步类型化视图(`doc` 为准)。
215    pub fn resync(&mut self) {
216        let doc = std::mem::replace(&mut self.doc, DocumentMut::new());
217        let (meta, _issues) = extract(doc, "<resync>");
218        *self = meta;
219    }
220
221    /// 按规范表序(`policies → authors → refs → entries → ext`)安置一张表 / 数组表。
222    fn place_table(&mut self, key: &'static str, item: Item) {
223        let order = crate::meta::TABLE_ORDER;
224        let pos = order.iter().position(|k| *k == key).unwrap_or(order.len());
225        let table = self.doc.as_table_mut();
226        let mut moved: Vec<(String, Item)> = Vec::new();
227        for k in order.iter().skip(pos + 1) {
228            if let Some(it) = table.remove(k) {
229                moved.push(((*k).to_string(), it));
230            }
231        }
232        table.insert(key, item);
233        for (k, it) in moved {
234            table.insert(&k, it);
235        }
236    }
237
238    /// `revision + 1` 并刷新 `updated_at`。
239    ///
240    /// `updated_at` 一律写成 TOML **原生 offset date-time**(规范 4.1),不得是字符串。
241    pub fn touch(&mut self) {
242        let next = self.revision.unwrap_or(0) + 1;
243        let now = util::now_rfc3339();
244        let table = self.doc.as_table_mut();
245        table.insert("revision", value(next));
246        if let Ok(dt) = now.parse::<toml_edit::Datetime>() {
247            table.insert("updated_at", value(dt));
248        }
249        self.resync();
250    }
251
252    /// 设置顶层字符串字段(保注释)。
253    pub fn set_str(&mut self, key: &str, v: &str) {
254        self.doc.as_table_mut().insert(key, value(v.to_string()));
255        self.resync();
256    }
257
258    /// 设置顶层字符串字段;`v` 为空串则**移除**该字段。
259    pub fn set_str_or_remove(&mut self, key: &str, v: &str) {
260        if v.is_empty() {
261            self.doc.as_table_mut().remove(key);
262        } else {
263            self.doc.as_table_mut().insert(key, value(v.to_string()));
264        }
265        self.resync();
266    }
267
268    /// 设置顶层字符串数组字段(如 `tags`)。
269    pub fn set_str_array(&mut self, key: &str, values: &[String]) {
270        let arr: toml_edit::Array = values
271            .iter()
272            .map(|s| toml_edit::Value::from(s.clone()))
273            .collect();
274        self.doc.as_table_mut().insert(key, value(arr));
275        self.resync();
276    }
277
278    /// 设置 `[policies]` 内的单个键(仅 root;保注释,键序随后由 `canonicalize()` 收口)。
279    ///
280    /// `None` 移除该键;`[policies]` 表不存在时创建。原本不存在且落完是空表时不产生改动。
281    pub fn set_policies_value(&mut self, key: &str, v: Option<toml_edit::Item>) {
282        let existing = self
283            .doc
284            .as_table()
285            .get("policies")
286            .and_then(|i| i.as_table().cloned());
287        let created = existing.is_none();
288        let mut pt = existing.unwrap_or_default();
289        match v {
290            Some(item) => {
291                pt.insert(key, item);
292            }
293            None => {
294                pt.remove(key);
295            }
296        }
297        if created && pt.is_empty() {
298            return;
299        }
300        self.place_table("policies", toml_edit::Item::Table(pt));
301        self.resync();
302    }
303
304    /// 设置 `[policies]` 内的字符串数组键(如 `ignore`);空数组即移除该键。
305    pub fn set_policies_str_array(&mut self, key: &str, values: &[String]) {
306        if values.is_empty() {
307            self.set_policies_value(key, None);
308            return;
309        }
310        let arr: toml_edit::Array = values
311            .iter()
312            .map(|s| toml_edit::Value::from(s.clone()))
313            .collect();
314        self.set_policies_value(key, Some(toml_edit::value(arr)));
315    }
316
317    /// 按 `id` 插入或替换一条 `[[authors]]`,返回 `true` 表示新增。
318    pub fn upsert_author(&mut self, a: &Author) -> bool {
319        let new_table = author_to_table(a);
320        let mut aot = self
321            .doc
322            .as_table()
323            .get("authors")
324            .and_then(|i| i.as_array_of_tables())
325            .cloned()
326            .unwrap_or_default();
327        let mut replaced = false;
328        for t in aot.iter_mut() {
329            if t.get("id").and_then(|v| v.as_str()) == Some(a.id.as_str()) {
330                *t = new_table.clone();
331                replaced = true;
332                break;
333            }
334        }
335        if !replaced {
336            aot.push(new_table);
337        }
338        self.place_table("authors", Item::ArrayOfTables(aot));
339        self.resync();
340        !replaced
341    }
342
343    /// 按 `id` 删除 `[[authors]]`。
344    pub fn remove_author(&mut self, id: &str) -> bool {
345        let Some(aot) = self
346            .doc
347            .as_table_mut()
348            .get_mut("authors")
349            .and_then(|i| i.as_array_of_tables_mut())
350        else {
351            return false;
352        };
353        let before = aot.len();
354        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
355        let changed = aot.len() != before;
356        if changed {
357            self.resync();
358        }
359        changed
360    }
361
362    /// 在**指定分支**的 `entries[path]` 上设置字符串字段(保注释,键序由规范化收口)。
363    ///
364    /// `key` 限 `ENTRY_KEYS` 中的字符串字段;`v` 为空串则移除该键。
365    /// 返回 `false` 表示该分支没有 `path` 对应的条目。
366    pub fn set_entry_str(&mut self, path: &str, key: &str, v: &str) -> bool {
367        self.with_entry(path, |t| {
368            if v.is_empty() {
369                t.remove(key);
370            } else {
371                t.insert(key, value(v.to_string()));
372            }
373        })
374    }
375
376    /// 在 `entries[path]` 上设置整数字段(如 `order`)。`None` 表示移除。
377    pub fn set_entry_int(&mut self, path: &str, key: &str, v: Option<i64>) -> bool {
378        self.with_entry(path, |t| match v {
379            Some(n) => {
380                t.insert(key, value(n));
381            }
382            None => {
383                t.remove(key);
384            }
385        })
386    }
387
388    /// 对 `entries[path]` 施加一次就地编辑。
389    fn with_entry(&mut self, path: &str, edit: impl FnOnce(&mut Table)) -> bool {
390        let Some(aot) = self
391            .doc
392            .as_table_mut()
393            .get_mut("entries")
394            .and_then(|i| i.as_array_of_tables_mut())
395        else {
396            return false;
397        };
398        let mut hit = false;
399        for t in aot.iter_mut() {
400            if t.get("path").and_then(|v| v.as_str()) == Some(path) {
401                edit(t);
402                hit = true;
403                break;
404            }
405        }
406        if hit {
407            self.resync();
408        }
409        hit
410    }
411
412    /// 插入或替换一条 `[[entries]]`,返回 `true` 表示新增。
413    pub fn upsert_entry(&mut self, e: &Entry) -> bool {
414        let new_table = entry_to_table(e);
415        let mut aot = self
416            .doc
417            .as_table()
418            .get("entries")
419            .and_then(|i| i.as_array_of_tables())
420            .cloned()
421            .unwrap_or_default();
422
423        let mut replaced = false;
424        for t in aot.iter_mut() {
425            if t.get("path").and_then(|v| v.as_str()) == Some(e.path.as_str()) {
426                *t = new_table.clone();
427                replaced = true;
428                break;
429            }
430        }
431        if !replaced {
432            aot.push(new_table);
433        }
434        self.place_table("entries", Item::ArrayOfTables(aot));
435        self.resync();
436        !replaced
437    }
438
439    /// 删除指定 `path` 的 `[[entries]]` 元素。
440    pub fn remove_entry_path(&mut self, path: &str) -> bool {
441        let Some(aot) = self
442            .doc
443            .as_table_mut()
444            .get_mut("entries")
445            .and_then(|i| i.as_array_of_tables_mut())
446        else {
447            return false;
448        };
449        let before = aot.len();
450        aot.retain(|t| t.get("path").and_then(|v| v.as_str()) != Some(path));
451        let changed = aot.len() != before;
452        if changed {
453            self.resync();
454        }
455        changed
456    }
457
458    /// 追加一条 `[[refs]]`。
459    pub fn push_ref(&mut self, r: &RefItem) {
460        let mut aot = self
461            .doc
462            .as_table()
463            .get("refs")
464            .and_then(|i| i.as_array_of_tables())
465            .cloned()
466            .unwrap_or_default();
467        aot.push(ref_to_table(r));
468        self.place_table("refs", Item::ArrayOfTables(aot));
469        self.resync();
470    }
471
472    /// 按 id 删除 `[[refs]]`。
473    pub fn remove_ref(&mut self, id: &str) -> bool {
474        let Some(aot) = self
475            .doc
476            .as_table_mut()
477            .get_mut("refs")
478            .and_then(|i| i.as_array_of_tables_mut())
479        else {
480            return false;
481        };
482        let before = aot.len();
483        aot.retain(|t| t.get("id").and_then(|v| v.as_str()) != Some(id));
484        let changed = aot.len() != before;
485        if changed {
486            self.resync();
487        }
488        changed
489    }
490
491    /// 规范 §4.9 归一化后的 TOML 文本(键序 / 表序固定,注释保留)。
492    ///
493    /// 属性是只读的派生视图:这里在**副本**上做规范化,不改动 `self.doc`。
494    pub fn canonical_text(&self, strip_comments: bool) -> String {
495        let mut doc = self.doc.clone();
496        crate::meta::canonicalize_doc(&mut doc);
497        let mut text = doc.to_string();
498        if !text.ends_with('\n') {
499            text.push('\n');
500        }
501        if strip_comments {
502            text = strip_line_comments(&text);
503        }
504        text
505    }
506
507    /// 保注释写回磁盘(写出的字节一律是 §4.9 规范形式)。
508    pub fn save(&self, path: &Path) -> Result<()> {
509        let text = self.canonical_text(false);
510        std::fs::write(path, text).map_err(|e| Error::io(path, e))
511    }
512}