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.
This commit is contained in:
Bert JW Regeer 2021-03-15 00:52:10 -07:00 committed by GitHub
parent 534174ae78
commit 5b005b48aa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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());