use serde_yaml::Result;
pub type Frontmatter = serde_yaml::Mapping;
#[allow(clippy::module_name_repetitions)]
pub fn frontmatter_from_str(mut s: &str) -> Result<Frontmatter> {
if s.is_empty() {
s = "{}";
}
let frontmatter: Frontmatter = serde_yaml::from_str(s)?;
Ok(frontmatter)
}
#[allow(clippy::module_name_repetitions)]
pub fn frontmatter_to_str(frontmatter: &Frontmatter) -> Result<String> {
if frontmatter.is_empty() {
return Ok("---\n---\n".to_owned());
}
let mut buffer = String::new();
buffer.push_str("---\n");
buffer.push_str(&serde_yaml::to_string(&frontmatter)?);
buffer.push_str("---\n");
Ok(buffer)
}
#[derive(Debug, Clone, Copy)]
#[allow(clippy::module_name_repetitions)]
#[non_exhaustive]
pub enum FrontmatterStrategy {
Auto,
Always,
Never,
}
#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;
use serde_yaml::Value;
use super::*;
#[test]
fn empty_string_should_yield_empty_frontmatter() {
assert_eq!(frontmatter_from_str("").unwrap(), Frontmatter::new());
}
#[test]
fn empty_frontmatter_to_str() {
let frontmatter = Frontmatter::new();
assert_eq!(
frontmatter_to_str(&frontmatter).unwrap(),
format!("---\n---\n")
);
}
#[test]
fn nonempty_frontmatter_to_str() {
let mut frontmatter = Frontmatter::new();
frontmatter.insert(Value::String("foo".into()), Value::String("bar".into()));
assert_eq!(
frontmatter_to_str(&frontmatter).unwrap(),
format!("---\nfoo: bar\n---\n")
);
}
}