Skip to main content

gitpoulpi_hosting/local_markdown/
frontmatter.rs

1//! A minimal YAML frontmatter reader/writer for issue notes.
2//!
3//! Not a YAML parser: it understands exactly what an Obsidian properties
4//! block holds (`key: scalar`, `key: [a, b]`, `key:` + `- a` lines) and
5//! keeps **everything else byte for byte**. The block is split into
6//! segments, one per top-level key (plus any leading comment lines); a
7//! segment keeps its original text, including its line endings, and is only
8//! regenerated when the key is set through [`Frontmatter::set_scalar`] /
9//! [`Frontmatter::set_list`]. Key order never changes.
10
11/// One top-level entry of the block, or the comment lines before the first.
12#[derive(Debug, Clone, PartialEq, Eq)]
13struct Segment {
14    /// `None` for lines before the first key.
15    key: Option<String>,
16    /// The exact original text, line terminators included.
17    text: String,
18}
19
20/// The parsed frontmatter block (the lines between the two `---` fences).
21#[derive(Debug, Clone, PartialEq, Eq, Default)]
22pub struct Frontmatter {
23    segments: Vec<Segment>,
24}
25
26/// A file split into its pieces; joining them gives the original bytes.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Document {
29    /// A UTF-8 byte order mark, kept as is.
30    pub bom: String,
31    /// `None` when the file does not open with a frontmatter block.
32    pub front: Option<Frontmatter>,
33    /// The opening fence line, terminator included (`---\r\n`).
34    open: String,
35    /// The closing fence line, terminator included (it may have none at EOF).
36    close: String,
37    /// Everything after the closing fence, untouched.
38    pub body: String,
39    /// `"\r\n"` when the file uses CRLF, else `"\n"`.
40    pub eol: &'static str,
41}
42
43fn line_end(text: &str) -> &'static str {
44    if text.contains("\r\n") {
45        "\r\n"
46    } else {
47        "\n"
48    }
49}
50
51/// The text of `line` without its terminator.
52fn bare(line: &str) -> &str {
53    line.trim_end_matches(['\n', '\r'])
54}
55
56impl Document {
57    /// Splits `text`; never fails (a file without a block has `front: None`).
58    pub fn parse(text: &str) -> Document {
59        let eol = line_end(text);
60        let (bom, rest) = match text.strip_prefix('\u{feff}') {
61            Some(r) => ("\u{feff}".to_string(), r),
62            None => (String::new(), text),
63        };
64        let lines: Vec<&str> = rest.split_inclusive('\n').collect();
65        let plain = |body: &str| Document {
66            bom: bom.clone(),
67            front: None,
68            open: String::new(),
69            close: String::new(),
70            body: body.to_string(),
71            eol,
72        };
73        let Some(first) = lines.first() else {
74            return plain(rest);
75        };
76        if bare(first).trim_end() != "---" {
77            return plain(rest);
78        }
79        let Some(close_at) = lines
80            .iter()
81            .skip(1)
82            .position(|l| matches!(bare(l).trim_end(), "---" | "..."))
83            .map(|p| p + 1)
84        else {
85            return plain(rest);
86        };
87        let block: String = lines[1..close_at].concat();
88        Document {
89            bom,
90            front: Some(Frontmatter::parse(&block)),
91            open: (*first).to_string(),
92            close: lines[close_at].to_string(),
93            body: lines[close_at + 1..].concat(),
94            eol,
95        }
96    }
97
98    /// The file's bytes again.
99    pub fn render(&self) -> String {
100        let mut out = self.bom.clone();
101        if let Some(front) = &self.front {
102            out.push_str(&self.open);
103            out.push_str(&front.render());
104            out.push_str(&self.close);
105        }
106        out.push_str(&self.body);
107        out
108    }
109
110    /// Makes sure there is a block to write into, with the file's line
111    /// ending.
112    pub fn ensure_front(&mut self) -> &mut Frontmatter {
113        if self.front.is_none() {
114            self.front = Some(Frontmatter::default());
115            self.open = format!("---{}", self.eol);
116            self.close = format!("---{}", self.eol);
117        }
118        self.front.as_mut().expect("just set")
119    }
120}
121
122/// Whether `line` starts a new top-level key, and which one.
123fn key_of(line: &str) -> Option<String> {
124    let first = line.chars().next()?;
125    if first.is_whitespace() || matches!(first, '#' | '-' | '[' | '{' | '"' | '\'' | '?') {
126        return None;
127    }
128    let (key, rest) = line.split_once(':')?;
129    // `key:` or `key: value`, never `a:b`.
130    if !(rest.is_empty() || rest.starts_with([' ', '\t'])) {
131        return None;
132    }
133    let key = key.trim_end();
134    (!key.is_empty()).then(|| key.to_string())
135}
136
137impl Frontmatter {
138    fn parse(block: &str) -> Frontmatter {
139        let mut segments: Vec<Segment> = Vec::new();
140        for line in block.split_inclusive('\n') {
141            match key_of(bare(line)) {
142                Some(key) => segments.push(Segment {
143                    key: Some(key),
144                    text: line.to_string(),
145                }),
146                None => match segments.last_mut() {
147                    Some(last) => last.text.push_str(line),
148                    None => segments.push(Segment {
149                        key: None,
150                        text: line.to_string(),
151                    }),
152                },
153            }
154        }
155        Frontmatter { segments }
156    }
157
158    pub fn render(&self) -> String {
159        self.segments.iter().map(|s| s.text.as_str()).collect()
160    }
161
162    /// Top-level keys in file order.
163    pub fn keys(&self) -> impl Iterator<Item = &str> {
164        self.segments.iter().filter_map(|s| s.key.as_deref())
165    }
166
167    fn segment(&self, key: &str) -> Option<&Segment> {
168        self.segments.iter().find(|s| {
169            s.key
170                .as_deref()
171                .is_some_and(|k| k.eq_ignore_ascii_case(key))
172        })
173    }
174
175    /// The raw text after `key:` on its first line, comment removed.
176    fn inline_value(&self, key: &str) -> Option<String> {
177        let seg = self.segment(key)?;
178        let first = bare(seg.text.lines().next().unwrap_or(""));
179        let (_, value) = first.split_once(':')?;
180        Some(strip_comment(value).trim().to_string())
181    }
182
183    /// A scalar value (`status: todo`); `None` when the key is absent or empty.
184    pub fn scalar(&self, key: &str) -> Option<String> {
185        let value = self.inline_value(key)?;
186        if value.is_empty() || value.starts_with('[') {
187            return None;
188        }
189        Some(unquote(&value))
190    }
191
192    /// A list value: flow (`[a, b]`), block (`- a` lines) or a lone scalar.
193    pub fn list(&self, key: &str) -> Vec<String> {
194        let Some(seg) = self.segment(key) else {
195            return Vec::new();
196        };
197        let value = self.inline_value(key).unwrap_or_default();
198        if let Some(inner) = value.strip_prefix('[') {
199            // A flow list may continue on the next lines until `]`.
200            let mut joined = inner.to_string();
201            if !joined.contains(']') {
202                for line in seg.text.lines().skip(1) {
203                    joined.push(' ');
204                    joined.push_str(strip_comment(line).trim());
205                    if joined.contains(']') {
206                        break;
207                    }
208                }
209            }
210            let inner = joined.split(']').next().unwrap_or("");
211            return split_flow(inner);
212        }
213        if !value.is_empty() {
214            return vec![unquote(&value)];
215        }
216        seg.text
217            .lines()
218            .skip(1)
219            .filter_map(|l| {
220                let t = strip_comment(l).trim().to_string();
221                let item = t.strip_prefix('-')?;
222                let item = item.trim();
223                (!item.is_empty()).then(|| unquote(item))
224            })
225            .collect()
226    }
227
228    /// Sets a scalar, keeping the key's place; appends when new. An empty
229    /// `value` writes `key:` (a blank property Obsidian shows as empty).
230    pub fn set_scalar(&mut self, key: &str, value: &str, eol: &str) {
231        let rendered = render_scalar(value);
232        let text = if rendered.is_empty() {
233            format!("{key}:{eol}")
234        } else {
235            format!("{key}: {rendered}{eol}")
236        };
237        self.put(key, text);
238    }
239
240    /// Sets a number (`id: 12`), never quoted.
241    pub fn set_number(&mut self, key: &str, value: u64, eol: &str) {
242        self.put(key, format!("{key}: {value}{eol}"));
243    }
244
245    /// Sets a list, keeping the key's place and, when the old value was a
246    /// block list, its style. Empty list: `key: []`.
247    pub fn set_list(&mut self, key: &str, items: &[String], eol: &str) {
248        let block = self.segment(key).is_some_and(|s| {
249            self.inline_value(key).unwrap_or_default().is_empty()
250                && s.text
251                    .lines()
252                    .skip(1)
253                    .any(|l| l.trim_start().starts_with('-'))
254        });
255        let text = if items.is_empty() {
256            format!("{key}: []{eol}")
257        } else if block {
258            let mut t = format!("{key}:{eol}");
259            for item in items {
260                t.push_str(&format!("  - {}{eol}", render_scalar(item)));
261            }
262            t
263        } else {
264            let list: Vec<String> = items.iter().map(|i| render_flow_item(i)).collect();
265            format!("{key}: [{}]{eol}", list.join(", "))
266        };
267        self.put(key, text);
268    }
269
270    fn put(&mut self, key: &str, text: String) {
271        match self.segments.iter_mut().find(|s| {
272            s.key
273                .as_deref()
274                .is_some_and(|k| k.eq_ignore_ascii_case(key))
275        }) {
276            Some(seg) => seg.text = text,
277            None => {
278                if let Some(last) = self.segments.last_mut() {
279                    if !last.text.ends_with('\n') {
280                        last.text.push('\n');
281                    }
282                }
283                self.segments.push(Segment {
284                    key: Some(key.to_string()),
285                    text,
286                });
287            }
288        }
289    }
290}
291
292/// `value` without a trailing ` # comment` (outside quotes).
293fn strip_comment(value: &str) -> String {
294    let mut quote: Option<char> = None;
295    let mut prev = ' ';
296    for (i, c) in value.char_indices() {
297        match quote {
298            Some(q) if c == q => quote = None,
299            Some(_) => {}
300            None if c == '"' || c == '\'' => quote = Some(c),
301            None if c == '#' && prev.is_whitespace() => return value[..i].to_string(),
302            None => {}
303        }
304        prev = c;
305    }
306    value.to_string()
307}
308
309fn unquote(value: &str) -> String {
310    let v = value.trim();
311    if let Some(inner) = v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
312        let mut out = String::new();
313        let mut chars = inner.chars();
314        while let Some(c) = chars.next() {
315            if c == '\\' {
316                match chars.next() {
317                    Some('n') => out.push('\n'),
318                    Some('t') => out.push('\t'),
319                    Some(other) => out.push(other),
320                    None => out.push('\\'),
321                }
322            } else {
323                out.push(c);
324            }
325        }
326        return out;
327    }
328    if let Some(inner) = v.strip_prefix('\'').and_then(|r| r.strip_suffix('\'')) {
329        return inner.replace("''", "'");
330    }
331    v.to_string()
332}
333
334/// Splits the inside of `[a, "b, c", d]` on top-level commas.
335fn split_flow(inner: &str) -> Vec<String> {
336    let mut items = Vec::new();
337    let mut cur = String::new();
338    let mut quote: Option<char> = None;
339    for c in inner.chars() {
340        match quote {
341            Some(q) => {
342                cur.push(c);
343                if c == q {
344                    quote = None;
345                }
346            }
347            None if c == '"' || c == '\'' => {
348                quote = Some(c);
349                cur.push(c);
350            }
351            None if c == ',' => {
352                items.push(std::mem::take(&mut cur));
353            }
354            None => cur.push(c),
355        }
356    }
357    items.push(cur);
358    items
359        .into_iter()
360        .map(|i| unquote(i.trim()))
361        .filter(|i| !i.is_empty())
362        .collect()
363}
364
365/// A scalar as YAML text: plain when safe, double-quoted otherwise.
366pub fn render_scalar(value: &str) -> String {
367    let v = value.replace(['\r', '\n'], " ");
368    let v = v.trim_end();
369    if v.is_empty() {
370        return String::new();
371    }
372    if needs_quotes(v, false) {
373        quoted(v)
374    } else {
375        v.to_string()
376    }
377}
378
379fn render_flow_item(value: &str) -> String {
380    if needs_quotes(value, true) {
381        quoted(value)
382    } else {
383        value.to_string()
384    }
385}
386
387fn quoted(v: &str) -> String {
388    format!("\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\""))
389}
390
391fn needs_quotes(v: &str, flow: bool) -> bool {
392    let first = v.chars().next().unwrap_or(' ');
393    let lower = v.to_ascii_lowercase();
394    v != v.trim()
395        || v.contains(": ")
396        || v.ends_with(':')
397        || v.contains(" #")
398        || (flow && v.contains([',', '[', ']', '{', '}']))
399        || matches!(
400            first,
401            '[' | '{' | '&' | '*' | '!' | '|' | '>' | '\'' | '"' | '%' | '@' | '`' | '#' | ','
402        )
403        || ((first == '-' || first == '?') && (v.len() == 1 || v[1..].starts_with(' ')))
404        || matches!(
405            lower.as_str(),
406            "true" | "false" | "yes" | "no" | "on" | "off" | "null" | "~"
407        )
408        || v.parse::<f64>().is_ok()
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    const NOTE: &str = "---\nid: 12\ntitle: Crash on empty name\nstatus: todo   # free text\nassignees: [kai, \"a b\"]\nlabels:\n  - bug\n  - ui\nmilestone: v0.1\n# my own comment\ncssclasses: wide\ncreated: 2026-10-14\n---\nBody line 1\n\nBody 2\n";
416
417    #[test]
418    fn a_note_round_trips_byte_for_byte() {
419        let doc = Document::parse(NOTE);
420        assert_eq!(doc.render(), NOTE);
421        let crlf = NOTE.replace('\n', "\r\n");
422        let doc = Document::parse(&crlf);
423        assert_eq!(doc.eol, "\r\n");
424        assert_eq!(doc.render(), crlf);
425    }
426
427    #[test]
428    fn values_are_read_leniently() {
429        let doc = Document::parse(NOTE);
430        let f = doc.front.as_ref().unwrap();
431        assert_eq!(f.scalar("id").as_deref(), Some("12"));
432        assert_eq!(f.scalar("status").as_deref(), Some("todo"));
433        assert_eq!(f.scalar("title").as_deref(), Some("Crash on empty name"));
434        assert_eq!(f.list("assignees"), ["kai", "a b"]);
435        assert_eq!(f.list("labels"), ["bug", "ui"]);
436        assert_eq!(f.list("missing"), Vec::<String>::new());
437        assert_eq!(f.scalar("MILESTONE").as_deref(), Some("v0.1"));
438        let single = Document::parse("---\nlabels: bug\n---\n");
439        assert_eq!(single.front.unwrap().list("labels"), ["bug"]);
440    }
441
442    #[test]
443    fn setting_a_key_touches_only_that_key() {
444        let mut doc = Document::parse(NOTE);
445        let eol = doc.eol;
446        let f = doc.front.as_mut().unwrap();
447        f.set_scalar("status", "doing", eol);
448        f.set_list("labels", &["bug".into(), "a: b".into()], eol);
449        f.set_list("assignees", &[], eol);
450        assert_eq!(
451            doc.render(),
452            "---\nid: 12\ntitle: Crash on empty name\nstatus: doing\nassignees: []\nlabels:\n  - bug\n  - \"a: b\"\nmilestone: v0.1\n# my own comment\ncssclasses: wide\ncreated: 2026-10-14\n---\nBody line 1\n\nBody 2\n"
453        );
454    }
455
456    #[test]
457    fn a_new_key_is_appended_and_crlf_is_kept() {
458        let crlf = NOTE.replace('\n', "\r\n");
459        let mut doc = Document::parse(&crlf);
460        let eol = doc.eol;
461        doc.front
462            .as_mut()
463            .unwrap()
464            .set_scalar("updated", "2026-10-15", eol);
465        let out = doc.render();
466        assert!(out.contains("created: 2026-10-14\r\nupdated: 2026-10-15\r\n---\r\n"));
467        assert!(!out.replace("\r\n", "").contains('\n'), "no bare LF added");
468    }
469
470    #[test]
471    fn a_note_without_a_block_gets_one_on_demand() {
472        let mut doc = Document::parse("# Title\n\ntext\n");
473        assert!(doc.front.is_none());
474        assert_eq!(doc.render(), "# Title\n\ntext\n");
475        let eol = doc.eol;
476        doc.ensure_front().set_number("id", 3, eol);
477        assert_eq!(doc.render(), "---\nid: 3\n---\n# Title\n\ntext\n");
478    }
479
480    #[test]
481    fn an_unclosed_block_is_just_a_body() {
482        let doc = Document::parse("---\nid: 1\nno close\n");
483        assert!(doc.front.is_none());
484        assert_eq!(doc.render(), "---\nid: 1\nno close\n");
485    }
486
487    #[test]
488    fn bom_and_odd_scalars_survive() {
489        let text = "\u{feff}---\nid: 1\ntitle: \"Say \\\"hi\\\": now\"\n---\n";
490        let doc = Document::parse(text);
491        assert_eq!(doc.render(), text);
492        assert_eq!(
493            doc.front.unwrap().scalar("title").as_deref(),
494            Some("Say \"hi\": now")
495        );
496        assert_eq!(render_scalar("plain"), "plain");
497        assert_eq!(render_scalar("a: b"), "\"a: b\"");
498        assert_eq!(render_scalar("123"), "\"123\"");
499        assert_eq!(render_scalar("true"), "\"true\"");
500        assert_eq!(render_scalar("- x"), "\"- x\"");
501        assert_eq!(render_scalar("two\nlines"), "two lines");
502    }
503
504    #[test]
505    fn a_colon_inside_a_value_is_not_a_key() {
506        let doc = Document::parse("---\nurl: http://x/y\nnote: a:b\n---\n");
507        let f = doc.front.unwrap();
508        assert_eq!(f.keys().collect::<Vec<_>>(), ["url", "note"]);
509        assert_eq!(f.scalar("url").as_deref(), Some("http://x/y"));
510    }
511}