Skip to main content

trumly_core/
format.rs

1//! Writes a `Node` back out as a markdown file. The one place that decides what a canonical node file
2//! looks like, so files written by the editor, the CLI and the server are all byte-identical.
3//!
4//! Layout: id, type, title (only if it differs from the id), parent, plane, fields, links, then the body.
5
6use std::borrow::Cow;
7
8use saphyr::{Mapping, Scalar, Yaml, YamlEmitter};
9use serde_json::Value;
10
11use crate::model::{Fields, Node};
12
13type Y = Yaml<'static>;
14
15fn string(s: &str) -> Y {
16    Yaml::Value(Scalar::String(Cow::Owned(s.to_string())))
17}
18
19/// JSON value -> YAML value (the reverse of the conversion in parse.rs).
20fn to_yaml(v: &Value) -> Y {
21    match v {
22        Value::Null => Yaml::Value(Scalar::Null),
23        Value::Bool(b) => Yaml::Value(Scalar::Boolean(*b)),
24        Value::Number(n) => match n.as_i64() {
25            Some(i) => Yaml::Value(Scalar::Integer(i)),
26            None => Yaml::Value(Scalar::FloatingPoint(n.as_f64().unwrap_or(0.0).into())),
27        },
28        Value::String(s) => string(s),
29        Value::Array(a) => Yaml::Sequence(a.iter().map(to_yaml).collect()),
30        Value::Object(o) => {
31            let mut m = Mapping::new();
32            for (k, v) in o {
33                m.insert(string(k), to_yaml(v));
34            }
35            Yaml::Mapping(m)
36        }
37    }
38}
39
40fn fields_to_yaml(f: &Fields) -> Y {
41    let mut m = Mapping::new();
42    for (k, v) in f {
43        m.insert(string(k), to_yaml(v));
44    }
45    Yaml::Mapping(m)
46}
47
48/// The file text for a node: `---`, YAML frontmatter, `---`, then the markdown body.
49pub fn node_to_markdown(n: &Node) -> String {
50    let mut m = Mapping::new();
51    m.insert(string("id"), string(&n.id));
52    if let Some(k) = n.kind.as_deref().filter(|k| !k.is_empty()) {
53        m.insert(string("type"), string(k));
54    }
55    if n.title != n.id {
56        m.insert(string("title"), string(&n.title));
57    }
58    if let Some(p) = &n.parent {
59        m.insert(string("parent"), string(p));
60    }
61    if let Some(p) = &n.plane {
62        m.insert(string("plane"), string(p));
63    }
64    if !n.fields.is_empty() {
65        m.insert(string("fields"), fields_to_yaml(&n.fields));
66    }
67    if !n.links.is_empty() {
68        let links = n
69            .links
70            .iter()
71            .map(|l| {
72                let mut lm = Mapping::new();
73                lm.insert(string("type"), string(&l.kind));
74                lm.insert(string("to"), string(&l.to));
75                if let Some(k) = &l.key {
76                    lm.insert(string("key"), string(k));
77                }
78                if !l.fields.is_empty() {
79                    lm.insert(string("fields"), fields_to_yaml(&l.fields));
80                }
81                Yaml::Mapping(lm)
82            })
83            .collect();
84        m.insert(string("links"), Yaml::Sequence(links));
85    }
86
87    let mut out = String::new();
88    let mut emitter = YamlEmitter::new(&mut out);
89    emitter.multiline_strings(true);
90    emitter.dump(&Yaml::Mapping(m)).expect("writing to a String cannot fail");
91
92    // The emitter starts with its own `---` and does not end with a newline.
93    out.push_str("\n---\n");
94    let body = n.body.trim();
95    if !body.is_empty() {
96        out.push('\n');
97        out.push_str(body);
98        out.push('\n');
99    }
100    out
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106    use crate::model::Link;
107    use crate::parse::parse_node;
108    use crate::rules::json_eq;
109    use serde_json::json;
110
111    fn node(fields: Value) -> Node {
112        Node {
113            id: "a".into(),
114            kind: Some("thing".into()),
115            title: "a".into(),
116            parent: None,
117            plane: None,
118            fields: fields.as_object().unwrap().iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
119            links: vec![],
120            body: String::new(),
121        }
122    }
123
124    fn same(a: &Node, b: &Node) -> bool {
125        a.id == b.id
126            && a.kind == b.kind
127            && a.title == b.title
128            && a.parent == b.parent
129            && a.plane == b.plane
130            && a.body == b.body
131            && json_eq(&json!(a.fields), &json!(b.fields))
132            && a.links.len() == b.links.len()
133            && a.links.iter().zip(&b.links).all(|(x, y)| x.kind == y.kind && x.to == y.to && x.key == y.key && json_eq(&json!(x.fields), &json!(y.fields)))
134    }
135
136    #[test]
137    fn layout_is_canonical() {
138        let mut n = node(json!({"note": "hi"}));
139        n.title = "Alpha".into();
140        n.parent = Some("g".into());
141        n.links.push(Link { kind: "uses".into(), to: "b".into(), key: Some("k".into()), fields: Fields::new() });
142        n.body = "# Heading\n\nText.".into();
143        let text = node_to_markdown(&n);
144        assert_eq!(text, "---\nid: a\ntype: thing\ntitle: Alpha\nparent: g\nfields:\n  note: hi\nlinks:\n  - type: uses\n    to: b\n    key: k\n---\n\n# Heading\n\nText.\n");
145    }
146
147    #[test]
148    fn round_trips_awkward_values() {
149        let awkward = json!({
150            "yes": "no", "num_string": "123", "bool_string": "true", "null_string": "null", "empty": "",
151            "colon": "a: b", "hash": "# not a comment", "dash": "- item", "lead": "  spaced", "trail": "spaced  ",
152            "multi": "line one\nline two\n", "multi2": "no trailing newline\nsecond", "quote": "it's \"quoted\"",
153            "unicode": "naïve — café ✓", "date": "2026-10-19", "float_string": "1.0", "tilde": "~", "brace": "{x}", "bracket": "[x]",
154            "int": 42, "neg": -7, "float": 1.5, "t": true, "f": false, "nil": null,
155            "list": [1, "two", [3], {"k": "v"}], "map": {"nested": {"deep": ["x"]}}, "emptylist": [], "emptymap": {}
156        });
157        let n = node(awkward);
158        let text = node_to_markdown(&n);
159        let back = parse_node(&text).unwrap_or_else(|e| panic!("{e:?}\n{text}"));
160        assert!(same(&n, &back), "round trip differs:\n{text}\n{:?}\n{:?}", n.fields, back.fields);
161    }
162
163    #[test]
164    fn formatting_twice_changes_nothing() {
165        let n = node(json!({"multi": "a\nb\n", "list": [1, 2]}));
166        let once = node_to_markdown(&n);
167        let twice = node_to_markdown(&parse_node(&once).unwrap());
168        assert_eq!(once, twice);
169    }
170}