diff --git a/core/frontmatter/doc.go b/core/frontmatter/doc.go new file mode 100644 index 0000000..b723de9 --- /dev/null +++ b/core/frontmatter/doc.go @@ -0,0 +1,2 @@ +// Package frontmatter contains utilities for parsing front matter from documents. +package frontmatter diff --git a/core/frontmatter/parser.go b/core/frontmatter/parser.go new file mode 100644 index 0000000..2b82de1 --- /dev/null +++ b/core/frontmatter/parser.go @@ -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 +} diff --git a/test/doc.go b/test/doc.go new file mode 100644 index 0000000..361c240 --- /dev/null +++ b/test/doc.go @@ -0,0 +1,2 @@ +// Package test contains all test files for the project. +package test diff --git a/test/frontmatter_test.go b/test/frontmatter_test.go new file mode 100644 index 0000000..3f84a90 --- /dev/null +++ b/test/frontmatter_test.go @@ -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) + } + } +}