/
build.go
336 lines (293 loc) · 8.12 KB
/
build.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
package build
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/adrg/frontmatter"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/cbroglie/mustache"
"github.com/vssio/go-vss/internal/config"
"github.com/yuin/goldmark"
highlighting "github.com/yuin/goldmark-highlighting/v2"
"github.com/yuin/goldmark/extension"
)
// Builder is a struct for building a static site.
type Builder struct {
config *config.Config
// init in Run()
templateMap map[string]*mustache.Template
gm goldmark.Markdown
buf bytes.Buffer
baseRenderContext map[string]interface{}
}
// NewBuilder returns a new Builder.
func NewBuilder(config *config.Config) *Builder {
return &Builder{
config: config,
}
}
// GetDistPath returns the dist directory path.
func (b Builder) GetDistPath() string {
return b.config.Dist
}
// ReloadConfig reloads the config file.
func (b *Builder) ReloadConfig() error {
c, err := config.LoadConfig()
if err != nil {
return err
}
b.config = c
return nil
}
func (b *Builder) Run() error {
if err := createDistDir(b.config.Dist); err != nil {
return err
}
log.Printf("[INFO] copying static files from %s to %s\n", b.config.Static, b.config.Dist)
if err := copyStatic(b.config.Static, b.config.Dist); err != nil {
return err
}
markdownFiles, err := getFilePathsByExt(".", ".md")
if err != nil {
return err
}
log.Printf("[INFO] found %d markdown files\n", len(markdownFiles))
templateFiles, err := getFilePathsByExt(b.config.Layouts, ".html")
if err != nil {
return err
}
if err := b.initTemplateMap(templateFiles); err != nil {
return err
}
log.Printf("[INFO] rendering markdown files\n")
b.gm = b.initGoldmark()
// for storing rendered html
b.baseRenderContext = b.config.AsMap()
for _, markdownPath := range markdownFiles {
log.Printf("[INFO] rendering %s\n", markdownPath)
if err := b.renderContent(markdownPath); err != nil {
return err
}
}
return nil
}
// renderContent renders the markdown file and writes the result to the dist directory.
func (b *Builder) renderContent(markdownPath string) error {
htmlPath := convertMarkdownPathToHtmlPath(markdownPath)
distFile, err := createDistFile(filepath.Join(b.config.Dist, htmlPath))
if err != nil {
return err
}
defer distFile.Close()
template, err := b.lookUpTemplate(htmlPath)
if err != nil {
return err
}
renderContext, err := b.getRenderContext(markdownPath)
if err != nil {
return err
}
return template.FRender(distFile, renderContext)
}
// getRenderContext returns a map[string]interface{} that contains the content of the markdown file.
func (b *Builder) getRenderContext(markdownPath string) (map[string]interface{}, error) {
defer b.buf.Reset()
content, err := os.ReadFile(markdownPath)
if err != nil {
return nil, err
}
// TODO: matter を利用してビルドできるようにする
var matter YamlFrontMatter
markdown, err := frontmatter.Parse(strings.NewReader(string(content)), &matter)
if err != nil {
return nil, err
}
if err := b.gm.Convert(markdown, &b.buf); err != nil {
return nil, err
}
renderContext := b.baseRenderContext
renderContext["contents"] = b.buf.String()
// content と markdown が同じであればここで return する
if bytes.Equal(content, markdown) {
return renderContext, nil
}
// matter のフィールドを renderContext に追加
// すでに存在する場合は上書き
for k, v := range matter.AsMap() {
renderContext[k] = v
}
return renderContext, nil
}
func (b *Builder) initTemplateMap(templateFiles []string) error {
m := make(map[string]*mustache.Template, len(templateFiles))
for _, templateFile := range templateFiles {
t, err := mustache.ParseFile(templateFile)
if err != nil {
return err
}
m[templateFile] = t
}
b.templateMap = m
return nil
}
// lookUpTemplate returns the path (file path) of the template path.
func (b *Builder) lookUpTemplate(path string) (*mustache.Template, error) {
dir := filepath.Dir(path)
layoutsDir := b.config.Layouts
t, ok := b.templateMap[filepath.Join(layoutsDir, path)]
if ok {
return t, nil
}
t, ok = b.templateMap[filepath.Join(layoutsDir, dir, "default.html")]
if ok {
return t, nil
}
t, ok = b.templateMap[filepath.Join(layoutsDir, "default.html")]
if ok {
return t, nil
}
return nil, errors.New("template not found")
}
func replaceExt(filePath, from, to string) string {
ext := filepath.Ext(filePath)
if len(from) > 0 && strings.ToLower(ext) != from {
return filePath
}
return filePath[:len(filePath)-len(ext)] + to
}
func convertMarkdownPathToHtmlPath(markdownPath string) string {
// TODO: support `markdown` extension ?
return replaceExt(markdownPath, ".md", ".html")
}
// copyStatic copy all files in the static directory (src) to the dist directory.
func copyStatic(src, dist string) error {
if existDir(src) {
// Create destination directory if it does not exist
if err := os.MkdirAll(dist, os.ModePerm); err != nil {
return err
}
// Get all files in the source directory
files, err := os.ReadDir(src)
if err != nil {
return err
}
// Copy each file to the destination directory
for _, file := range files {
srcFile := filepath.Join(src, file.Name())
distFile := filepath.Join(dist, file.Name())
if file.IsDir() {
// Recursively copy subdirectories
if err := copyStatic(srcFile, distFile); err != nil {
return err
}
} else {
// Copy file contents
if err := copyFile(srcFile, distFile); err != nil {
return err
}
}
}
} else {
log.Printf("[INFO] static directory not found. skip copying static files.")
}
return nil
}
// copyFile copies a file from src to dst.
func copyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return err
}
return nil
}
// existDir checks if a directory exists.
func existDir(dir string) bool {
info, err := os.Stat(dir)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
func createDistDir(dist string) error {
// TODO: cache dist directory
if existDir(dist) {
log.Printf("[INFO] re creating dist directory: %s", dist)
if err := os.RemoveAll(dist); err != nil {
return err
}
if err := os.Mkdir(dist, os.ModePerm); err != nil {
return err
}
} else {
log.Printf("[INFO] creating dist directory: %s", dist)
if err := os.Mkdir(dist, os.ModePerm); err != nil {
return err
}
}
return nil
}
func getFilePathsByExt(dirPath, ext string) ([]string, error) {
var filePaths []string
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ext) {
filePaths = append(filePaths, path)
}
return nil
})
if err != nil {
return nil, err
}
return filePaths, nil
}
func (b *Builder) initGoldmark() goldmark.Markdown {
// TODO: highlight は option にする(例: 他の syntax highlighter を使いたい場合のため)
extensions := []goldmark.Extender{
// default extensions
extension.GFM,
}
highlightoptions := []highlighting.Option{}
if b.config.Build.Goldmark.HighlightConfig != nil {
if b.config.Build.Goldmark.HighlightConfig.Style != nil {
highlightoptions = append(highlightoptions, highlighting.WithStyle(*b.config.Build.Goldmark.HighlightConfig.Style))
}
// TODO: キーがない場合は highlight しないようにする
if b.config.Build.Goldmark.HighlightConfig.WithNumbers != nil {
highlightoptions = append(
highlightoptions,
highlighting.WithFormatOptions(chromahtml.WithLineNumbers(*b.config.Build.Goldmark.HighlightConfig.WithNumbers)),
)
}
}
if len(highlightoptions) > 0 {
fmt.Println("highlightoptions")
extensions = append(extensions, highlighting.NewHighlighting(highlightoptions...))
}
return goldmark.New(
goldmark.WithExtensions(extensions...),
)
}
func createDistFile(dist string) (*os.File, error) {
dir := filepath.Dir(dist)
if !existDir(dir) {
os.MkdirAll(dir, os.ModePerm)
}
return os.Create(dist)
}