-
Notifications
You must be signed in to change notification settings - Fork 0
/
sitegen.go
578 lines (500 loc) · 12.1 KB
/
sitegen.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package sitegen
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/cheggaaa/pb"
"github.com/rubenv/pygmentize"
"github.com/russross/blackfriday"
"gopkg.in/yaml.v2"
)
func Start() {
templates = template.Must(template.ParseGlob("templates/*.html"))
// Crawl the filesystem tree.
log.Println("==> Crawling")
content, err := crawlContent()
if err != nil {
log.Fatal(err)
}
// Wait for parsing
log.Println("==> Parsing")
if parseError != nil {
log.Fatal(parseError)
}
// Allow processing metadata
if processor != nil {
log.Println("==> Processing")
content.Process()
if processError != nil {
log.Fatal(processError)
}
}
// Generate the output
log.Println("==> Generating")
err = os.MkdirAll("static", 0755)
if err != nil {
log.Fatal(err)
}
queue := NewContentQueue()
content.Write("static", queue)
queue.Wait()
if generateError != nil {
log.Printf("Failed to generate: %#v\n", generateError.Error())
}
}
var (
parseError error = nil
processError error = nil
generateError error = nil
templates *template.Template
processor MetadataProcessor
queue *ContentQueue
)
type ContentItem struct {
Filename string
FullPath string
Url string
Type ContentType
Content template.HTML
Children []*ContentItem
Metadata Metadata
Extra interface{}
}
type Metadata struct {
Title string
Template string
Date time.Time
}
type metadataTime struct {
Title string
Template string
Date string
}
type ContentType int
const (
Content ContentType = iota
Directory
Asset
)
func crawlContent() (*ContentItem, error) {
return readDir(".", "content")
}
func readDir(name, path string) (*ContentItem, error) {
fullPath := path + "/" + name
files, err := ioutil.ReadDir(fullPath)
if err != nil {
return nil, err
}
c := &ContentItem{
Filename: name,
FullPath: fullPath,
Type: Directory,
Children: make([]*ContentItem, 0),
}
for _, v := range files {
var child *ContentItem
filename := v.Name()
if isContentFile(filename) {
parts := strings.Split(filename, ".")
outname := strings.Join(parts[0:len(parts)-1], ".") + ".html"
child = &ContentItem{
Filename: outname,
FullPath: fullPath + "/" + filename,
Type: Content,
}
child.Parse(fullPath + "/" + filename)
} else if v.IsDir() {
child, err = readDir(filename, fullPath)
if err != nil {
return nil, err
}
} else {
child = &ContentItem{
Filename: filename,
FullPath: fullPath + "/" + filename,
Type: Asset,
}
}
c.Children = append(c.Children, child)
}
return c, nil
}
func isContentFile(filename string) bool {
return strings.HasSuffix(filename, ".html") || strings.HasSuffix(filename, ".md")
}
func splitContent(content []byte) (frontMatter, body []byte, err error) {
startDelim := []byte("---\n")
endDelim := []byte("\n---\n\n")
if bytes.HasPrefix(content, startDelim) {
endIndex := bytes.Index(content, endDelim)
if endIndex == -1 {
err = errors.New("No end delimiter found for metadata!")
return
}
frontMatter = content[len(startDelim):endIndex]
body = content[endIndex+len(endDelim) : len(content)]
} else {
frontMatter = nil
body = content
}
return
}
func (c *ContentItem) parseContent(filename string) error {
printName := strings.TrimPrefix(filename, "content/.")
log.Printf(" -> %s\n", printName)
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
frontMatter, body, err := splitContent(data)
if err != nil {
return err
}
if frontMatter != nil {
yaml.Unmarshal(frontMatter, &c.Metadata)
}
if c.Metadata.Template == "" {
c.Metadata.Template = "page"
}
var content []byte
if strings.HasSuffix(filename, ".md") {
content = RenderMarkdown(body)
} else {
content = body
}
c.Content = template.HTML(content)
return nil
}
func RenderMarkdown(input []byte) []byte {
// set up the HTML renderer
htmlFlags := 0
htmlFlags |= blackfriday.HTML_USE_XHTML
htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_LATEX_DASHES
htmlFlags |= blackfriday.HTML_FOOTNOTE_RETURN_LINKS
renderer := &renderer{
Html: blackfriday.HtmlRendererWithParameters(htmlFlags, "", "", blackfriday.HtmlRendererParameters{
FootnoteReturnLinkContents: "↩",
}).(*blackfriday.Html),
}
// set up the parser
extensions := 0
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
extensions |= blackfriday.EXTENSION_HEADER_IDS
extensions |= blackfriday.EXTENSION_FOOTNOTES
return blackfriday.Markdown(input, renderer, extensions)
}
type renderer struct {
*blackfriday.Html
}
func (r *renderer) BlockCode(out *bytes.Buffer, text []byte, lang string) {
out.WriteString("<highlight language=\"")
out.WriteString(lang)
out.WriteString("\">")
code := string(text)
code = strings.TrimRightFunc(code, unicode.IsSpace)
out.WriteString(code)
out.WriteString("</highlight>")
}
func (c *ContentItem) Parse(filename string) {
err := c.parseContent(filename)
if err != nil {
parseError = err
}
}
func (c *ContentItem) Process() {
c.Url = strings.TrimSuffix(strings.TrimPrefix(c.FullPath, "content/."), "index.html")
extra, err := processor(c)
if err != nil {
processError = err
return
}
c.Extra = extra
for _, v := range c.Children {
v.Process()
}
}
func (c *ContentItem) Write(path string, queue *ContentQueue) {
fullPath := path + "/" + c.Filename
printName := strings.TrimPrefix(fullPath, "static/.")
if printName != "" {
log.Printf(" -> %s\n", printName)
}
ci := queue.Insert(c)
go func() {
err := c.write(fullPath)
if err != nil {
generateError = err
}
ci.Result <- true
}()
for _, v := range c.Children {
v.Write(fullPath, queue)
}
}
func (c *ContentItem) write(path string) error {
if c.Type == Directory {
err := os.MkdirAll(path, 0755)
if err != nil {
return err
}
} else if c.Type == Content {
err := c.WriteContent(path)
if err != nil {
return fmt.Errorf("write failed for %s: %s", path, err)
}
} else if c.Type == Asset {
out := strings.Replace(c.FullPath, "content/.", "static", 1)
err := copyFile(c.FullPath, out)
if err != nil {
return err
}
}
return nil
}
var codeRegex = regexp.MustCompile(`(?s)<highlight(.*?)>(.*?)</highlight>`)
func (c *ContentItem) WriteContent(path string) error {
out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer out.Close()
buf := &bytes.Buffer{}
err = templates.ExecuteTemplate(buf, c.Metadata.Template, c)
if err != nil {
return err
}
var innerErr error = nil
var badCode string = ""
html := codeRegex.ReplaceAllStringFunc(string(buf.Bytes()), func(in string) string {
parts := codeRegex.FindStringSubmatch(in)
attrs := parseAttributes(parts[1])
code := strings.TrimRightFunc(parts[2], unicode.IsSpace)
code = strings.TrimLeft(code, "\n")
formatted, err := pygmentize.HighlightLanguage(code, attrs["language"], pygmentize.NewHtmlFormatter())
if err != nil {
innerErr = err
badCode = code
return ""
}
lines := strings.Split(strings.TrimRightFunc(formatted, unicode.IsSpace), "\n")
var out bytes.Buffer
out.WriteString(`<div class="code`)
if attrs["language"] != "" {
out.WriteString(" code-")
out.WriteString(attrs["language"])
}
out.WriteString(`">`)
if attrs["title"] != "" {
out.WriteString(`<div class="title">`)
out.WriteString(attrs["title"])
out.WriteString(`</div>`)
}
out.WriteString(`<div class="scroller"><table><tr><td class="nrs">`)
for i, _ := range lines {
out.WriteString(`<div class="nr">`)
out.WriteString(strconv.Itoa(i + 1))
out.WriteString(`</div>`)
}
out.WriteString(`</td><td class="src"><pre>`)
out.WriteString("<pre>")
out.WriteString(strings.TrimRightFunc(formatted, unicode.IsSpace))
out.WriteString(`</pre></td></tr></table></div></div>`)
return string(out.Bytes())
})
if innerErr != nil {
log.Printf("%s %#v\n", path, innerErr.Error())
log.Println(badCode)
return innerErr
}
_, err = out.WriteString(html)
return err
}
// Metadata processing
type MetadataProcessor func(item *ContentItem) (interface{}, error)
func SetMetadataProcessor(f MetadataProcessor) {
processor = f
}
// Time handling
func (m *Metadata) UnmarshalYAML(unmarshal func(interface{}) error) error {
md := &metadataTime{}
if err := unmarshal(md); err != nil {
return err
}
loc, _ := time.LoadLocation("Europe/Brussels")
t, err := time.ParseInLocation("2006-01-02 15:04:05", md.Date, loc)
if err != nil {
return err
}
// TODO: Use reflection to copy all fields.
m.Title = md.Title
m.Template = md.Template
m.Date = t
return nil
}
// Processing queue
type ContentQueue struct {
lock *sync.Mutex
items []*ContentQueueItem
}
type ContentQueueItem struct {
item *ContentItem
Result chan bool
}
func NewContentQueue() *ContentQueue {
return &ContentQueue{
lock: &sync.Mutex{},
items: make([]*ContentQueueItem, 0),
}
}
func (c *ContentQueue) Insert(i *ContentItem) *ContentQueueItem {
c.lock.Lock()
defer c.lock.Unlock()
ci := &ContentQueueItem{
item: i,
Result: make(chan bool, 1),
}
c.items = append(c.items, ci)
return ci
}
func (c *ContentQueue) Wait() {
finished := 0
bar := pb.StartNew(len(c.items))
for finished < len(c.items) {
<-c.items[finished].Result
finished++
bar.Increment()
}
bar.Finish()
}
// Utilities
var attrRegex = regexp.MustCompile(`(\w+)=('|")(.*?)('|")`)
type step int
const (
attr_key step = iota
attr_val step = iota
attr_space step = iota
)
func parseAttributes(in string) map[string]string {
in = strings.TrimSpace(in)
attrs := make(map[string]string)
curr := attr_key
start := 0
pos := 0
key := ""
val := ""
quote := '"'
for pos < len(in) {
switch curr {
case attr_key:
if in[pos] == '=' {
key = in[start:pos]
val = ""
curr = attr_val
quote = rune(in[pos+1])
start = pos + 2
pos++
}
pos++
case attr_val:
if in[pos] == '\\' {
val += in[start:pos]
pos++
val += in[pos : pos+1]
pos++
start = pos
} else if rune(in[pos]) == quote {
val += in[start:pos]
attrs[key] = val
curr = attr_space
}
pos++
case attr_space:
if in[pos] == ' ' {
pos++
} else {
curr = attr_key
start = pos
}
}
}
return attrs
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// copyFile copies a file from src to dst. If src and dst files exist, and are
// the same, then return success. Otherise, attempt to create a hard link
// between the two files. If that fail, copy the file contents from src to dst.
func copyFile(src, dst string) (err error) {
sfi, err := os.Stat(src)
if err != nil {
return
}
if !sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
return fmt.Errorf("copyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(dst)
if err != nil {
if !os.IsNotExist(err) {
return
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("copyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return
}
}
if err = os.Link(src, dst); err == nil {
return
}
return copyFileContents(src, dst)
}
// copyFileContents copies the contents of the file named src to the file named
// by dst. The file will be created if it does not already exist. If the
// destination file exists, all it's contents will be replaced by the contents
// of the source file.
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}