-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
414 lines (360 loc) · 9.93 KB
/
main.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"text/template"
"time"
"github.com/jcgregorio/piccolo/piccolo"
"golang.org/x/net/html"
)
const (
SITE_TITLE = "BitWorking"
DOMAIN = "https://bitworking.org/"
FEED_LEN = 4
)
var shortMonths = [...]string{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
}
func fatalf(format string, args ...interface{}) {
fmt.Printf(format, args...)
os.Exit(1)
}
// ShortMonth returns the short English name of the month ("Jan", "Feb", ...).
func ShortMonth(m time.Month) string { return shortMonths[m-1] }
type datediffer func(time.Time) string
// datediff returns a function that formats the archive entries correctly.
//
// The returned function is a closure that keeps track of the last time.Time it
// saw which it needs to do the formatting correctly.
func datediff() datediffer {
var last time.Time
return func(t time.Time) string {
r := ""
if t.After(last) {
r = fmt.Sprintf("foo %#v", t)
}
// If years differ, emit year, month, day
if t.Year() != last.Year() {
r = fmt.Sprintf("<i><b>%d</b></i></td><td></td></tr>\n <tr><td><b>%s</b></td><td></td></tr>\n <tr><td> %d", t.Year(), ShortMonth(t.Month()), t.Day())
} else if t.Month() != last.Month() {
r = fmt.Sprintf("<b>%s</b></td><td></td></tr>\n <tr><td> %d", ShortMonth(t.Month()), t.Day())
} else {
r = fmt.Sprintf("%d", t.Day())
}
last = t
return r
}
}
// trunc10 formats a time to just the year, month and day in ISO format.
func trunc10(t time.Time) string {
return t.Format("2006-01-02")
}
// rfc339 formats a time in RFC3339 format.
func rfc3339(t time.Time) string {
return t.Format(time.RFC3339)
}
// Templates contains all the parsed templates.
type Templates struct {
IndexHTML *template.Template
IndexAtom *template.Template
ArchiveHTML *template.Template
EntryHTML *template.Template
}
func loadTemplate(d *piccolo.DocSet, name string) *template.Template {
funcMap := template.FuncMap{
"datediff": datediff(),
"trunc10": trunc10,
"rfc3339": rfc3339,
}
fullname := filepath.Join(d.Root, "tpl", name)
return template.Must(template.New(name).Funcs(funcMap).ParseFiles(fullname))
}
func loadTemplates(d *piccolo.DocSet) *Templates {
return &Templates{
IndexHTML: loadTemplate(d, "index.html"),
IndexAtom: loadTemplate(d, "index.atom"),
ArchiveHTML: loadTemplate(d, "archive.html"),
EntryHTML: loadTemplate(d, "entry.html"),
}
}
// Expand expands the template with the given data.
func Expand(d *piccolo.DocSet, t *template.Template, data interface{}, path string) error {
dst, err := d.Dest(path)
if err != nil {
return err
}
dstDir, _ := filepath.Split(dst)
if err := os.MkdirAll(dstDir, 0755); err != nil {
return err
}
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
t.Execute(out, data)
return nil
}
// SimpleInclude loads the include file given the docset d.
//
func SimpleInclude(d *piccolo.DocSet, filename string) (string, time.Time, error) {
fullname := filepath.Join(d.Root, filename)
f, err := os.Open(fullname)
if err != nil {
return "", time.Time{}, err
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return "", time.Time{}, err
}
t := stat.ModTime()
b, err := ioutil.ReadAll(f)
if err != nil {
return "", time.Time{}, err
}
return string(b), t, nil
}
// Include loads the include file given the docset d.
//
// Returns the extracted HTML and the time the file was last modified.
func Include(d *piccolo.DocSet, filename, element string) (string, time.Time, error) {
fullname := filepath.Join(d.Root, "inc", filename)
f, err := os.Open(fullname)
if err != nil {
return "", time.Time{}, err
}
defer f.Close()
stat, err := f.Stat()
if err != nil {
return "", time.Time{}, err
}
t := stat.ModTime()
doc, err := html.Parse(f)
if err != nil {
return "", time.Time{}, err
}
var found func(*html.Node)
children := []*html.Node{}
found = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == element {
for c := n.FirstChild; c != nil; c = c.NextSibling {
children = append(children, c)
}
return
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
found(c)
}
}
found(doc)
return StrFromNodes(children), t, nil
}
// Newest returns the most recent of all the times passed in.
func Newest(times ...time.Time) time.Time {
newest := times[0]
for _, t := range times {
if t.After(newest) {
newest = t
}
}
return newest
}
// StrFromNodes returns the string of the rendered html.Nodes.
func StrFromNodes(nodes []*html.Node) string {
buf := bytes.NewBuffer([]byte{})
for _, h := range nodes {
html.Render(buf, h)
}
return buf.String()
}
// Entry represents a single blog entry.
type Entry struct {
// Path is the source file path.
Path string
// Title is the title of the entry.
Title string
// URL is the relative URL of the file.
URL string
// Created is the created time.
Created time.Time
// Upated is the updated time.
Updated time.Time
// Body is the string representation of the body element, w/o
// the <body> tags.
Body string
}
// EntryByCreated is a type that allows sorting Entries by their created time.
type EntryByCreated []*Entry
func (s EntryByCreated) Len() int { return len(s) }
func (s EntryByCreated) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s EntryByCreated) Less(i, j int) bool { return s[i].Created.After(s[j].Created) }
// TemplateData is the data used for expanding the index and archive (html and atom) templates.
type TemplateData struct {
// Domain is the domain name the site will be served from.
Domain string
SiteTitle string
Header string
InlineCSS string
Titlebar string
Footer string
Entries []*Entry
// Most recent time anything on the site was updated.
Updated time.Time
}
func modifiedTime(path string) time.Time {
mod := time.Time{}
if stat, err := os.Stat(path); err == nil {
mod = stat.ModTime()
}
return mod
}
func incMust(s string, t time.Time, err error) (string, time.Time) {
if err != nil {
log.Fatalf("Error loading header: %v\n", err)
}
return s, t
}
func main() {
cwd, err := os.Getwd()
if err != nil {
log.Fatalf("Failed to get cwd: %v\n", err)
}
d, err := piccolo.NewDocSet(cwd)
if err != nil {
log.Fatalf("Error building docset: %v\n", err)
}
fmt.Printf("Root: %s\n", d.Root)
templates := loadTemplates(d)
headerStr, headerMod := incMust(Include(d, "header.html", "head"))
inlineCss, inlineCssMod := incMust(SimpleInclude(d, "out/prefixed.css"))
footerStr, footerMod := incMust(Include(d, "footer.html", "body"))
titlebarStr, titlebarMod := incMust(Include(d, "titlebar.html", "body"))
entryMod := modifiedTime(filepath.Join(d.Root, "tpl", "entry.html"))
incMod := Newest(headerMod, inlineCssMod, footerMod, titlebarMod, entryMod)
oneentry := make([]*Entry, 1)
data := &TemplateData{
Domain: DOMAIN,
SiteTitle: SITE_TITLE,
Header: headerStr,
InlineCSS: string(inlineCss),
Titlebar: titlebarStr,
Footer: footerStr,
Entries: oneentry,
}
entries := make([]*Entry, 0)
// Walk the docset and copy over files, possibly transformed. Collect all
// the entries along the way.
walker := func(path string, info os.FileInfo, err error) error {
attr, err := d.Path(path)
if err != nil {
return err
}
if info.IsDir() && attr.Has(piccolo.IGNORE) {
return filepath.SkipDir
}
dest, err := d.Dest(path)
if err != nil {
return err
}
destMod := modifiedTime(dest)
if !info.IsDir() && attr.Has(piccolo.INCLUDE) {
if filepath.Ext(path) == ".html" {
fileinfo, err := piccolo.CreationDateSaved(path)
if err != nil {
return err
}
if err := piccolo.LaTex(fileinfo.Node, d.Root); err != nil {
fmt.Printf("Error: expanding LaTex: %s", err)
}
url, err := d.URL(path)
if err != nil {
return err
}
entries = append(entries, &Entry{
Path: path,
Title: fileinfo.Title,
URL: url,
Created: fileinfo.Created,
Updated: fileinfo.Updated,
})
if Newest(fileinfo.Updated, incMod).After(destMod) {
fmt.Printf("INCLUDE: %v\n", dest)
// Use the data for template expansion, but with only one entry in it.
data.Entries[0] = entries[len(entries)-1]
data.Entries[0].Body = StrFromNodes(fileinfo.Body())
if err := Expand(d, templates.EntryHTML, data, path); err != nil {
return err
}
}
}
}
if !info.IsDir() && attr.Has(piccolo.VERBATIM) {
if info.ModTime().After(destMod) {
fmt.Printf("VERBATIM: %v\n", dest)
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return err
}
dst, err := os.Create(dest)
if err != nil {
return err
}
defer dst.Close()
src, err := os.Open(path)
if err != nil {
return err
}
defer src.Close()
_, err = io.Copy(dst, src)
if err != nil {
return err
}
}
}
return nil
}
err = filepath.Walk(d.Root, walker)
if err != nil {
fatalf("Error walking: %v\n", err)
}
sort.Sort(EntryByCreated(entries))
data.Entries = entries
// TODO(jcgregorio) This is actually wrong, need to sort by Updated first, as if anyone cares.
data.Updated = entries[0].Updated
if err := Expand(d, templates.ArchiveHTML, data, filepath.Join(d.Archive, "index.html")); err != nil {
fatalf("Error building archive: %v\n", err)
}
// Take the first 10 items from the list, expand the Body, then pass to templates.
latest := entries[:FEED_LEN]
for _, e := range latest {
fi, _ := piccolo.CreationDateSaved(e.Path)
if err := piccolo.LaTex(fi.Node, d.Root); err != nil {
fmt.Printf("Error: expanding LaTex: %s", err)
}
e.Body = StrFromNodes(fi.Body())
}
data.Entries = latest
if err := Expand(d, templates.IndexHTML, data, filepath.Join(d.Main, "index.html")); err != nil {
fatalf("Error building archive: %v\n", err)
}
if err := Expand(d, templates.IndexAtom, data, filepath.Join(d.Feed, "index.atom")); err != nil {
fatalf("Error building feed: %v\n", err)
}
}