frontmatter: Allow CRLF line endings

This commit is contained in:
adnano 2022-06-14 17:42:23 -04:00
parent 9f415ca3a6
commit 7fb173213e
2 changed files with 7 additions and 5 deletions

View file

@ -5,17 +5,19 @@ import "bytes"
var (
frontmatterOpen = []byte("---")
frontmatterClose = []byte("\n---")
lf = []byte("\n")
crlf = []byte("\r\n")
)
func extractFrontmatter(b []byte) (frontmatter, content []byte) {
if !bytes.HasPrefix(b, frontmatterOpen) {
return nil, b
}
if len(b) > len(frontmatterOpen) && b[len(frontmatterOpen)] != '\n' {
next := b[len(frontmatterOpen):]
if len(next) > 0 && !bytes.HasPrefix(next, lf) && !bytes.HasPrefix(next, crlf) {
return nil, b
}
b = b[len(frontmatterOpen):]
b = next
i := bytes.Index(b, frontmatterClose)
if i == -1 {
return b, nil

View file

@ -65,10 +65,10 @@ func TestExtractFrontmatter(t *testing.T) {
for _, test := range tests {
frontmatter, content := extractFrontmatter([]byte(test.Raw))
if string(frontmatter) != test.Frontmatter {
t.Fatalf("expected frontmatter %q, got %q", test.Frontmatter, string(frontmatter))
t.Fatalf("expected frontmatter %q, got %q, raw %q", test.Frontmatter, string(frontmatter), test.Raw)
}
if string(content) != test.Content {
t.Fatalf("expected content %q, got %q", test.Content, string(content))
t.Fatalf("expected content %q, got %q, raw %q", test.Content, string(content), test.Raw)
}
}
}