summaryrefslogtreecommitdiff
path: root/internal/frontmatter/parser.go
blob: 3c00a7f252966eacc7f70ce4f07fe2f1d0cf10e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package frontmatter

import (
	"fmt"
	"regexp"
	"time"

	"gopkg.in/yaml.v3"
)

type Metadata struct {
	Title            string    `yaml:"title"`
	ShortDescription string    `yaml:"shortDescription"`
	ActionDate       string    `yaml:"actionDate"`
	PublishedTime    time.Time `yaml:"publishedTime"`
	Thumbnail        string    `yaml:"thumbnail"`
	Tags             []string  `yaml:"tags"`
	Geolocation      string    `yaml:"geolocation"`
	Timezone         string    `yaml:"timezone"`
}

func ParseFrontmatter(content []byte) (metadata *Metadata, markdown []byte, err error) {
	frontmatterRegex := regexp.MustCompile(`^---\s*\r?\n([\s\S]*?)\r?\n---\s*\r?\n([\s\S]*)$`)
	matches := frontmatterRegex.FindSubmatch(content)

	if len(matches) != 3 {
		return nil, content, nil
	}

	yamlContent := matches[1]
	markdownContent := matches[2]

	metadata = &Metadata{}
	if err := yaml.Unmarshal([]byte(yamlContent), &metadata); err != nil {
		return nil, nil, fmt.Errorf("failed to parse YAML frontmatter: %w", err)
	}

	return metadata, markdownContent, nil
}