1
0
Fork 0
mirror of https://git.sr.ht/~adnano/kiln synced 2024-05-07 13:56:08 +02:00

Add frontmatter extractor

This commit is contained in:
Adnan Maolood 2021-04-21 15:13:45 -04:00
parent b58deee457
commit d74ff31a3c
2 changed files with 92 additions and 0 deletions

23
frontmatter.go Normal file
View File

@ -0,0 +1,23 @@
package main
import "bytes"
var (
frontmatterOpen = []byte("---")
frontmatterClose = []byte("\n---")
)
func extractFrontmatter(b []byte) (frontmatter, content []byte) {
if !bytes.HasPrefix(b, frontmatterOpen) {
return nil, b
}
fm := b[len(frontmatterOpen):]
if len(fm) != 0 && fm[0] != '\n' {
return nil, b
}
i := bytes.Index(fm, frontmatterClose)
if i == -1 {
i = len(fm)
}
return fm[:i], b[len(frontmatterOpen)+len(fm):]
}

69
frontmatter_test.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"testing"
)
func TestExtractFrontmatter(t *testing.T) {
tests := []struct {
Raw string
Frontmatter string
Content string
}{
{
Raw: "",
Frontmatter: "",
Content: "",
},
{
Raw: "---\na: b\nc: d\n---",
Frontmatter: "\na: b\nc: d",
Content: "",
},
{
Raw: "# Hello, world!",
Frontmatter: "",
Content: "# Hello, world!",
},
{
Raw: "---\ne: f\ng: h",
Frontmatter: "\ne: f\ng: h",
Content: "",
},
{
Raw: "----\na: b\nc: d",
Frontmatter: "",
Content: "----\na: b\nc: d",
},
{
Raw: "---\n---",
Frontmatter: "",
Content: "",
},
{
Raw: "\n---\n---\nHello, world!",
Frontmatter: "",
Content: "\n---\n---\nHello, world!",
},
{
Raw: "---",
Frontmatter: "",
Content: "",
},
{
Raw: "----",
Frontmatter: "",
Content: "----",
},
}
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))
}
if string(content) != test.Content {
t.Fatalf("expected content %q, got %q", test.Content, string(content))
}
}
}