Skip to main content

agent_first_data/document/format/
frontmatter.rs

1//! Frontmatter mode: address the leading TOML (`+++`) or YAML (`---`) metadata
2//! block of a Markdown-ish file as a config document, leaving the body bytes
3//! untouched.
4//!
5//! This backend does not parse Markdown. It splits the source into three
6//! byte-exact spans — the opening delimiter line, the frontmatter block, and
7//! the closing delimiter line plus everything after it (the body) — and hands
8//! only the middle span to the inner TOML/YAML backend. Every edit re-splices
9//! `pre + edited_frontmatter + post`, so the body survives verbatim; the frozen
10//! body is exactly why frontmatter mode is source-preserving-only (there is no
11//! whole-document re-render — the body is not part of the parsed value).
12//!
13//! Detection is never automatic: the caller selects the delimiter explicitly
14//! (`--input-format toml-frontmatter|yaml-frontmatter`). A file that does not
15//! open with the requested delimiter, or whose block is never closed, is a hard
16//! error — sniffing a fence is exactly the shape-guessing AFDATA avoids.
17
18use crate::document::{DocumentError, DocumentResult};
19
20/// The fence delimiter that brackets a frontmatter block.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Delimiter {
23    /// `+++` — Zola's TOML frontmatter.
24    Plus,
25    /// `---` — Jekyll/Hugo/Obsidian YAML frontmatter.
26    Dash,
27}
28
29impl Delimiter {
30    /// The literal fence line for this delimiter.
31    fn marker(self) -> &'static str {
32        match self {
33            Delimiter::Plus => "+++",
34            Delimiter::Dash => "---",
35        }
36    }
37
38    /// Human-readable format label used in error envelopes.
39    fn label(self) -> &'static str {
40        match self {
41            Delimiter::Plus => "TOML frontmatter",
42            Delimiter::Dash => "YAML frontmatter",
43        }
44    }
45}
46
47/// Three byte-exact spans of a frontmatter document: the opening delimiter line
48/// (`pre`), the frontmatter block handed to the inner backend (`frontmatter`),
49/// and the closing delimiter line plus the body (`post`). Concatenating `pre`,
50/// `frontmatter`, and `post` reproduces the original source byte for byte.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Parts<'a> {
53    pub pre: &'a str,
54    pub frontmatter: &'a str,
55    pub post: &'a str,
56}
57
58/// Split `source` into its frontmatter spans for the given delimiter.
59///
60/// The opening delimiter must be the file's very first line (no leading blank
61/// lines, no BOM). The closing delimiter is the next line equal to the marker
62/// at column zero. A missing opening or closing fence is a [`DocumentError`],
63/// never a silent "there is no frontmatter, treat the whole file as body".
64pub fn split(source: &str, delim: Delimiter) -> DocumentResult<Parts<'_>> {
65    let marker = delim.marker();
66
67    let first_line_end = source.find('\n');
68    let first_line = match first_line_end {
69        Some(nl) => &source[..nl],
70        None => source,
71    };
72    if first_line.trim_end() != marker {
73        return Err(DocumentError::ParseError {
74            format: delim.label().to_string(),
75            detail: format!("file does not begin with a `{marker}` frontmatter delimiter line"),
76        });
77    }
78    let Some(nl) = first_line_end else {
79        // A bare `+++`/`---` with no trailing newline: opened, never closed.
80        return Err(unterminated(delim));
81    };
82    split_at_closing_line(source, nl + 1, marker).ok_or_else(|| unterminated(delim))
83}
84
85/// Find leading frontmatter without allocating an error for ordinary Markdown.
86#[cfg(feature = "markdown")]
87pub(super) fn leading(source: &str) -> Option<(Delimiter, Parts<'_>)> {
88    let nl = source.find('\n')?;
89    let delimiter = match source[..nl].trim_end() {
90        "+++" => Delimiter::Plus,
91        "---" => Delimiter::Dash,
92        _ => return None,
93    };
94    let parts = split_at_closing_line(source, nl + 1, delimiter.marker())?;
95    Some((delimiter, parts))
96}
97
98fn split_at_closing_line<'a>(
99    source: &'a str,
100    block_start: usize,
101    marker: &str,
102) -> Option<Parts<'a>> {
103    // The closing delimiter is the next line whose trimmed content is the
104    // marker. Leading whitespace disqualifies it (an indented `+++` is content,
105    // not a fence); trailing whitespace/CR is tolerated.
106    let mut idx = block_start;
107    loop {
108        let line_end = source[idx..]
109            .find('\n')
110            .map(|offset| idx + offset)
111            .unwrap_or(source.len());
112        let line = &source[idx..line_end];
113        if line.trim_end() == marker {
114            return Some(Parts {
115                pre: &source[..block_start],
116                frontmatter: &source[block_start..idx],
117                post: &source[idx..],
118            });
119        }
120        if line_end == source.len() {
121            return None;
122        }
123        idx = line_end + 1;
124    }
125}
126
127fn unterminated(delim: Delimiter) -> DocumentError {
128    DocumentError::ParseError {
129        format: delim.label().to_string(),
130        detail: format!(
131            "unterminated frontmatter: no closing `{}` delimiter",
132            delim.marker()
133        ),
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
140    use super::*;
141
142    fn assert_roundtrip(source: &str, parts: &Parts<'_>) {
143        assert_eq!(
144            format!("{}{}{}", parts.pre, parts.frontmatter, parts.post),
145            source,
146            "spans must concatenate back to the source byte for byte"
147        );
148    }
149
150    #[test]
151    fn splits_toml_frontmatter_and_freezes_body() {
152        let source = "+++\ntitle = \"x\"\n+++\n# Body\n\nprose\n";
153        let parts = split(source, Delimiter::Plus).unwrap();
154        assert_eq!(parts.pre, "+++\n");
155        assert_eq!(parts.frontmatter, "title = \"x\"\n");
156        assert_eq!(parts.post, "+++\n# Body\n\nprose\n");
157        assert_roundtrip(source, &parts);
158    }
159
160    #[test]
161    fn splits_yaml_frontmatter() {
162        let source = "---\ntitle: x\n---\nbody\n";
163        let parts = split(source, Delimiter::Dash).unwrap();
164        assert_eq!(parts.pre, "---\n");
165        assert_eq!(parts.frontmatter, "title: x\n");
166        assert_eq!(parts.post, "---\nbody\n");
167        assert_roundtrip(source, &parts);
168    }
169
170    #[test]
171    fn empty_block_is_valid() {
172        let source = "+++\n+++\nbody\n";
173        let parts = split(source, Delimiter::Plus).unwrap();
174        assert_eq!(parts.frontmatter, "");
175        assert_eq!(parts.post, "+++\nbody\n");
176        assert_roundtrip(source, &parts);
177    }
178
179    #[test]
180    fn frontmatter_only_no_body() {
181        let source = "+++\ntitle = \"x\"\n+++\n";
182        let parts = split(source, Delimiter::Plus).unwrap();
183        assert_eq!(parts.frontmatter, "title = \"x\"\n");
184        assert_eq!(parts.post, "+++\n");
185        assert_roundtrip(source, &parts);
186    }
187
188    #[test]
189    fn preserves_crlf_line_endings() {
190        let source = "+++\r\ntitle = \"x\"\r\n+++\r\nbody\r\n";
191        let parts = split(source, Delimiter::Plus).unwrap();
192        assert_eq!(parts.pre, "+++\r\n");
193        assert_eq!(parts.frontmatter, "title = \"x\"\r\n");
194        assert_eq!(parts.post, "+++\r\nbody\r\n");
195        assert_roundtrip(source, &parts);
196    }
197
198    #[test]
199    fn missing_opening_delimiter_errors() {
200        let err = split("# Just a markdown heading\n", Delimiter::Plus).unwrap_err();
201        assert!(matches!(err, DocumentError::ParseError { .. }));
202    }
203
204    #[test]
205    fn wrong_delimiter_errors() {
206        // A `+++` file addressed as YAML frontmatter must not silently succeed.
207        let err = split("+++\ntitle = \"x\"\n+++\n", Delimiter::Dash).unwrap_err();
208        assert!(matches!(err, DocumentError::ParseError { .. }));
209    }
210
211    #[test]
212    fn unterminated_block_errors() {
213        let err = split("+++\ntitle = \"x\"\nno closing fence\n", Delimiter::Plus).unwrap_err();
214        assert!(matches!(err, DocumentError::ParseError { .. }));
215    }
216
217    #[test]
218    fn indented_fence_is_not_a_close() {
219        // A `+++` that is not at column zero is body content, so the block is
220        // unterminated rather than closed there.
221        let err = split("+++\ntitle = \"x\"\n  +++\n", Delimiter::Plus).unwrap_err();
222        assert!(matches!(err, DocumentError::ParseError { .. }));
223    }
224}