summaryrefslogtreecommitdiffstats
path: root/internal/cms/build.go
blob: c43461113f411b4966f2e4d3915028913b812e5b (plain) (blame)
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
package cms

import (
	"fmt"
	"io"
	"io/fs"
	"os"
	"path"
	"path/filepath"
	"sort"
	"strings"
)

func Build(root string) (BuildReport, error) {
	project, err := LoadProject(root)
	if err != nil {
		return BuildReport{}, err
	}
	outDir := filepath.Join(root, "public")
	if err := os.RemoveAll(outDir); err != nil {
		return BuildReport{}, err
	}
	if err := os.MkdirAll(outDir, 0o755); err != nil {
		return BuildReport{}, err
	}

	report := BuildReport{OutputDir: outDir}
	if err := copyAssets(filepath.Join(root, "assets"), outDir, &report); err != nil {
		return BuildReport{}, err
	}

	hasIndex := false
	for _, doc := range project.Docs {
		if doc.Draft {
			continue
		}
		if doc.Type == "page" && doc.Slug == "index" {
			hasIndex = true
		}
		rel := outputRel(doc)
		rendered := renderDocument(project, doc)
		if err := writeFile(filepath.Join(outDir, filepath.FromSlash(rel)), []byte(rendered)); err != nil {
			return BuildReport{}, err
		}
		report.FilesWritten++
	}
	if !hasIndex {
		rendered := renderGeneratedIndex(project)
		if err := writeFile(filepath.Join(outDir, "index.gmi"), []byte(rendered)); err != nil {
			return BuildReport{}, err
		}
		report.FilesWritten++
	}
	for section, docs := range articlesBySection(project.Docs) {
		rendered := renderSectionIndex(project, section, docs)
		if err := writeFile(filepath.Join(outDir, section, "index.gmi"), []byte(rendered)); err != nil {
			return BuildReport{}, err
		}
		report.FilesWritten++
	}

	return report, nil
}

func renderDocument(project Project, doc Document) string {
	body := expandBlocks(project, doc.Body)
	return strings.TrimRight(body, "\n") + "\n"
}

func renderGeneratedIndex(project Project) string {
	var b strings.Builder
	b.WriteString("# " + project.Config.Title + "\n\n")
	b.WriteString(renderMenu(project.Menus["top"]))
	b.WriteString("\n## Latest articles\n\n")
	b.WriteString(renderWidget(project, Widget{Name: "recent-articles", Type: "recent", Section: "articles", Limit: 5}))
	return strings.TrimRight(b.String(), "\n") + "\n"
}

func renderSectionIndex(project Project, section string, docs []Document) string {
	title := titleize(section)
	if cfg, ok := project.Sections[section]; ok {
		title = cfg.Title
	}
	var b strings.Builder
	b.WriteString("# " + title + "\n\n")
	if menu, ok := project.Menus["top"]; ok {
		b.WriteString(renderMenu(menu))
		b.WriteString("\n")
	}
	for _, doc := range docs {
		b.WriteString("=> " + docURL(doc) + " " + doc.Date + " " + doc.Title + "\n")
	}
	return strings.TrimRight(b.String(), "\n") + "\n"
}

func expandBlocks(project Project, body string) string {
	var out []string
	for _, line := range strings.Split(body, "\n") {
		name, arg, ok := parseBlock(line)
		if !ok {
			out = append(out, line)
			continue
		}
		switch name {
		case "menu":
			out = append(out, strings.TrimRight(renderMenu(project.Menus[arg]), "\n"))
		case "widget":
			widget, ok := project.Widgets[arg]
			if !ok {
				out = append(out, "Missing widget: "+arg)
				continue
			}
			out = append(out, strings.TrimRight(renderWidget(project, widget), "\n"))
		default:
			out = append(out, line)
		}
	}
	return strings.Join(out, "\n")
}

func parseBlock(line string) (string, string, bool) {
	line = strings.TrimSpace(line)
	if !strings.HasPrefix(line, "{{") || !strings.HasSuffix(line, "}}") {
		return "", "", false
	}
	line = strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(line, "{{"), "}}"))
	parts := strings.Fields(line)
	if len(parts) != 2 {
		return "", "", false
	}
	return parts[0], parts[1], true
}

func renderMenu(menu Menu) string {
	if len(menu.Items) == 0 {
		return ""
	}
	var b strings.Builder
	for _, item := range menu.Items {
		b.WriteString("=> " + item.URL + " " + item.Label + "\n")
	}
	return b.String()
}

func renderWidget(project Project, widget Widget) string {
	switch widget.Type {
	case "recent":
		return renderRecentWidget(project, widget)
	default:
		return "Unsupported widget: " + widget.Type + "\n"
	}
}

func renderRecentWidget(project Project, widget Widget) string {
	var docs []Document
	for _, doc := range project.Docs {
		if doc.Type == "article" && !doc.Draft && doc.Section == widget.Section {
			docs = append(docs, doc)
		}
	}
	sortArticles(docs)
	if widget.Limit > 0 && len(docs) > widget.Limit {
		docs = docs[:widget.Limit]
	}
	if len(docs) == 0 {
		return "No articles yet.\n"
	}
	var b strings.Builder
	for _, doc := range docs {
		b.WriteString("=> " + docURL(doc) + " " + doc.Date + " " + doc.Title + "\n")
	}
	return b.String()
}

func articlesBySection(docs []Document) map[string][]Document {
	sections := map[string][]Document{}
	for _, doc := range docs {
		if doc.Type != "article" || doc.Draft {
			continue
		}
		sections[doc.Section] = append(sections[doc.Section], doc)
	}
	for section := range sections {
		sortArticles(sections[section])
	}
	return sections
}

func sortArticles(docs []Document) {
	sort.Slice(docs, func(i, j int) bool {
		if docs[i].Date != docs[j].Date {
			return docs[i].Date > docs[j].Date
		}
		return docs[i].Slug < docs[j].Slug
	})
}

func outputRel(doc Document) string {
	if doc.Type == "page" {
		if doc.Slug == "index" || doc.Slug == "" {
			return "index.gmi"
		}
		return doc.Slug + ".gmi"
	}
	section := doc.Section
	if section == "" {
		section = "articles"
	}
	return path.Join(section, doc.Slug+".gmi")
}

func docURL(doc Document) string {
	rel := outputRel(doc)
	if rel == "index.gmi" {
		return "/"
	}
	return "/" + rel
}

func copyAssets(src, outDir string, report *BuildReport) error {
	if _, err := os.Stat(src); err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return err
	}
	return filepath.WalkDir(src, func(pathName string, entry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() {
			return nil
		}
		rel, err := filepath.Rel(src, pathName)
		if err != nil {
			return err
		}
		dest := filepath.Join(outDir, filepath.FromSlash(filepath.ToSlash(rel)))
		if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
			return err
		}
		if err := copyFile(pathName, dest); err != nil {
			return err
		}
		report.FilesWritten++
		return nil
	})
}

func copyFile(src, dest string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()

	out, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer out.Close()

	if _, err := io.Copy(out, in); err != nil {
		return err
	}
	if err := out.Close(); err != nil {
		return err
	}
	return nil
}

func debugProject(project Project) string {
	return fmt.Sprintf("%d docs, %d menus, %d widgets", len(project.Docs), len(project.Menus), len(project.Widgets))
}