summaryrefslogtreecommitdiff
path: root/markdown/markdown.go
blob: cc2abf1eb157e49b37ef7843d0f72b55d9c65491 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package markdown

import (
	"bytes"
	"fmt"
	"io/fs"
	"path/filepath"
	"strings"

	"git.sr.ht/~a73x/home/content"
	"github.com/adrg/frontmatter"
)

type Content struct {
	Meta map[string]any
	Body string
	Path string
}

func ParseContents() ([]Content, error) {
	contentFiles, err := glob(content.FS, ".", ".md")
	if err != nil {
		return nil, fmt.Errorf("failed to glob: %v", err)
	}

	res := make([]Content, 0, len(contentFiles))
	for _, contentFile := range contentFiles {
		c, err := parseMarkdownFile(content.FS, contentFile)
		if err != nil {
			return nil, fmt.Errorf("failed to read markdown file: %v", err)
		}

		res = append(res, c)
	}

	return res, nil
}

func glob(embedded fs.FS, dir string, ext string) ([]string, error) {
	files := []string{}
	err := fs.WalkDir(embedded, dir, func(path string, d fs.DirEntry, err error) error {
		if filepath.Ext(path) == ext {
			files = append(files, path)
		}
		return nil
	})

	return files, err
}

func parseMarkdownFile(embedded fs.FS, path string) (Content, error) {
	input, err := fs.ReadFile(embedded, path)
	if err != nil {
		return Content{}, fmt.Errorf("failed to read post: %v", err)
	}

	matter := map[string]any{}
	matter["template"] = "default"
	rest, err := frontmatter.Parse(bytes.NewBuffer(input), &matter)
	if err != nil {
		return Content{}, fmt.Errorf("failed to parse frontmatter: %v", err)
	}
	path = strings.Replace(path, ".md", "", 1)
	if path == "index" {
		path = ""
	}

	path = "/" + path

	mc := Content{
		Body: string(rest),
		Path: path,
		Meta: matter,
	}

	return mc, nil
}