feat(frontmatter): parsing and tag extract
This commit is contained in:
parent
74a0d9603c
commit
5e0dbe5873
3 changed files with 47 additions and 3 deletions
|
|
@ -3,10 +3,20 @@ package frontmatter
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type FrontMatter struct {
|
||||||
|
Title string
|
||||||
|
Tags []string
|
||||||
|
Created string
|
||||||
|
Updated string
|
||||||
|
Author string
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
func ParseFrontMatter(r io.Reader) (map[string]string, error) {
|
func ParseFrontMatter(r io.Reader) (map[string]string, error) {
|
||||||
scanner := bufio.NewScanner(r)
|
scanner := bufio.NewScanner(r)
|
||||||
frontMatter := make(map[string]string)
|
frontMatter := make(map[string]string)
|
||||||
|
|
@ -31,3 +41,16 @@ func ParseFrontMatter(r io.Reader) (map[string]string, error) {
|
||||||
|
|
||||||
return frontMatter, nil
|
return frontMatter, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExtractTags(frontMatter map[string]string) ([]string, error) {
|
||||||
|
tagsStr, ok := frontMatter["tags"]
|
||||||
|
if !ok {
|
||||||
|
return nil, errors.New("tags not found in front matter")
|
||||||
|
}
|
||||||
|
var tags []string
|
||||||
|
err := json.Unmarshal([]byte(tagsStr), &tags)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return tags, nil
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,2 +0,0 @@
|
||||||
// Package test contains all test files for the project.
|
|
||||||
package test
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
package test
|
package frontmatter_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
@ -31,3 +31,26 @@ This is the content of the note.`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExtractTags(t *testing.T) {
|
||||||
|
frontMatter := map[string]string{
|
||||||
|
"tags": `["test", "note"]`,
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := []string{"test", "note"}
|
||||||
|
|
||||||
|
result, err := frontmatter.ExtractTags(frontMatter)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(result) != len(expected) {
|
||||||
|
t.Fatalf("expected %d tags, got %d", len(expected), len(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, expectedTag := range expected {
|
||||||
|
if result[i] != expectedTag {
|
||||||
|
t.Errorf("expected tag %d to be %s, got %s", i, expectedTag, result[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue