~adnano/kiln

ref: ec0209f928227f65493c4488af36e204f0fbf44b kiln/page.go -rw-r--r-- 7.9 KiB
ec0209f9Adnan Maolood page: Fix output path for index pages 7 months ago
                                                                                
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
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	pathpkg "path"
	"sort"
	"strings"
	"time"

	"gopkg.in/yaml.v3"
)

// Page represents a page.
type Page struct {
	Title     string
	Date      time.Time
	Weight    int
	Params    map[string]interface{}
	FilePath  string  `yaml:"-"`
	Permalink string  `yaml:"-"`
	Content   string  `yaml:"-"`
	Prev      *Page   `yaml:"-"`
	Next      *Page   `yaml:"-"`
	Pages     []*Page `yaml:"-"`
	Dirs      []*Page `yaml:"-"`
	feeds     map[string][]byte
	index     bool
}

// read reads from a directory and indexes the files and directories within it.
func (p *Page) read(srcDir string, task *Task, cfg *Site) error {
	return p._read(srcDir, "", task, cfg)
}

func (p *Page) _read(srcDir, path string, task *Task, cfg *Site) error {
	entries, err := ioutil.ReadDir(pathpkg.Join(srcDir, path))
	if err != nil {
		return err
	}
	for _, entry := range entries {
		name := entry.Name()
		path := pathpkg.Join(path, name)
		if entry.IsDir() {
			// Ignore directories beginning with "_"
			if strings.HasPrefix(name, "_") {
				continue
			}
			// Gather directory data
			dir := &Page{Permalink: "/" + path + "/", FilePath: path}
			if err := dir._read(srcDir, path, task, cfg); err != nil {
				return err
			}
			p.Dirs = append(p.Dirs, dir)
		} else if ext := pathpkg.Ext(name); task.Match(ext) {
			// Ignore pages beginning with "_" with the exception of _index pages
			namePrefix := strings.TrimSuffix(name, ext)
			if strings.HasPrefix(name, "_") && namePrefix != "_index" {
				continue
			}

			srcPath := pathpkg.Join(srcDir, path)
			content, err := ioutil.ReadFile(srcPath)
			if err != nil {
				return err
			}

			page := &Page{
				FilePath: path,
			}
			if namePrefix == "_index" {
				p.index = true
				page = p
			}

			// Try to parse the date from the page filename
			const layout = "2006-01-02"
			base := pathpkg.Base(path)
			if len(base) >= len(layout) {
				dateStr := base[:len(layout)]
				if time, err := time.Parse(layout, dateStr); err == nil {
					page.Date = time
					// Remove the date from the path
					base = base[len(layout):]
					if len(base) > 0 {
						// Remove a leading dash
						if base[0] == '-' {
							base = base[1:]
						}
						if len(base) > 0 {
							dir := pathpkg.Dir(path)
							if dir == "." {
								dir = ""
							}
							path = pathpkg.Join(dir, base)
						}
					}
				}
			}

			// Extract frontmatter from content
			frontmatter, content := extractFrontmatter(content)
			if len(frontmatter) != 0 {
				if err := yaml.Unmarshal(frontmatter, page); err != nil {
					log.Printf("failed to parse frontmatter for %q: %v", path, err)
				}

				// Trim leading newlines from content
				content = bytes.TrimLeft(content, "\r\n")
			}

			if cmd, ok := task.Preprocess[strings.TrimPrefix(ext, ".")]; ok {
				var buf bytes.Buffer
				if err := execute(cmd, bytes.NewReader(content), &buf); err != nil {
					return err
				}
				content = buf.Bytes()
			}
			page.Content = string(content)

			if !page.index {
				if namePrefix == "index" {
					path = "/" + strings.TrimSuffix(path, name)
				} else {
					path = "/" + strings.TrimSuffix(path, ext)
					if task.UglyURLs {
						path += task.OutputExt
					} else {
						path += "/"
					}
				}
				page.Permalink = path
				if permalink, ok := cfg.permalinks[p.Permalink]; ok {
					var b strings.Builder
					permalink.Execute(&b, page)
					page.Permalink = b.String()
				}
				p.Pages = append(p.Pages, page)
			}
		}
	}
	return nil
}

// process processes the directory's contents.
func (p *Page) process(cfg *Site, task *Task) error {
	// Build feeds before templates are applied to the page contents
	for _, feed := range task.feeds[p.FilePath] {
		b, err := p.buildFeed(cfg, feed)
		if err != nil {
			return err
		}
		p.addFeed(feed.Output, b)
	}

	if task.TemplateExt != "" {
		// Create index
		if p.index {
			tmpl, ok := cfg.templates.FindTemplate(p.Permalink, "index"+task.TemplateExt)
			if ok {
				var b strings.Builder
				if err := tmpl.Execute(&b, p); err != nil {
					return err
				}
				p.Content = b.String()
			}
		}

		// Process pages
		for i := range p.Pages {
			var b strings.Builder
			tmpl, ok := cfg.templates.FindTemplate(p.Permalink, "page"+task.TemplateExt)
			if ok {
				if err := tmpl.Execute(&b, p.Pages[i]); err != nil {
					return err
				}
				p.Pages[i].Content = b.String()
			}
		}
	}

	// Process subdirectories
	for _, d := range p.Dirs {
		if err := d.process(cfg, task); err != nil {
			return err
		}
	}
	return nil
}

// buildFeed build the feed of the directory
func (p *Page) buildFeed(cfg *Site, feed Feed) ([]byte, error) {
	// Feed represents a feed.
	type Feed struct {
		Title     string
		Permalink string
		Pages     []*Page
	}

	tmpl, ok := cfg.templates.FindTemplate(p.Permalink, feed.Template)
	if !ok {
		return nil, fmt.Errorf("failed to generate feed %q: missing feed template %q", feed.Title, feed.Template)
	}

	var b bytes.Buffer
	data := Feed{
		Title:     feed.Title,
		Permalink: p.Permalink,
		Pages:     p.Pages,
	}
	if err := tmpl.Execute(&b, data); err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}

func (p *Page) addFeed(name string, content []byte) {
	if p.feeds == nil {
		p.feeds = map[string][]byte{}
	}
	p.feeds[name] = content
}

// write writes the directory's contents to the provided destination path.
func (p *Page) write(dstDir string, task *Task) error {
	dirPath := pathpkg.Join(dstDir, p.Permalink)

	// Write pages
	for _, page := range p.Pages {
		dstPath := pathpkg.Join(dstDir, page.Permalink)
		if !task.UglyURLs {
			dstPath = pathpkg.Join(dstPath, "index"+task.OutputExt)
		}
		if err := page.writeTo(dstPath, task); err != nil {
			return err
		}
	}
	// Write index page
	if p.index {
		dstPath := pathpkg.Join(dstDir, p.Permalink, "index"+task.OutputExt)
		if err := p.writeTo(dstPath, task); err != nil {
			return err
		}
	}

	// Write feeds
	for name, content := range p.feeds {
		dstPath := pathpkg.Join(dstDir, name)
		os.MkdirAll(dirPath, 0755)
		if err := os.WriteFile(dstPath, content, 0644); err != nil {
			return err
		}
	}

	// Write subdirectories
	for _, dir := range p.Dirs {
		dir.write(dstDir, task)
	}
	return nil
}

func (p *Page) writeTo(dstPath string, task *Task) error {
	var content []byte
	if cmd := task.Postprocess; cmd != "" {
		var buf bytes.Buffer
		if err := execute(cmd, strings.NewReader(p.Content), &buf); err != nil {
			return err
		}
		content = buf.Bytes()
	} else {
		content = []byte(p.Content)
	}

	dir := pathpkg.Dir(dstPath)
	os.MkdirAll(dir, 0755)
	if err := os.WriteFile(dstPath, content, 0644); err != nil {
		return err
	}
	return nil
}

// sort sorts the directory's pages by weight, then date, then filepath.
func (p *Page) sort() {
	sortPages(p.Pages)
	sortPages(p.Dirs)

	// Sort subdirectories
	for _, d := range p.Dirs {
		d.sort()
	}
}

func sortPages(pages []*Page) {
	sort.Slice(pages, func(i, j int) bool {
		pi, pj := pages[i], pages[j]
		return pi.FilePath < pj.FilePath
	})

	sort.SliceStable(pages, func(i, j int) bool {
		pi, pj := pages[i], pages[j]
		return pi.Date.After(pj.Date)
	})

	sort.SliceStable(pages, func(i, j int) bool {
		pi, pj := pages[i], pages[j]
		return pi.Weight < pj.Weight
	})

	for i := range pages {
		if i-1 >= 0 {
			pages[i].Prev = pages[i-1]
		}
		if i+1 < len(pages) {
			pages[i].Next = pages[i+1]
		}
	}
}

// execute runs a command.
func execute(command string, input io.Reader, output io.Writer) error {
	split := strings.Split(command, " ")
	cmd := exec.Command(split[0], split[1:]...)
	cmd.Stdin = input
	cmd.Stderr = os.Stderr
	cmd.Stdout = output
	err := cmd.Run()
	if err != nil {
		return err
	}
	return nil
}

func (p *Page) getPage(path string) *Page {
	// XXX: This is inefficient
	if p.Permalink == path {
		return p
	}
	for _, page := range p.Pages {
		if page.FilePath == path {
			return page
		}
	}
	for _, dir := range p.Dirs {
		if dir.Permalink == path {
			return dir
		}
	}
	for _, dir := range p.Dirs {
		if page := dir.getPage(path); page != nil {
			return page
		}
	}
	return nil
}