use fabryk_core::{Error, Result};
use serde::de::DeserializeOwned;
use yaml_serde::Value;
#[derive(Debug, Clone)]
pub struct FrontmatterResult<'a> {
value: Option<Value>,
body: &'a str,
had_delimiters: bool,
}
impl<'a> FrontmatterResult<'a> {
fn with_frontmatter(value: Value, body: &'a str) -> Self {
Self {
value: Some(value),
body,
had_delimiters: true,
}
}
fn without_frontmatter(body: &'a str) -> Self {
Self {
value: None,
body,
had_delimiters: false,
}
}
fn with_invalid_frontmatter(body: &'a str) -> Self {
Self {
value: None,
body,
had_delimiters: true,
}
}
pub fn has_frontmatter(&self) -> bool {
self.value.is_some()
}
pub fn had_delimiters(&self) -> bool {
self.had_delimiters
}
pub fn value(&self) -> Option<&Value> {
self.value.as_ref()
}
pub fn into_value(self) -> Option<Value> {
self.value
}
pub fn body(&self) -> &'a str {
self.body
}
pub fn deserialize<T: DeserializeOwned>(&self) -> Result<Option<T>> {
match &self.value {
Some(value) => {
let parsed: T = yaml_serde::from_value(value.clone())
.map_err(|e| Error::parse(format!("Failed to deserialize frontmatter: {e}")))?;
Ok(Some(parsed))
}
None => Ok(None),
}
}
pub fn get_str(&self, key: &str) -> Option<&str> {
self.value.as_ref()?.get(key)?.as_str()
}
pub fn get_string_list(&self, key: &str) -> Vec<String> {
self.value
.as_ref()
.and_then(|v| v.get(key))
.and_then(|v| v.as_sequence())
.map(|seq| {
seq.iter()
.filter_map(|item| item.as_str().map(String::from))
.collect()
})
.unwrap_or_default()
}
}
pub fn extract_frontmatter(content: &str) -> Result<FrontmatterResult<'_>> {
if !content.starts_with("---") {
return Ok(FrontmatterResult::without_frontmatter(content));
}
let after_first_delimiter = match content[3..].find('\n') {
Some(pos) => &content[3 + pos + 1..],
None => return Ok(FrontmatterResult::without_frontmatter(content)),
};
let (yaml_content, body_after_closing) =
if let Some(rest) = after_first_delimiter.strip_prefix("---") {
("", rest)
} else if let Some(closing_pos) = after_first_delimiter.find("\n---") {
(
&after_first_delimiter[..closing_pos],
&after_first_delimiter[closing_pos + 4..],
)
} else {
log::warn!("Frontmatter opening delimiter found but no closing delimiter");
return Ok(FrontmatterResult::without_frontmatter(content));
};
let body = body_after_closing
.strip_prefix('\n')
.unwrap_or(body_after_closing);
match yaml_serde::from_str::<Value>(yaml_content) {
Ok(value) => Ok(FrontmatterResult::with_frontmatter(value, body)),
Err(e) => {
log::warn!("Failed to parse frontmatter YAML: {e}");
Ok(FrontmatterResult::with_invalid_frontmatter(body))
}
}
}
pub fn strip_frontmatter(content: &str) -> &str {
extract_frontmatter(content)
.map(|r| r.body())
.unwrap_or(content)
}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[test]
fn test_extract_valid_frontmatter() {
let content = "---\ntitle: Test Document\nauthor: Claude\n---\n\n# Content";
let result = extract_frontmatter(content).unwrap();
assert!(result.has_frontmatter());
assert!(result.had_delimiters());
assert_eq!(result.get_str("title"), Some("Test Document"));
assert_eq!(result.get_str("author"), Some("Claude"));
assert_eq!(result.body().trim(), "# Content");
}
#[test]
fn test_extract_no_frontmatter() {
let content = "# Just Markdown\n\nNo frontmatter here.";
let result = extract_frontmatter(content).unwrap();
assert!(!result.has_frontmatter());
assert!(!result.had_delimiters());
assert_eq!(result.body(), content);
}
#[test]
fn test_extract_empty_frontmatter() {
let content = "---\n---\n\nBody content";
let result = extract_frontmatter(content).unwrap();
assert!(result.had_delimiters());
assert_eq!(result.body().trim(), "Body content");
}
#[test]
fn test_extract_frontmatter_no_closing() {
let content = "---\ntitle: Incomplete\n\nNo closing delimiter";
let result = extract_frontmatter(content).unwrap();
assert!(!result.has_frontmatter());
assert!(!result.had_delimiters()); assert_eq!(result.body(), content);
}
#[test]
fn test_extract_frontmatter_invalid_yaml() {
let content = "---\n{{invalid: yaml: here}}\n---\n\nBody";
let result = extract_frontmatter(content).unwrap();
assert!(!result.has_frontmatter());
assert!(result.had_delimiters());
assert_eq!(result.body().trim(), "Body");
}
#[test]
fn test_extract_frontmatter_with_lists() {
let content = "---\ntitle: Test\ntags:\n - rust\n - markdown\n---\n\nBody";
let result = extract_frontmatter(content).unwrap();
assert!(result.has_frontmatter());
let tags = result.get_string_list("tags");
assert_eq!(tags, vec!["rust", "markdown"]);
}
#[test]
fn test_extract_frontmatter_with_nested() {
let content = "---\nmeta:\n author: Claude\n version: 1.0\n---\n\nBody";
let result = extract_frontmatter(content).unwrap();
assert!(result.has_frontmatter());
let value = result.value().unwrap();
let author = value
.get("meta")
.and_then(|m| m.get("author"))
.and_then(|a| a.as_str());
assert_eq!(author, Some("Claude"));
}
#[derive(Debug, Deserialize, PartialEq)]
struct TestFrontmatter {
title: String,
#[serde(default)]
tags: Vec<String>,
category: Option<String>,
}
#[test]
fn test_deserialize_frontmatter() {
let content = "---\ntitle: My Doc\ntags:\n - a\n - b\ncategory: test\n---\n\nBody";
let result = extract_frontmatter(content).unwrap();
let fm: Option<TestFrontmatter> = result.deserialize().unwrap();
let fm = fm.unwrap();
assert_eq!(fm.title, "My Doc");
assert_eq!(fm.tags, vec!["a", "b"]);
assert_eq!(fm.category, Some("test".to_string()));
}
#[test]
fn test_deserialize_no_frontmatter() {
let content = "# No frontmatter";
let result = extract_frontmatter(content).unwrap();
let fm: Option<TestFrontmatter> = result.deserialize().unwrap();
assert!(fm.is_none());
}
#[test]
fn test_deserialize_partial_frontmatter() {
let content = "---\ntitle: Only Title\n---\n\nBody";
let result = extract_frontmatter(content).unwrap();
let fm: Option<TestFrontmatter> = result.deserialize().unwrap();
let fm = fm.unwrap();
assert_eq!(fm.title, "Only Title");
assert!(fm.tags.is_empty());
assert!(fm.category.is_none());
}
#[test]
fn test_strip_frontmatter() {
let content = "---\ntitle: Test\n---\n\n# Heading\n\nParagraph";
let body = strip_frontmatter(content);
assert_eq!(body.trim(), "# Heading\n\nParagraph");
}
#[test]
fn test_strip_no_frontmatter() {
let content = "# Just content";
let body = strip_frontmatter(content);
assert_eq!(body, content);
}
#[test]
fn test_frontmatter_with_dashes_in_content() {
let content = "---\ntitle: Test\n---\n\nContent with --- dashes in it";
let result = extract_frontmatter(content).unwrap();
assert!(result.has_frontmatter());
assert!(result.body().contains("--- dashes"));
}
#[test]
fn test_frontmatter_unicode() {
let content = "---\ntitle: 音楽理論\nauthor: クロード\n---\n\n本文";
let result = extract_frontmatter(content).unwrap();
assert!(result.has_frontmatter());
assert_eq!(result.get_str("title"), Some("音楽理論"));
assert_eq!(result.get_str("author"), Some("クロード"));
assert_eq!(result.body().trim(), "本文");
}
#[test]
fn test_empty_content() {
let content = "";
let result = extract_frontmatter(content).unwrap();
assert!(!result.has_frontmatter());
assert_eq!(result.body(), "");
}
#[test]
fn test_only_opening_delimiter() {
let content = "---";
let result = extract_frontmatter(content).unwrap();
assert!(!result.has_frontmatter());
assert_eq!(result.body(), "---");
}
}