-
Notifications
You must be signed in to change notification settings - Fork 0
/
blog.go
288 lines (249 loc) · 6.64 KB
/
blog.go
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package main
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// Version 2, December 2004
//
// Copyright (C) 2024 Thiago Kenji Okada <[email protected]>
//
// Everyone is permitted to copy and distribute verbatim or modified
// copies of this license document, and changing it is allowed as long
// as the name is changed.
//
// DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
// TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
//
// 0. You just DO WHAT THE FUCK YOU WANT TO.
import (
"bytes"
"flag"
"fmt"
"io/fs"
"log"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/alecthomas/chroma/formatters/html"
"github.com/elliotchance/orderedmap/v2"
"github.com/gorilla/feeds"
"github.com/gosimple/slug"
"github.com/yuin/goldmark"
highlighting "github.com/yuin/goldmark-highlighting"
"github.com/yuin/goldmark/extension"
)
const (
blogBaseUrl = "https://github.com/thiagokokada/blog"
blogMainUrl = blogBaseUrl + "/blob/main/"
blogRawUrl = blogBaseUrl + "/raw/main/"
readmeTemplate = `# Blog
Mirror of my blog in https://kokada.capivaras.dev/.
## Posts
[![RSS](https://img.shields.io/badge/RSS-FFA562?style=for-the-badge&logo=rss&logoColor=white)](https://raw.githubusercontent.com/thiagokokada/blog/main/rss.xml)
%s
`
)
type post struct {
title string
slug string
contents []byte
date time.Time
}
type path = string
type posts = *orderedmap.OrderedMap[path, post]
func must2[T1, T2 any](v1 T1, v2 T2, err error) (T1, T2) {
must(err)
return v1, v2
}
func must1[T any](v T, err error) T {
must(err)
return v
}
func must(err error) {
if err != nil {
panic(err)
}
}
func extractTitleAndContents(raw []byte) (title string, contents []byte, err error) {
if len(raw) == 0 {
return "", nil, fmt.Errorf("empty file")
}
// We are assuming that each file has one title as a H1 header...
if raw[0] != '#' {
return "", nil, fmt.Errorf("missing '#' (H1) at the start of file")
}
// ...followed by a line break and the contents
for i, c := range raw {
if c != '\n' {
continue
}
title = string(bytes.TrimSpace(raw[1:i]))
contents = bytes.TrimSpace(raw[i:])
break
}
// If we scan the whole file and title or contents are empty, something
// is wrong with the file
if title == "" {
return title, contents, fmt.Errorf("could not find title")
}
if contents == nil {
return title, contents, fmt.Errorf("could not find content")
}
return title, contents, nil
}
func getAndValidateSlug(mdFilename, title string) (string, error) {
// 01-my-awesome-blog-post.md => my-awesome-blog-post
filenameSlug := strings.TrimSuffix(mdFilename[3:], ".md")
// My awesome blog post => my-awesome-blog-post
titleSlug := getSlug(title)
// Add any filename that are known to be broken, generally because the
// title got changed after publishing
knownBrokenFilenames := []string{
// Typo, should be "troubleshooting"
"01-troubleshoting-zsh-lag-and-solutions-with-nix.md",
}
if filenameSlug != titleSlug && !slices.Contains(knownBrokenFilenames, mdFilename) {
return filenameSlug, fmt.Errorf(
"got conflicting slugs: filename slug: %s, title slug: %s",
filenameSlug,
titleSlug,
)
}
return filenameSlug, nil
}
func getSlug(s string) string {
return slug.Make(s)
}
func grabPosts(root string) (posts, error) {
posts := orderedmap.NewOrderedMap[path, post]()
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Ignore hidden files
if d.Name()[0] == '.' {
return nil
}
// Ignore non-Markdown files
if filepath.Ext(d.Name()) != ".md" {
return nil
}
// Get the base directory of the file
dir := filepath.Base(filepath.Dir(path))
// Ignore files in the current directory
if dir == "." {
return nil
}
// Parse directory name as a date
date, err := time.Parse(time.DateOnly, dir)
if err != nil {
log.Printf("[WARN]: ignoring non-date directory: %s\n", path)
return nil
}
// Load the contents of the Markdown and try to parse
// the title
raw, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf(
"something went wrong when reading file: %s, error: %w",
path,
err,
)
}
title, contents, err := extractTitleAndContents(raw)
if err != nil || title == "" || contents == nil {
return fmt.Errorf(
"something is wrong with file: %s, error: %w",
path,
err,
)
}
slug, err := getAndValidateSlug(d.Name(), title)
if err != nil {
return fmt.Errorf(
"something is wrong with slug for file: %s, error: %w",
path,
err,
)
}
if date.After(time.Now()) {
log.Printf("[INFO]: ignoring future post: %s\n", path)
return nil
}
posts.Set(path, post{
title: title,
slug: slug,
contents: contents,
date: date,
})
return nil
})
return posts, err
}
func genRss(ps posts) string {
feed := &feeds.Feed{
Title: "kokada's blog",
Description: "# dd if=/dev/urandom of=/dev/brain0",
}
md := goldmark.New(
goldmark.WithExtensions(
NewLinkRewriter(blogMainUrl, nil),
extension.GFM,
highlighting.NewHighlighting(
highlighting.WithStyle("monokai"),
highlighting.WithFormatOptions(html.Standalone(true)),
),
),
)
var items []*feeds.Item
for el := ps.Back(); el != nil; el = el.Prev() {
path, post := el.Key, el.Value
link := must1(url.JoinPath(blogMainUrl, path))
var buf bytes.Buffer
must(md.Convert(post.contents, &buf))
items = append(items, &feeds.Item{
Title: post.title,
Link: &feeds.Link{Href: link},
Created: post.date,
Id: link,
Description: buf.String(),
})
}
feed.Items = items
return must1(feed.ToRss())
}
func genReadme(ps posts) string {
var titles []string
for el := ps.Back(); el != nil; el = el.Prev() {
path, post := el.Key, el.Value
title := fmt.Sprintf(
"- [%s](%s) - %s",
post.title,
path,
post.date.Format(time.DateOnly),
)
titles = append(titles, title)
}
return fmt.Sprintf(readmeTemplate, strings.Join(titles, "\n"))
}
func main() {
slugify := flag.String("slugify", "", "Slugify input (e.g.: for blog titles)")
rss := flag.Bool("rss", false, "Generate RSS (XML) instead of README.md")
prepare := flag.Bool("prepare", false, "Prepare posts to Mataroa (e.g.: validate posts, mostly for debug)")
publish := flag.Bool("publish", false, "Publish updates to Maratoa instance")
flag.Parse()
if *slugify != "" {
fmt.Println(getSlug(*slugify))
os.Exit(0)
}
posts := must1(grabPosts("posts"))
if *prepare {
prepareToMataroa(posts)
} else if *publish {
publishToMataroa(posts)
} else if *rss {
fmt.Print(genRss(posts))
} else {
fmt.Print(genReadme(posts))
}
}