1use saphyr::{LoadableYamlNode, ScalarOwned, YamlOwned};
5use serde_json::{Map, Number, Value};
6
7use crate::model::{Fields, Link, Node};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ParseError {
13 InvalidFrontmatter,
15 MissingId,
17}
18
19impl ParseError {
20 pub fn as_str(self) -> &'static str {
22 match self {
23 ParseError::InvalidFrontmatter => "invalid_frontmatter",
24 ParseError::MissingId => "missing_id",
25 }
26 }
27}
28
29fn split_frontmatter(text: &str) -> Option<(String, String)> {
32 let text = text.replace("\r\n", "\n");
34 let mut lines = text.split('\n');
36 if lines.next()?.trim_end_matches([' ', '\t']) != "---" {
37 return None;
38 }
39 let mut yaml: Vec<&str> = Vec::new();
40 for line in lines.by_ref() {
41 if line.trim_end_matches([' ', '\t']) == "---" {
42 let body: Vec<&str> = lines.collect();
44 return Some((yaml.join("\n"), body.join("\n").trim().to_string()));
45 }
46 yaml.push(line);
47 }
48 None
49}
50
51fn to_json(y: &YamlOwned) -> Option<Value> {
54 match y {
55 YamlOwned::Value(s) => match s {
56 ScalarOwned::Null => Some(Value::Null),
57 ScalarOwned::Boolean(b) => Some(Value::Bool(*b)),
58 ScalarOwned::Integer(i) => Some(Value::from(*i)),
59 ScalarOwned::FloatingPoint(f) => Number::from_f64(f.into_inner()).map(Value::Number),
60 ScalarOwned::String(s) => Some(Value::String(s.clone())),
61 },
62 YamlOwned::Sequence(seq) => seq.iter().map(to_json).collect::<Option<Vec<_>>>().map(Value::Array),
63 YamlOwned::Mapping(map) => {
64 let mut out = Map::new();
65 for (k, v) in map {
66 let key = k.as_str()?; out.insert(key.to_string(), to_json(v)?);
68 }
69 Some(Value::Object(out))
70 }
71 _ => None,
72 }
73}
74
75fn non_empty(v: &Value) -> Option<String> {
77 match v {
78 Value::String(s) if !s.is_empty() => Some(s.clone()),
79 _ => None,
80 }
81}
82
83fn opt_string(m: &Map<String, Value>, key: &str) -> Option<Option<String>> {
86 match m.get(key) {
87 None | Some(Value::Null) => Some(None),
88 Some(Value::String(s)) => Some(Some(s.clone())),
89 _ => None,
90 }
91}
92
93fn opt_map(m: &Map<String, Value>, key: &str) -> Option<Fields> {
95 match m.get(key) {
96 None | Some(Value::Null) => Some(Fields::new()),
97 Some(Value::Object(o)) => Some(o.iter().map(|(k, v)| (k.clone(), v.clone())).collect()),
98 _ => None,
99 }
100}
101
102fn parse_link(v: &Value) -> Option<Link> {
103 let m = v.as_object()?;
104 let kind = non_empty(m.get("type")?)?;
105 let to = non_empty(m.get("to")?)?;
106 let key = opt_string(m, "key")?.filter(|k| !k.is_empty());
108 let fields = opt_map(m, "fields")?;
109 Some(Link { kind, to, key, fields })
110}
111
112pub fn node_from_map(fm: &Map<String, Value>, body: String) -> Result<Node, ParseError> {
115 use ParseError::*;
116
117 let id = match fm.get("id") {
119 None | Some(Value::Null) => return Err(MissingId),
120 Some(v) => non_empty(v).ok_or(InvalidFrontmatter)?,
121 };
122
123 let kind = opt_string(fm, "type").ok_or(InvalidFrontmatter)?;
124 let title = opt_string(fm, "title").ok_or(InvalidFrontmatter)?;
125 let parent = opt_string(fm, "parent").ok_or(InvalidFrontmatter)?;
126 let plane = opt_string(fm, "plane").ok_or(InvalidFrontmatter)?;
127 let fields = opt_map(fm, "fields").ok_or(InvalidFrontmatter)?;
128
129 let links = match fm.get("links") {
130 None | Some(Value::Null) => Vec::new(),
131 Some(Value::Array(a)) => a.iter().map(parse_link).collect::<Option<Vec<_>>>().ok_or(InvalidFrontmatter)?,
132 _ => return Err(InvalidFrontmatter),
133 };
134
135 Ok(Node {
136 title: title.filter(|t| !t.is_empty()).unwrap_or_else(|| id.clone()),
138 id,
139 kind,
140 parent,
141 plane,
142 fields,
143 links,
144 body,
145 })
146}
147
148pub fn parse_node(text: &str) -> Result<Node, ParseError> {
150 use ParseError::InvalidFrontmatter;
151
152 let (yaml_text, body) = split_frontmatter(text).ok_or(InvalidFrontmatter)?;
153 let docs = YamlOwned::load_from_str(&yaml_text).map_err(|_| InvalidFrontmatter)?;
154 let doc = docs.first().ok_or(InvalidFrontmatter)?;
155 match to_json(doc) {
156 Some(Value::Object(m)) => node_from_map(&m, body),
157 _ => Err(InvalidFrontmatter),
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use super::*;
164
165 #[test]
166 fn minimal() {
167 let n = parse_node("---\nid: a\ntype: thing\n---\n").unwrap();
168 assert_eq!(n.id, "a");
169 assert_eq!(n.kind.as_deref(), Some("thing"));
170 assert_eq!(n.title, "a"); assert_eq!(n.body, "");
172 }
173
174 #[test]
175 fn full_node() {
176 let src = "---\nid: a\ntype: t\ntitle: Alpha\nparent: g\nplane: p\nfields:\n n: 1\n ok: true\nlinks:\n - type: uses\n to: b\n key: k\n fields: { verbs: [append] }\n---\n\n# Hi\n";
177 let n = parse_node(src).unwrap();
178 assert_eq!(n.title, "Alpha");
179 assert_eq!(n.parent.as_deref(), Some("g"));
180 assert_eq!(n.fields["n"], Value::from(1));
181 assert_eq!(n.fields["ok"], Value::Bool(true));
182 assert_eq!(n.links[0].key.as_deref(), Some("k"));
183 assert_eq!(n.links[0].fields["verbs"], serde_json::json!(["append"]));
184 assert_eq!(n.body, "# Hi");
185 }
186
187 #[test]
188 fn crlf_and_dashes_in_body() {
189 let n = parse_node("---\r\nid: a\r\ntype: doc\r\n---\r\n\r\nText\r\n---\r\nmore\r\n").unwrap();
190 assert_eq!(n.body, "Text\n---\nmore");
191 }
192
193 #[test]
194 fn yaml_12_keeps_no_as_a_string() {
195 let n = parse_node("---\nid: a\ntype: t\nfields:\n x: no\n---\n").unwrap();
196 assert_eq!(n.fields["x"], Value::String("no".into()));
197 }
198
199 #[test]
200 fn errors() {
201 assert_eq!(parse_node("no frontmatter"), Err(ParseError::InvalidFrontmatter));
202 assert_eq!(parse_node("---\nid: [unclosed\n---\n"), Err(ParseError::InvalidFrontmatter));
203 assert_eq!(parse_node("---\n- a\n- b\n---\n"), Err(ParseError::InvalidFrontmatter));
204 assert_eq!(parse_node("---\ntype: t\n---\n"), Err(ParseError::MissingId));
205 assert_eq!(parse_node("---\nid: a\nparent: 5\n---\n"), Err(ParseError::InvalidFrontmatter));
206 assert_eq!(parse_node("---\nid: a\nlinks:\n - type: x\n---\n"), Err(ParseError::InvalidFrontmatter));
207 }
208}