Skip to main content

systemprompt_models/services/
frontmatter.rs

1//! Line-anchored YAML frontmatter splitting.
2//!
3//! The canonical frontmatter parser for every consumer in the workspace
4//! (skills, content ingestion, sync diffing, static generation). A
5//! frontmatter block opens with a `---` line at the very start of the
6//! document (after an optional UTF-8 BOM) and closes at the next line that
7//! is exactly `---`. A `---` anywhere else — mid-line, in a markdown table
8//! separator row, or as a horizontal rule — is body text, never a delimiter.
9
10#[derive(Debug, Clone, Copy)]
11pub struct Frontmatter<'a> {
12    pub yaml: &'a str,
13    pub body: &'a str,
14}
15
16pub fn split_frontmatter(content: &str) -> Option<Frontmatter<'_>> {
17    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
18    let mut lines = content.split_inclusive('\n');
19
20    let opening = lines.next()?;
21    if opening.trim_end() != "---" {
22        return None;
23    }
24
25    let yaml_start = opening.len();
26    let mut offset = yaml_start;
27    for line in lines {
28        if line.trim_end() == "---" {
29            return Some(Frontmatter {
30                yaml: &content[yaml_start..offset],
31                body: &content[offset + line.len()..],
32            });
33        }
34        offset += line.len();
35    }
36    None
37}
38
39pub fn strip_frontmatter(content: &str) -> String {
40    split_frontmatter(content).map_or_else(|| content.to_owned(), |f| f.body.trim().to_owned())
41}