From 8b7620b0bdb32a9e2b37580b0757c24a1ed61e5e Mon Sep 17 00:00:00 2001 From: zyl Date: Fri, 8 Nov 2024 11:07:31 -0800 Subject: [PATCH] add ability for the built-in frontmatter parser to also output --- src/frontmatter.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/frontmatter.rs b/src/frontmatter.rs index 054fc1a..5cf7a44 100644 --- a/src/frontmatter.rs +++ b/src/frontmatter.rs @@ -1,4 +1,4 @@ -use serde::de::DeserializeOwned; +use serde::{de::DeserializeOwned, Serialize}; /// Very basic YAML front matter parser. #[derive(Debug)] @@ -30,3 +30,27 @@ where }) } } + +impl FrontMatter +where + T: Serialize, +{ + /// Formats the front matter and content to a string ready for saving. + pub fn format(&self) -> eyre::Result { + let mut output = String::new(); + + if let Some(data) = &self.data { + output.push_str("---\n"); + output.push_str(&serde_yml::to_string(data)?); + output.push_str("---\n\n"); + } + + output.push_str(&self.content); + + if !output.ends_with('\n') { + output.push('\n'); + } + + Ok(output) + } +}