1use std::path::Path;
6
7use serde_json::{Map as JMap, Value as JValue};
8use toml_edit::{DocumentMut, Item, Table};
9
10use crate::error::{Error, Issue, Result, code};
11use crate::util;
12
13pub const TOP_BARE_KEYS: &[&str] = &[
17 "str",
18 "spec",
19 "kind",
20 "id",
21 "name",
22 "type",
23 "title",
24 "summary",
25 "tags",
26 "revision",
27 "created_at",
28 "updated_at",
29 "schema",
30];
31
32pub const TABLE_ORDER: &[&str] = &["policies", "authors", "refs", "entries", "ext"];
34
35pub const POLICIES_KEYS: &[&str] = &[
37 "id_version",
38 "max_depth",
39 "manifest",
40 "sha256",
41 "ignore",
42 "gitignore",
43 "large_asset_bytes",
44 "deep_tree_warn",
45];
46
47pub const AUTHOR_KEYS: &[&str] = &["id", "name", "role", "at"];
49
50pub const REF_KEYS: &[&str] = &["id", "target", "rel", "title", "order", "note"];
52
53pub const ENTRY_KEYS: &[&str] = &[
55 "path",
56 "role",
57 "id",
58 "type",
59 "title",
60 "summary",
61 "order",
62 "media_type",
63 "size",
64 "sha256",
65 "count",
66 "schema",
67 "optional",
68 "note",
69];
70
71pub const ROOT_ALLOWED: &[&str] = &[
73 "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
74 "created_at", "updated_at", "schema", "policies", "authors", "refs", "entries", "ext",
75];
76
77pub const BRANCH_ALLOWED: &[&str] = &[
79 "str", "spec", "kind", "id", "name", "type", "title", "summary", "tags", "revision",
80 "created_at", "updated_at", "schema", "authors", "refs", "entries", "ext",
81];
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Kind {
88 Root,
90 Node,
92 Branch,
94}
95
96impl Kind {
97 pub fn as_str(self) -> &'static str {
99 match self {
100 Kind::Root => "root",
101 Kind::Node => "node",
102 Kind::Branch => "branch",
103 }
104 }
105
106 pub fn parse(s: &str) -> Option<Kind> {
108 match s {
109 "root" => Some(Kind::Root),
110 "node" => Some(Kind::Node),
111 "branch" => Some(Kind::Branch),
112 _ => None,
113 }
114 }
115
116 pub fn allowed_top_keys(self) -> &'static [&'static str] {
118 match self {
119 Kind::Root => ROOT_ALLOWED,
120 _ => BRANCH_ALLOWED,
121 }
122 }
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ManifestPolicy {
128 Strict,
130 Advisory,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum ShaPolicy {
137 Required,
139 Optional,
141 Off,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Policies {
148 pub id_version: usize,
150 pub max_depth: usize,
152 pub manifest: ManifestPolicy,
154 pub sha256: ShaPolicy,
156 pub ignore: Vec<String>,
158 pub gitignore: bool,
160 pub large_asset_bytes: u64,
162 pub deep_tree_warn: usize,
164}
165
166impl Default for Policies {
167 fn default() -> Self {
168 Self {
169 id_version: 7,
170 max_depth: 32,
171 manifest: ManifestPolicy::Strict,
172 sha256: ShaPolicy::Required,
173 ignore: Vec::new(),
174 gitignore: true,
175 large_asset_bytes: 10 * 1024 * 1024,
176 deep_tree_warn: 16,
177 }
178 }
179}
180
181#[derive(Debug, Clone, Default, PartialEq, Eq)]
183pub struct Author {
184 pub id: String,
186 pub name: Option<String>,
188 pub role: String,
190 pub at: Option<String>,
192}
193
194#[derive(Debug, Clone, Default, PartialEq, Eq)]
196pub struct RefItem {
197 pub id: String,
199 pub target: String,
201 pub rel: String,
203 pub title: Option<String>,
205 pub order: Option<i64>,
207 pub note: Option<String>,
209}
210
211#[derive(Debug, Clone, Default, PartialEq, Eq)]
213pub struct Entry {
214 pub path: String,
216 pub role: String,
218 pub id: Option<String>,
220 pub r#type: Option<String>,
222 pub title: Option<String>,
224 pub summary: Option<String>,
226 pub order: Option<i64>,
228 pub media_type: Option<String>,
230 pub size: Option<i64>,
232 pub sha256: Option<String>,
234 pub count: Option<i64>,
236 pub schema: Option<String>,
238 pub optional: bool,
240 pub note: Option<String>,
242}
243
244impl Entry {
245 pub fn is_branch(&self) -> bool {
247 self.role == "node" || self.role == "branch"
248 }
249
250 pub fn is_file_like(&self) -> bool {
252 self.role == "payload" || self.role == "asset"
253 }
254}
255
256#[derive(Debug)]
258pub struct Meta {
259 pub doc: DocumentMut,
261 pub str_version: Option<i64>,
263 pub spec: Option<String>,
265 pub kind_raw: Option<String>,
267 pub kind: Option<Kind>,
269 pub id: Option<String>,
271 pub name: Option<String>,
273 pub r#type: Option<String>,
275 pub title: Option<String>,
277 pub summary: Option<String>,
279 pub tags: Vec<String>,
281 pub revision: Option<i64>,
283 pub created_at: Option<String>,
285 pub updated_at: Option<String>,
287 pub schema: Option<String>,
289 pub policies: Policies,
291 pub authors: Vec<Author>,
293 pub refs: Vec<RefItem>,
295 pub entries: Vec<Entry>,
297}
298
299pub enum MetaLoad {
301 Ok(Box<Meta>, Vec<Issue>),
303 Failed(Vec<Issue>),
305}
306
307pub fn load(path: &Path, rel: &str) -> Result<MetaLoad> {
309 let bytes = std::fs::read(path).map_err(|e| Error::io(path, e))?;
310 let mut issues = Vec::new();
311
312 if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) {
314 issues.push(Issue::error(
315 code::PARSE,
316 rel,
317 "文件含 UTF-8 BOM,规范要求 UTF-8 无 BOM",
318 ));
319 return Ok(MetaLoad::Failed(issues));
320 }
321 let text = match std::str::from_utf8(&bytes) {
322 Ok(t) => t,
323 Err(e) => {
324 issues.push(Issue::error(
325 code::PARSE,
326 rel,
327 format!("编码非 UTF-8:{e}"),
328 ));
329 return Ok(MetaLoad::Failed(issues));
330 }
331 };
332
333 let doc: DocumentMut = match text.parse() {
334 Ok(d) => d,
335 Err(e) => {
336 issues.push(Issue::error(code::PARSE, rel, format!("TOML 解析失败:{e}")));
337 return Ok(MetaLoad::Failed(issues));
338 }
339 };
340
341 let (meta, mut field_issues) = extract(doc, rel);
342 issues.append(&mut field_issues);
343 Ok(MetaLoad::Ok(Box::new(meta), issues))
344}
345
346pub fn extract(doc: DocumentMut, rel: &str) -> (Meta, Vec<Issue>) {
348 let mut cx = Ctx {
349 rel: rel.to_string(),
350 issues: Vec::new(),
351 };
352 let table = doc.as_table().clone();
353
354 let str_version = cx.opt_int(&table, "str");
355 let spec = cx.opt_str(&table, "spec");
356 let kind_raw = cx.opt_str(&table, "kind");
357 let kind = match kind_raw.as_deref() {
358 Some(s) => match Kind::parse(s) {
359 Some(k) => Some(k),
360 None => {
361 cx.err(
362 code::KIND_INVALID,
363 format!("`kind` = {s:?} 非法(应为 root / node / branch)"),
364 );
365 None
366 }
367 },
368 None => {
369 cx.err(code::SCHEMA_FIELD, "缺少必填字段 `kind`");
370 None
371 }
372 };
373
374 let allowed = kind.map(|k| k.allowed_top_keys()).unwrap_or(BRANCH_ALLOWED);
375 cx.check_unknown(&table, allowed);
376
377 for key in ["id", "revision", "created_at", "updated_at"] {
380 if table.get(key).is_none() {
381 cx.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
382 }
383 }
384
385 let id = cx.opt_str(&table, "id");
386 let name = cx.opt_str(&table, "name");
387 let r#type = cx.opt_str(&table, "type");
388 let title = cx.opt_str(&table, "title");
389 let summary = cx.opt_str(&table, "summary");
390 let tags = cx.opt_str_array(&table, "tags").unwrap_or_default();
391 let revision = cx.opt_int(&table, "revision");
392 let created_at = cx.opt_dt(&table, "created_at");
393 let updated_at = cx.opt_dt(&table, "updated_at");
394 let schema = cx.opt_str(&table, "schema");
395
396 let mut policies = Policies::default();
398 if let Some(item) = table.get("policies") {
399 match item.as_table() {
400 Some(pt) => {
401 if kind != Some(Kind::Root) {
402 cx.err(
403 code::SCHEMA_FIELD,
404 "`[policies]` 只能出现在 root 的 `._meta` 中",
405 );
406 }
407 cx.check_unknown(pt, POLICIES_KEYS);
408 if let Some(v) = cx.opt_int(pt, "id_version") {
409 policies.id_version = v.max(0) as usize;
410 }
411 if let Some(v) = cx.opt_int(pt, "max_depth") {
412 policies.max_depth = v.max(1) as usize;
413 }
414 if let Some(v) = cx.opt_str(pt, "manifest") {
415 policies.manifest = match v.as_str() {
416 "strict" => ManifestPolicy::Strict,
417 "advisory" => ManifestPolicy::Advisory,
418 _ => {
419 cx.err(
420 code::SCHEMA_FIELD,
421 format!("`policies.manifest` = {v:?} 非法(strict / advisory)"),
422 );
423 policies.manifest
424 }
425 };
426 }
427 if let Some(v) = cx.opt_str(pt, "sha256") {
428 policies.sha256 = match v.as_str() {
429 "required" => ShaPolicy::Required,
430 "optional" => ShaPolicy::Optional,
431 "off" => ShaPolicy::Off,
432 _ => {
433 cx.err(
434 code::SCHEMA_FIELD,
435 format!("`policies.sha256` = {v:?} 非法(required / optional / off)"),
436 );
437 policies.sha256
438 }
439 };
440 }
441 if let Some(v) = cx.opt_str_array(pt, "ignore") {
442 policies.ignore = v.into_iter().filter(|s| !s.trim().is_empty()).collect();
443 }
444 if let Some(item) = pt.get("gitignore") {
445 match item.as_bool() {
446 Some(b) => policies.gitignore = b,
447 None => cx.err(
448 code::SCHEMA_FIELD,
449 "`policies.gitignore` 必须是布尔值",
450 ),
451 }
452 }
453 if let Some(v) = cx.opt_int(pt, "large_asset_bytes") {
454 policies.large_asset_bytes = v.max(0) as u64;
455 }
456 if let Some(v) = cx.opt_int(pt, "deep_tree_warn") {
457 policies.deep_tree_warn = v.max(1) as usize;
458 }
459 }
460 None => cx.err(code::SCHEMA_FIELD, "`policies` 必须是表 `[policies]`"),
461 }
462 }
463
464 let mut authors = Vec::new();
466 if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
467 for (i, t) in aot.iter().enumerate() {
468 cx.set_rel(&format!("{rel} #authors[{i}]"));
469 cx.check_unknown(t, AUTHOR_KEYS);
470 let aid = cx.req_str(t, "id").unwrap_or_default();
471 let role = cx.req_str(t, "role").unwrap_or_default();
472 let aname = cx.opt_str(t, "name");
473 let at = cx.opt_dt(t, "at");
474 authors.push(Author {
475 id: aid,
476 name: aname,
477 role,
478 at,
479 });
480 }
481 cx.set_rel(rel);
482 } else if table.get("authors").is_some() {
483 cx.err(code::SCHEMA_FIELD, "`authors` 必须是数组表 `[[authors]]`");
484 }
485
486 let mut refs = Vec::new();
488 if let Some(aot) = table.get("refs").and_then(|i| i.as_array_of_tables()) {
489 for (i, t) in aot.iter().enumerate() {
490 cx.set_rel(&format!("{rel} #refs[{i}]"));
491 cx.check_unknown(t, REF_KEYS);
492 refs.push(RefItem {
493 id: cx.req_str(t, "id").unwrap_or_default(),
494 target: cx.req_str(t, "target").unwrap_or_default(),
495 rel: cx.req_str(t, "rel").unwrap_or_default(),
496 title: cx.opt_str(t, "title"),
497 order: cx.opt_int(t, "order"),
498 note: cx.opt_str(t, "note"),
499 });
500 }
501 cx.set_rel(rel);
502 } else if table.get("refs").is_some() {
503 cx.err(code::SCHEMA_FIELD, "`refs` 必须是数组表 `[[refs]]`");
504 }
505
506 let mut entries = Vec::new();
508 if let Some(aot) = table.get("entries").and_then(|i| i.as_array_of_tables()) {
509 for (i, t) in aot.iter().enumerate() {
510 cx.set_rel(&format!("{rel} #entries[{i}]"));
511 cx.check_unknown(t, ENTRY_KEYS);
512 let path = cx.req_str(t, "path").unwrap_or_default();
513 let role = cx.req_str(t, "role").unwrap_or_default();
514 if path.contains('/') {
515 cx.err(
516 code::SCHEMA_FIELD,
517 format!("`entries[].path` = {path:?} 必须是单段路径(不含 `/`)"),
518 );
519 }
520 let e = Entry {
521 path,
522 role,
523 id: cx.opt_str(t, "id"),
524 r#type: cx.opt_str(t, "type"),
525 title: cx.opt_str(t, "title"),
526 summary: cx.opt_str(t, "summary"),
527 order: cx.opt_int(t, "order"),
528 media_type: cx.opt_str(t, "media_type"),
529 size: cx.opt_int(t, "size"),
530 sha256: cx.opt_str(t, "sha256"),
531 count: cx.opt_int(t, "count"),
532 schema: cx.opt_str(t, "schema"),
533 optional: cx.opt_bool(t, "optional").unwrap_or(false),
534 note: cx.opt_str(t, "note"),
535 };
536 entries.push(e);
537 }
538 cx.set_rel(rel);
539 } else if table.get("entries").is_some() {
540 cx.err(code::SCHEMA_FIELD, "`entries` 必须是数组表 `[[entries]]`");
541 }
542
543 let meta = Meta {
544 doc,
545 str_version,
546 spec,
547 kind_raw,
548 kind,
549 id,
550 name,
551 r#type,
552 title,
553 summary,
554 tags,
555 revision,
556 created_at,
557 updated_at,
558 schema,
559 policies,
560 authors,
561 refs,
562 entries,
563 };
564 (meta, cx.issues)
565}
566
567pub fn canonicalize_doc(doc: &mut DocumentMut) {
575 let top_rank = |k: &str, it: &Item| -> usize {
578 match it {
579 Item::Table(_) | Item::ArrayOfTables(_) => {
580 TOP_BARE_KEYS.len()
581 + 1
582 + TABLE_ORDER
583 .iter()
584 .position(|x| *x == k)
585 .unwrap_or(TABLE_ORDER.len())
586 }
587 _ => TOP_BARE_KEYS
588 .iter()
589 .position(|x| *x == k)
590 .unwrap_or(TOP_BARE_KEYS.len()),
591 }
592 };
593 doc.as_table_mut()
594 .sort_values_by(|k1, i1, k2, i2| top_rank(k1.get(), i1).cmp(&top_rank(k2.get(), i2)));
595
596 for (key, order) in [
598 ("policies", POLICIES_KEYS),
599 ("authors", AUTHOR_KEYS),
600 ("refs", REF_KEYS),
601 ("entries", ENTRY_KEYS),
602 ] {
603 let rank = |k: &str| order.iter().position(|x| *x == k).unwrap_or(usize::MAX);
604 match doc.as_table_mut().get_mut(key) {
605 Some(Item::Table(t)) => {
606 t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
607 }
608 Some(Item::ArrayOfTables(a)) => {
609 for t in a.iter_mut() {
610 t.sort_values_by(|k1, _, k2, _| rank(k1.get()).cmp(&rank(k2.get())));
611 }
612 }
613 _ => {}
614 }
615 }
616
617 sort_collections_in(doc);
619
620 renumber_positions_in(doc);
622}
623
624fn collection_sort_key(t: &Table) -> (i64, String) {
626 let order = t
627 .get("order")
628 .and_then(Item::as_integer)
629 .unwrap_or(i64::MAX);
630 let id = t
631 .get("path")
632 .or_else(|| t.get("id"))
633 .and_then(Item::as_str)
634 .unwrap_or("")
635 .to_string();
636 (order, id)
637}
638
639fn sort_collections_in(doc: &mut DocumentMut) {
641 for key in ["entries", "refs"] {
642 let Some(aot) = doc
643 .as_table_mut()
644 .get_mut(key)
645 .and_then(Item::as_array_of_tables_mut)
646 else {
647 continue;
648 };
649 let mut items: Vec<Table> = aot.iter().cloned().collect();
650 items.sort_by_key(collection_sort_key);
651 for (slot, table) in aot.iter_mut().zip(items) {
652 *slot = table;
653 }
654 }
655}
656
657fn renumber_positions_in(doc: &mut DocumentMut) {
663 fn walk(t: &mut Table, pos: &mut isize) {
664 *pos += 1;
665 t.set_position(Some(*pos));
666 for (_, item) in t.iter_mut() {
667 match item {
668 Item::Table(child) => walk(child, pos),
669 Item::ArrayOfTables(a) => {
670 for child in a.iter_mut() {
671 walk(child, pos);
672 }
673 }
674 _ => {}
675 }
676 }
677 }
678 let mut pos = 0isize;
679 walk(doc.as_table_mut(), &mut pos);
680}
681
682impl Meta {
685 pub fn to_json(&self) -> JValue {
688 let table = self.doc.as_table();
689 let mut map = JMap::new();
690
691 for key in TOP_BARE_KEYS {
692 if let Some(item) = table.get(key) {
693 map.insert((*key).to_string(), item_to_json(item));
694 }
695 }
696 if let Some(item) = table.get("policies") {
697 match item.as_table() {
698 Some(t) => {
699 map.insert("policies".into(), table_to_json(t, POLICIES_KEYS));
700 }
701 None => {
702 map.insert("policies".into(), item_to_json(item));
703 }
704 }
705 }
706 if let Some(aot) = table.get("authors").and_then(|i| i.as_array_of_tables()) {
707 map.insert(
708 "authors".into(),
709 JValue::Array(
710 aot.iter()
711 .map(|t| table_to_json(t, AUTHOR_KEYS))
712 .collect(),
713 ),
714 );
715 }
716 map.insert(
718 "refs".into(),
719 match table.get("refs").and_then(|i| i.as_array_of_tables()) {
720 Some(aot) => JValue::Array(
721 aot.iter()
722 .map(|t| table_to_json(t, REF_KEYS))
723 .collect(),
724 ),
725 None => JValue::Array(Vec::new()),
726 },
727 );
728 map.insert(
729 "entries".into(),
730 match table.get("entries").and_then(|i| i.as_array_of_tables()) {
731 Some(aot) => JValue::Array(
732 aot.iter()
733 .map(|t| table_to_json(t, ENTRY_KEYS))
734 .collect(),
735 ),
736 None => JValue::Array(Vec::new()),
737 },
738 );
739 if let Some(item) = table.get("ext") {
740 map.insert("ext".into(), item_to_json(item));
741 }
742 for (k, v) in table.iter() {
744 if !map.contains_key(k) {
745 map.insert(k.to_string(), item_to_json(v));
746 }
747 }
748 JValue::Object(map)
749 }
750
751 pub fn sort_collections(&mut self) {
753 sort_collections_in(&mut self.doc);
754 renumber_positions_in(&mut self.doc);
755 }
756
757 pub fn canonicalize(&mut self) {
759 canonicalize_doc(&mut self.doc);
760 }
761
762 pub fn revision_issues(&self, rel: &str) -> Vec<Issue> {
764 let mut out = Vec::new();
765 match self.revision {
766 None => {}
767 Some(r) if r < 1 => out.push(Issue::error(
768 code::REVISION_STALE,
769 rel,
770 format!("`revision` = {r},必须为 ≥ 1 的整数"),
771 )),
772 Some(_) => {}
773 }
774 if let (Some(c), Some(u)) = (self.created_at.as_deref(), self.updated_at.as_deref()) {
775 match (util::parse_rfc3339(c), util::parse_rfc3339(u)) {
776 (Some(cd), Some(ud)) if ud < cd => out.push(Issue::error(
777 code::REVISION_STALE,
778 rel,
779 format!("`updated_at`({u})早于 `created_at`({c})"),
780 )),
781 _ => {}
782 }
783 }
784 out
785 }
786}
787
788fn item_to_json(item: &Item) -> JValue {
790 match item {
791 Item::None => JValue::Null,
792 Item::Value(v) => value_to_json(v),
793 Item::Table(t) => {
794 let mut m = JMap::new();
795 for (k, v) in t.iter() {
796 m.insert(k.to_string(), item_to_json(v));
797 }
798 JValue::Object(m)
799 }
800 Item::ArrayOfTables(aot) => JValue::Array(
801 aot.iter()
802 .map(|t| {
803 let mut m = JMap::new();
804 for (k, v) in t.iter() {
805 m.insert(k.to_string(), item_to_json(v));
806 }
807 JValue::Object(m)
808 })
809 .collect(),
810 ),
811 }
812}
813
814fn value_to_json(v: &toml_edit::Value) -> JValue {
816 if let Some(s) = v.as_str() {
817 return JValue::String(s.to_string());
818 }
819 if let Some(i) = v.as_integer() {
820 return JValue::from(i);
821 }
822 if let Some(f) = v.as_float() {
823 return serde_json::Number::from_f64(f)
824 .map(JValue::Number)
825 .unwrap_or(JValue::Null);
826 }
827 if let Some(b) = v.as_bool() {
828 return JValue::Bool(b);
829 }
830 if let Some(d) = v.as_datetime() {
831 return JValue::String(d.to_string());
832 }
833 if let Some(a) = v.as_array() {
834 return JValue::Array(a.iter().map(value_to_json).collect());
835 }
836 if let Some(t) = v.as_inline_table() {
837 let mut m = JMap::new();
838 for (k, val) in t.iter() {
839 m.insert(k.to_string(), value_to_json(val));
840 }
841 return JValue::Object(m);
842 }
843 JValue::Null
844}
845
846fn table_to_json(table: &Table, order: &[&str]) -> JValue {
848 let mut m = JMap::new();
849 for k in order {
850 if let Some(v) = table.get(k) {
851 m.insert((*k).to_string(), item_to_json(v));
852 }
853 }
854 for (k, v) in table.iter() {
855 if !m.contains_key(k) {
856 m.insert(k.to_string(), item_to_json(v));
857 }
858 }
859 JValue::Object(m)
860}
861
862struct Ctx {
866 rel: String,
867 issues: Vec<Issue>,
868}
869
870impl Ctx {
871 fn set_rel(&mut self, rel: &str) {
872 self.rel = rel.to_string();
873 }
874
875 fn err(&mut self, code: &'static str, message: impl Into<String>) {
876 self.issues
877 .push(Issue::error(code, self.rel.clone(), message));
878 }
879
880 fn check_unknown(&mut self, t: &Table, allowed: &[&str]) {
881 for (k, _) in t.iter() {
882 if !allowed.contains(&k) {
883 self.err(
884 code::SCHEMA_FIELD,
885 format!("未知字段 `{k}`(扩展请放入 `[ext]`)"),
886 );
887 }
888 }
889 }
890
891 fn req_str(&mut self, t: &Table, key: &str) -> Option<String> {
892 match t.get(key) {
893 None => {
894 self.err(code::SCHEMA_FIELD, format!("缺少必填字段 `{key}`"));
895 None
896 }
897 Some(item) => match item.as_str() {
898 Some(s) => Some(s.to_string()),
899 None => {
900 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
901 None
902 }
903 },
904 }
905 }
906
907 fn opt_str(&mut self, t: &Table, key: &str) -> Option<String> {
908 match t.get(key) {
909 None => None,
910 Some(item) => match item.as_str() {
911 Some(s) => Some(s.to_string()),
912 None => {
913 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串"));
914 None
915 }
916 },
917 }
918 }
919
920 fn opt_int(&mut self, t: &Table, key: &str) -> Option<i64> {
921 match t.get(key) {
922 None => None,
923 Some(item) => match item.as_integer() {
924 Some(i) => Some(i),
925 None => {
926 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是整数"));
927 None
928 }
929 },
930 }
931 }
932
933 fn opt_bool(&mut self, t: &Table, key: &str) -> Option<bool> {
934 match t.get(key) {
935 None => None,
936 Some(item) => match item.as_bool() {
937 Some(b) => Some(b),
938 None => {
939 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是布尔值"));
940 None
941 }
942 },
943 }
944 }
945
946 fn opt_dt(&mut self, t: &Table, key: &str) -> Option<String> {
948 let Some(item) = t.get(key) else {
949 return None;
950 };
951 if item.as_str().is_some() {
952 self.err(
953 code::PARSE,
954 format!("`{key}` 必须使用 TOML 原生 offset date-time,不得写成字符串"),
955 );
956 return None;
957 }
958 match item.as_datetime() {
959 Some(d) => {
960 if d.date.is_none() || d.time.is_none() || d.offset.is_none() {
961 self.err(
962 code::PARSE,
963 format!("`{key}` 必须是带时区偏移的 offset date-time(如 2026-09-14T10:03:11+08:00)"),
964 );
965 return None;
966 }
967 Some(d.to_string())
968 }
969 None => {
970 self.err(
971 code::PARSE,
972 format!("`{key}` 必须是 offset date-time"),
973 );
974 None
975 }
976 }
977 }
978
979 fn opt_str_array(&mut self, t: &Table, key: &str) -> Option<Vec<String>> {
980 let Some(item) = t.get(key) else {
981 return None;
982 };
983 let Some(arr) = item.as_array() else {
984 self.err(code::SCHEMA_FIELD, format!("`{key}` 必须是字符串数组"));
985 return None;
986 };
987 let mut out = Vec::new();
988 for v in arr.iter() {
989 match v.as_str() {
990 Some(s) => out.push(s.to_string()),
991 None => {
992 self.err(code::SCHEMA_FIELD, format!("`{key}` 的元素必须是字符串"));
993 }
994 }
995 }
996 Some(out)
997 }
998}