test(frontmatter): test simple frontmatter parser
This commit is contained in:
parent
e27a564445
commit
74a0d9603c
4 changed files with 70 additions and 0 deletions
2
core/frontmatter/doc.go
Normal file
2
core/frontmatter/doc.go
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// Package frontmatter contains utilities for parsing front matter from documents.
|
||||
package frontmatter
|
||||
33
core/frontmatter/parser.go
Normal file
33
core/frontmatter/parser.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package frontmatter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
func ParseFrontMatter(r io.Reader) (map[string]string, error) {
|
||||
scanner := bufio.NewScanner(r)
|
||||
frontMatter := make(map[string]string)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == "---" {
|
||||
break
|
||||
}
|
||||
parts := bytes.SplitN([]byte(line), []byte(":"), 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, errors.New("invalid front matter format")
|
||||
}
|
||||
key := string(bytes.TrimSpace(parts[0]))
|
||||
value := string(bytes.TrimSpace(parts[1]))
|
||||
frontMatter[key] = value
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return frontMatter, nil
|
||||
}
|
||||
2
test/doc.go
Normal file
2
test/doc.go
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
// Package test contains all test files for the project.
|
||||
package test
|
||||
33
test/frontmatter_test.go
Normal file
33
test/frontmatter_test.go
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
package test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/KristianJBorgwarth/dendrite.daemon/core/frontmatter"
|
||||
)
|
||||
|
||||
func TestParseFrontMatter(t *testing.T) {
|
||||
input := `title: My Note
|
||||
template: default
|
||||
tags: ["test", "note"]
|
||||
---
|
||||
This is the content of the note.`
|
||||
|
||||
expected := map[string]string{
|
||||
"title": "My Note",
|
||||
"template": "default",
|
||||
"tags": `["test", "note"]`,
|
||||
}
|
||||
|
||||
result, err := frontmatter.ParseFrontMatter(strings.NewReader(input))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
for key, expectedValue := range expected {
|
||||
if value, ok := result[key]; !ok || value != expectedValue {
|
||||
t.Errorf("expected %s to be %s, got %s", key, expectedValue, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue