-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplates.go
279 lines (233 loc) · 5.58 KB
/
templates.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
package main
import (
"encoding/json"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"time"
"github.com/charmbracelet/log"
"github.com/gomarkdown/markdown"
i "github.com/nicksnyder/go-i18n/v2/i18n"
)
var fm = template.FuncMap{
"config": config,
"enabled": enabled,
"i18n": i18n,
"date": date,
"alternates": alternates,
"link": link,
"join": join,
"mkslice": mkslice,
"append": appendSlice,
"sort": sortSlice,
"uniq": uniq,
"nextPage": nextPage,
"prevPage": prevPage,
"stripTags": stripTags,
"htmlDecode": htmlDecode,
"hasSuffix": strings.HasSuffix,
"ts": func() string { return ts.Format(time.RFC3339) },
"jsonify": jsonify,
"divide": func(a, b int) int { return a / b },
"cleanPhotos": func(photos []Photo) []Photo {
var result []Photo
for _, photo := range photos {
photo.Title = md(photo.Title)
photo.BlurhashImageBase64 = ""
result = append(result, photo)
}
return result
},
"escape": escape,
"crc": crc32sum,
"md": md,
}
func config(key string) string {
return cfg.GetString(key)
}
func enabled(key string) bool {
return cfg.GetBool(key)
}
func i18n(key, lang string) string {
localizer := i.NewLocalizer(bundle, lang)
str, err := localizer.Localize(&i.LocalizeConfig{MessageID: key})
if err != nil {
log.Errorf("error localizing %q: %v", key, err)
return key
}
return str
}
func date(date, format string) string {
var t time.Time
if date == "" {
// use current time in UTC
t = time.Now().UTC()
} else {
// parse date
var err error
t, err = time.Parse("2006-01-02", date)
if err != nil {
log.Errorf("error parsing date %q: %v", date, err)
return date
}
}
if format == "" {
format = "2006-01-02"
}
return t.Format(format)
}
func alternates(data Data) []*MarkdownFile {
if len(data.Alternates) > 0 {
return data.Alternates
}
var result []*MarkdownFile
for _, file := range data.All {
if file.ID == data.File.ID {
result = append(result, file)
}
}
sort.Sort(ByLanguage(result))
return result
}
var langSuffix = regexp.MustCompile(`_([a-z]{2}).(html|md)$`)
func link(path string, langs ...string) string {
lang := ""
if len(langs) > 0 {
lang = langs[0]
}
link := path
if langSuffix.MatchString(path) {
match := langSuffix.FindStringSubmatch(path)
lang = match[1]
link = path[:len(path)-len(match[0])] + ".html"
}
if cfg.RemoveHTMLExtension {
link = strings.TrimSuffix(
strings.TrimSuffix(
strings.TrimSuffix(link, "index.html"),
".html",
),
"/",
)
}
if lang != "" && lang != cfg.DefaultLanguage {
link += "?lang=" + lang
}
return link
}
func join(sep string, items []string) string {
return strings.Join(items, sep)
}
func mkslice() []string {
return []string{}
}
func appendSlice(item string, items []string) []string {
return append(items, item)
}
func sortSlice(items []string) []string {
sort.Strings(items)
return items
}
func uniq(items []string) []string {
seen := make(map[string]struct{})
var result []string
for _, item := range items {
if _, ok := seen[item]; !ok {
seen[item] = struct{}{}
result = append(result, item)
}
}
return result
}
func prevPage(data Data) (prev *MarkdownFile) {
// technically, it get's the NEXT page
// from the list of all pages SORTED by created date (descending)
// but chronologically, it's the PREVIOUS page
prev = nil
var (
i int
file *MarkdownFile
)
for i, file = range data.AllSorted {
if file.Path == data.File.Path { // searching for the current page
break
}
}
for _, file := range data.AllSorted[i+1:] {
if file.ID == data.File.ID { // skipping same pages in different languages
continue
}
if file.Language == data.File.Language { // first page in the same language
prev = file
break
}
}
return
}
func nextPage(data Data) (next *MarkdownFile) {
// technically, it get's the PREVIOUS page
// from the list of all pages SORTED by created date (descending)
// but chronologically, it's the NEXT page
next = nil
for _, file := range data.AllSorted {
if file.Path == data.File.Path { // searching for the current page
break // this is the most recent page, so there's no next page
}
if file.Language == data.File.Language {
// last seen page in the same language
next = file
}
}
return
}
var htmlTagRegexp = regexp.MustCompile("<[^>]*>")
func stripTags(html string) string {
return htmlTagRegexp.ReplaceAllString(string(html), "")
}
func htmlDecode(html string) string {
return strings.ReplaceAll(html, "&", "&")
}
func jsonify(data interface{}) string {
b, err := json.Marshal(data)
if err != nil {
log.Errorf("error marshaling data: %v", err)
return ""
}
return string(b)
}
func md(in string) string {
in = string(markdown.ToHTML([]byte(in), nil, nil))
// remove newline at the end
return strings.TrimSuffix(strings.TrimPrefix(in, "<p>"), "</p>\n")
}
func escape(in string) string {
// escape quotes for HTML attributes
return strings.ReplaceAll(in, `"`, `"`)
}
var crc32sums = map[string]string{}
func crc32sum(s string) string {
if cached, ok := crc32sums[s]; ok {
return cached
}
// calculate CRC32 checksum for a file
file, err := os.Open(filepath.Join(cfg.ContentDirectory, s))
if err != nil {
log.Errorf("error opening file %q: %v", s, err)
return ""
}
defer file.Close()
hash := crc32.NewIEEE()
if _, err := io.Copy(hash, file); err != nil {
log.Errorf("error calculating CRC32 checksum for file %q: %v", s, err)
return ""
}
hashed := fmt.Sprintf("%x", hash.Sum32())
crc32sums[s] = hashed
return hashed
}