all repos — homestead @ 526002b13309812ce647faff2bdf66d6991ec467

Code for my website

internal/content/posts.go (view raw)

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package content

import (
	"bytes"
	"context"
	"io"
	"os"
	"path"
	"path/filepath"
	"slices"
	"strings"
	"time"

	"go.alanpearce.eu/x/log"

	"github.com/adrg/frontmatter"
	mapset "github.com/deckarep/golang-set/v2"
	fences "github.com/stefanfritsch/goldmark-fences"
	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
	htmlrenderer "github.com/yuin/goldmark/renderer/html"
	"gitlab.com/tozd/go/errors"
)

type PostMatter struct {
	Date        time.Time
	Description string
	Title       string
	Taxonomies  struct {
		Tags []string
	}
}

type Post struct {
	Input    string
	Output   string
	Basename string
	URL      string
	*PostMatter

	content []byte
}

type Config struct {
	Root    string
	PostDir string
}

type Collection struct {
	config *Config

	Posts []Post
	Tags  mapset.Set[string]
}

var markdown = goldmark.New(
	goldmark.WithRendererOptions(
		htmlrenderer.WithUnsafe(),
	),
	goldmark.WithExtensions(
		extension.GFM,
		extension.Footnote,
		extension.Typographer,
		&fences.Extender{},
	),
)

var postOutputReplacer = strings.NewReplacer(
	"index.md", "index.html",
	".md", "/index.html",
)
var postURLReplacer = strings.NewReplacer(
	"index.md", "",
	".md", "/",
)

func (cc *Collection) GetPost(filename string) (*Post, error) {
	fp := filepath.Join(cc.config.Root, cc.config.PostDir, filename)
	url := path.Join("/", cc.config.PostDir, postURLReplacer.Replace(filename)) + "/"
	post := &Post{
		Input:      fp,
		Output:     path.Join(cc.config.PostDir, postOutputReplacer.Replace(filename)),
		Basename:   filepath.Base(url),
		URL:        url,
		PostMatter: &PostMatter{},
	}

	err := parse(fp, post)
	if err != nil {
		return nil, err
	}

	return post, nil
}

var pageOutputReplacer = strings.NewReplacer(
	"index.md", "index.html",
	".md", ".html",
)
var pageURLReplacer = strings.NewReplacer(
	"index.md", "",
	".md", "",
)

func (cc *Collection) GetPage(filename string) (*Post, error) {
	fp := filepath.Join(cc.config.Root, filename)
	url := path.Join("/", pageURLReplacer.Replace(filename))
	post := &Post{
		Input:      fp,
		Output:     pageOutputReplacer.Replace(filename),
		Basename:   filepath.Base(url),
		URL:        url,
		PostMatter: &PostMatter{},
	}

	err := parse(fp, post)
	if err != nil {
		return nil, err
	}

	return post, nil
}

func parse(fp string, post *Post) error {
	content, err := os.Open(fp)
	if err != nil {
		return errors.WithMessagef(err, "could not open post %s", fp)
	}
	defer content.Close()

	post.content, err = frontmatter.Parse(content, post.PostMatter)
	if err != nil {
		return errors.WithMessagef(
			err,
			"could not parse front matter of post %s",
			fp,
		)
	}

	return nil
}

// implements templ.Component
func (p *Post) Render(_ context.Context, w io.Writer) error {
	return markdown.Convert(p.content, w)
}

func (p *Post) RenderString() (string, error) {
	var buf bytes.Buffer
	if err := p.Render(context.Background(), &buf); err != nil {
		return "", errors.WithMessage(err, "could not convert markdown content")
	}

	return buf.String(), nil
}

func NewContentCollection(config *Config, log *log.Logger) (*Collection, error) {
	cc := &Collection{
		Posts:  []Post{},
		Tags:   mapset.NewSet[string](),
		config: config,
	}

	log.Debug("reading posts", "root", config.Root, "input_dir", config.PostDir)
	subdir := filepath.Join(config.Root, config.PostDir)
	files, err := os.ReadDir(subdir)
	if err != nil {
		return nil, errors.WithMessagef(err, "could not read post directory %s", subdir)
	}
	for _, f := range files {
		fn := f.Name()
		if !f.IsDir() && path.Ext(fn) == ".md" {
			log.Debug("reading post", "post", fn)
			post, err := cc.GetPost(fn)
			if err != nil {
				return nil, err
			}

			for _, tag := range post.PostMatter.Taxonomies.Tags {
				cc.Tags.Add(strings.ToLower(tag))
			}

			cc.Posts = append(cc.Posts, *post)
		}
	}
	slices.SortFunc(cc.Posts, func(a, b Post) int {
		return b.Date.Compare(a.Date)
	})

	return cc, nil
}