From 5b005b48aa39a80670df13db05d20edef3a80a26 Mon Sep 17 00:00:00 2001 From: Bert JW Regeer Date: Mon, 15 Mar 2021 00:52:10 -0700 Subject: [PATCH] Allow frontmatter to have optional newline if no content (#1408) Without content it should be possible to create a file that contains no newlines after the frontmatter at all, rather than forcing a newline after the frontmatter. --- components/front_matter/src/lib.rs | 32 +++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/components/front_matter/src/lib.rs b/components/front_matter/src/lib.rs index 9397af89..bc7a7cf1 100644 --- a/components/front_matter/src/lib.rs +++ b/components/front_matter/src/lib.rs @@ -15,9 +15,10 @@ pub use section::SectionFrontMatter; lazy_static! { static ref TOML_RE: Regex = - Regex::new(r"^[[:space:]]*\+\+\+(\r?\n(?s).*?(?-s))\+\+\+\r?\n((?s).*(?-s))$").unwrap(); + Regex::new(r"^[[:space:]]*\+\+\+(\r?\n(?s).*?(?-s))\+\+\+(?:$|(?:\r?\n((?s).*(?-s))$))") + .unwrap(); static ref YAML_RE: Regex = - Regex::new(r"^[[:space:]]*---(\r?\n(?s).*?(?-s))---\r?\n((?s).*(?-s))$").unwrap(); + Regex::new(r"^[[:space:]]*---(\r?\n(?s).*?(?-s))---(?:$|(?:\r?\n((?s).*(?-s))$))").unwrap(); } pub enum RawFrontMatter<'a> { @@ -82,7 +83,8 @@ fn split_content<'c>(file_path: &Path, content: &'c str) -> Result<(RawFrontMatt // caps[1] => front matter // caps[2] => content let front_matter = caps.get(1).unwrap().as_str(); - let content = caps.get(2).unwrap().as_str(); + let content = caps.get(2).map_or("", |m| m.as_str()); + if is_toml { Ok((RawFrontMatter::Toml(front_matter), content)) } else { @@ -183,6 +185,18 @@ description: hey there date: 2002-10-12 --- "#; "yaml")] + #[test_case(r#" ++++ +title = "Title" +description = "hey there" +date = 2002-10-12 ++++"#; "toml no newline")] + #[test_case(r#" +--- +title: Title +description: hey there +date: 2002-10-12 +---"#; "yaml no newline")] fn can_split_content_with_only_frontmatter_valid(content: &str) { let (front_matter, content) = split_page_content(Path::new(""), content).unwrap(); assert_eq!(content, ""); @@ -235,6 +249,12 @@ description = "hey there" date = 2002-10-12 ---"#; "toml unmatched")] #[test_case(r#" ++++ +title = "Title" +description = "hey there" +date = 2002-10-12 +++++"#; "toml too many pluses")] + #[test_case(r#" --- title: Title description: hey there @@ -245,6 +265,12 @@ title: Title description: hey there date: 2002-10-12 +++"#; "yaml unmatched")] + #[test_case(r#" +--- +title: Title +description: hey there +date: 2002-10-12 +----"#; "yaml too many dashes")] fn errors_if_cannot_locate_frontmatter(content: &str) { let res = split_page_content(Path::new(""), content); assert!(res.is_err());