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//! Copyright (c) systemprompt.io — Business Source License 1.1.
11//! See <https://systemprompt.io> for licensing details.
12
13#[derive(Debug, Clone, Copy)]
14pub struct Frontmatter<'a> {
15    pub yaml: &'a str,
16    pub body: &'a str,
17}
18
19pub fn split_frontmatter(content: &str) -> Option<Frontmatter<'_>> {
20    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
21    let mut lines = content.split_inclusive('\n');
22
23    let opening = lines.next()?;
24    if opening.trim_end() != "---" {
25        return None;
26    }
27
28    let yaml_start = opening.len();
29    let mut offset = yaml_start;
30    for line in lines {
31        if line.trim_end() == "---" {
32            return Some(Frontmatter {
33                yaml: &content[yaml_start..offset],
34                body: &content[offset + line.len()..],
35            });
36        }
37        offset += line.len();
38    }
39    None
40}
41
42pub fn strip_frontmatter(content: &str) -> String {
43    split_frontmatter(content).map_or_else(|| content.to_owned(), |f| f.body.trim().to_owned())
44}