frontmatter: Fix extraction algorithm

This commit is contained in:
adnano 2021-04-24 13:24:31 -04:00
parent 2d543b9c1e
commit 81aac7692d
2 changed files with 11 additions and 5 deletions

View file

@ -11,13 +11,14 @@ func extractFrontmatter(b []byte) (frontmatter, content []byte) {
if !bytes.HasPrefix(b, frontmatterOpen) { if !bytes.HasPrefix(b, frontmatterOpen) {
return nil, b return nil, b
} }
fm := b[len(frontmatterOpen):] if len(b) > len(frontmatterOpen) && b[len(frontmatterOpen)] != '\n' {
if len(fm) != 0 && fm[0] != '\n' {
return nil, b return nil, b
} }
i := bytes.Index(fm, frontmatterClose) b = b[len(frontmatterOpen):]
i := bytes.Index(b, frontmatterClose)
if i == -1 { if i == -1 {
i = len(fm) return b, nil
} }
return fm[:i], b[len(frontmatterOpen)+len(fm):] return b[:i], b[i+len(frontmatterClose):]
} }

View file

@ -20,6 +20,11 @@ func TestExtractFrontmatter(t *testing.T) {
Frontmatter: "\na: b\nc: d", Frontmatter: "\na: b\nc: d",
Content: "", Content: "",
}, },
{
Raw: "---\na: b\nc: d\n---\nHello, world!",
Frontmatter: "\na: b\nc: d",
Content: "\nHello, world!",
},
{ {
Raw: "# Hello, world!", Raw: "# Hello, world!",
Frontmatter: "", Frontmatter: "",