Skip to main content

compmd/frontmatter/
written.rs

1//! A document's frontmatter as written (spec ยง2.1), for a tool that rewrites it: its syntax, its value with each
2//! mapping's keys in the order they are written, and the line each key is on.
3
4use std::collections::HashMap;
5
6use serde_json::Value;
7
8use crate::parse::frontmatter::{find, parse};
9
10pub use crate::parse::frontmatter::Format as Syntax;
11
12/// A frontmatter as written.
13///
14/// ```
15/// use compmd::frontmatter::{Syntax, Written};
16///
17/// let written = Written::of("---\ntitle: Notes\nmd:\n  lang: de\n---\n\n# Notes\n").expect("a frontmatter");
18/// assert_eq!(written.syntax, Syntax::Yaml);
19/// assert_eq!(written.value["md"]["lang"], "de");
20/// assert_eq!(written.key_lines["/md/lang"], 4);
21/// ```
22#[derive(Clone, Debug, PartialEq)]
23pub struct Written {
24    /// What it is written in.
25    pub syntax: Syntax,
26    /// Its value, each mapping's keys in written order; data imports' `from` as written.
27    pub value: Value,
28    /// The line each key is on, from 1 in the document, by JSON pointer (`/md/import/0/from`), whose steps are the
29    /// keys and indexes as they are.
30    pub key_lines: HashMap<String, usize>,
31}
32
33impl Written {
34    /// The frontmatter at the start of the document `text`; `None` when it has none, or one that doesn't read (F033).
35    #[must_use]
36    pub fn of(text: &str) -> Option<Self> {
37        let found = find(text)?;
38        let document = parse(found).ok()?;
39        // The frontmatter's text starts on the document's second line.
40        let key_lines = document
41            .keys
42            .into_iter()
43            .map(|(pointer, mark)| (pointer, mark.line + 1))
44            .collect();
45        Some(Self {
46            syntax: found.format,
47            value: document.value,
48            key_lines,
49        })
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use serde_json::json;
57
58    #[test]
59    fn toml_keys_have_their_lines_and_their_order() {
60        let written =
61            Written::of("+++\nzebra = 1\napple = 2\n[md]\nlang = \"de\"\n+++\n").expect("TOML");
62        assert_eq!(written.syntax, Syntax::Toml);
63        assert_eq!(
64            written.value,
65            json!({ "zebra": 1, "apple": 2, "md": { "lang": "de" } })
66        );
67        let keys: Vec<&String> = written
68            .value
69            .as_object()
70            .expect("a mapping")
71            .keys()
72            .collect();
73        assert_eq!(keys, ["zebra", "apple", "md"]);
74        assert_eq!(written.key_lines["/apple"], 3);
75        assert_eq!(written.key_lines["/md/lang"], 5);
76    }
77
78    #[test]
79    fn none_without_one_or_with_one_that_doesnt_read() {
80        assert_eq!(Written::of("# Notes\n"), None);
81        assert_eq!(Written::of("---\na: [\n---\n"), None);
82    }
83}