This repository has been archived by the owner on Apr 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.go
505 lines (461 loc) · 14.3 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
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
package ortfomk
import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
exprVM "github.com/antonmedv/expr/vm"
"github.com/stoewer/go-strcase"
"gopkg.in/yaml.v3"
v8 "rogchap.com/v8go"
)
var g *GlobalData = &GlobalData{}
var DynamicPathExpressionsCache = map[string]*exprVM.Program{}
type Translations map[string]*TranslationsOneLang
// GlobalData holds data that is used throughout the whole build process
type GlobalData struct {
mu sync.Mutex
Translations Translations
Database
// Maps each link to the pages in which they appear
HTTPLinks map[string][]string
Spinner Spinner
CurrentObjectID string
CurrentOutputFile string
CurrentLanguage string
Progress struct {
Step BuildStep
Resolution int
File string
Current int
Total int
}
Flags Flags
Configuration Configuration
OutputDirectory string
TemplatesDirectory string
AdditionalData map[string]interface{}
}
type Flags struct {
ProgressFile string
Silent bool
}
// WarmUp needs to be run before any building starts.
// It sets the global data, scans the template directory
// to determine the total number of pages to build, and starts the spinner.
func WarmUp(data *GlobalData) {
g = data
g.Spinner = CreateSpinner()
g.Spinner.Start()
}
// CoolDown needs to be stop before the program exits.
// It properly stops the spinner.
func CoolDown() {
LogDebug("cooling down")
g.Spinner.Stop()
// make the cursor again, since spinner.Stop() doesn't seem to take care of it.
fmt.Printf("\033[?25h")
}
func SetGlobalData(data *GlobalData) {
g = data
}
func SetTranslationsOnGlobalData(translations map[string]*TranslationsOneLang) {
g.Translations = translations
}
func SetDatabaseOnGlobalData(database Database) {
g.Database = database
}
func LoadAdditionalData(filesToLoad []string) (additionalData map[string]interface{}, err error) {
additionalData = make(map[string]interface{})
for _, file := range filesToLoad {
var loaded interface{}
content, err := ioutil.ReadFile(file)
if err != nil {
return additionalData, fmt.Errorf("while reading %s: %w", file, err)
}
err = yaml.Unmarshal([]byte(content), &loaded)
if err != nil {
return additionalData, fmt.Errorf("while parsing %s: %w", file, err)
}
if loaded == nil {
LogWarning("Loaded data from %s is null", file)
}
additionalData[strcase.LowerCamelCase(filepathStem(file))] = loaded
}
return additionalData, nil
}
func ComputeTotalToBuildCount() {
g.mu.Lock()
g.Progress.Total = ToBuildTotalCount(g.TemplatesDirectory)
g.mu.Unlock()
}
func ToBuildTotalCount(in string) (count int) {
err := filepath.WalkDir(in, func(path string, entry fs.DirEntry, err error) error {
currentDirectory := filepath.Dir(path)
if strings.Contains(path, "/mixins/") {
return nil
}
if !(strings.HasSuffix(path, ".pug") || strings.HasSuffix(path, ".html")) {
return nil
}
if err != nil {
return err
}
ortfoignore, err := closestOrtfoignore(currentDirectory)
if err != nil {
return err
}
if ortfoignore != nil && ortfoignore.Ignore(path) {
LogDebug("ignoring %s because of ortfoignore at %s", path, filepath.Join(ortfoignore.Base(), ".ortfoignore"))
return nil
}
LogDebug("walking into %s", path)
// Collect variables the path depends upon
pathVariables := make([]string, 0)
for _, expr := range DynamicPathExpressions(path) {
variables, err := VariablesOfExpression(expr)
if err != nil {
return fmt.Errorf("couldn't extract variables of expression %q: %w", expr, err)
}
pathVariables = append(pathVariables, variables...)
}
pathVariables = deduplicate(pathVariables)
if len(excluding(pathVariables, "language")) > 0 {
for _, variable := range pathVariables {
switch variable {
case "work":
for _, lang := range []string{"fr", "en"} {
for _, work := range g.Works {
if distPath, err := (&Hydration{language: lang, work: work}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
case "tag":
for _, lang := range []string{"fr", "en"} {
for _, tag := range g.Tags {
if distPath, err := (&Hydration{language: lang, tag: tag}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
case "technology":
for _, lang := range []string{"fr", "en"} {
for _, tech := range g.Technologies {
if distPath, err := (&Hydration{language: lang, tech: tech}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
case "site":
for _, lang := range []string{"fr", "en"} {
for _, site := range g.Sites {
if distPath, err := (&Hydration{language: lang, site: site}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
case "collection":
for _, lang := range []string{"fr", "en"} {
for _, collection := range g.Collections {
if distPath, err := (&Hydration{language: lang, collection: collection}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
}
}
} else {
for _, lang := range []string{"fr", "en"} {
if distPath, err := (&Hydration{language: lang}).GetDistFilepath(path); distPath != "" && err == nil {
count += 1
}
}
}
LogDebug("count is now %d", count)
return nil
})
if err != nil {
LogError("couldn't count the total number of pages to build: %s", err)
}
return
}
// BuildAll builds pages from templates found in the given directory in parallel, using the given number of goroutines (workersCount).
// if workersCount is 0 or less, it is set to the number of page templates to compile.
func BuildAll(in string, workersCount int) (built []string, httpLinks map[string][]string, err error) {
toBuildChannel := make(chan string)
httpLinks = g.HTTPLinks
LogDebug("scanning for things to build")
toBuild, err := ScanAll(in)
if err != nil {
return built, httpLinks, fmt.Errorf("while scanning templates directory: %w", err)
}
if workersCount <= 0 {
workersCount = len(toBuild)
}
var builtMutex sync.Mutex
var wg sync.WaitGroup
wg.Add(workersCount)
LogDebug("launching 5 parallel build subroutines")
for i := 0; i < workersCount; i++ {
go func(toBuildChannel chan string) {
for {
newlyBuilt := make([]string, 0)
path, more := <-toBuildChannel
if !more {
wg.Done()
return
}
// Collect variables the path depends upon
pathVariables := make([]string, 0)
for _, expr := range DynamicPathExpressions(path) {
variables, err := VariablesOfExpression(expr)
if err != nil {
LogError("couldn't extract variables of expression %q: %s", expr, err)
return
}
pathVariables = append(pathVariables, variables...)
}
pathVariables = deduplicate(pathVariables)
if len(excluding(pathVariables, "language")) > 0 {
for _, variable := range pathVariables {
switch variable {
case "work":
newlyBuilt = append(newlyBuilt, BuildWorkPages(path)...)
case "tag":
newlyBuilt = append(newlyBuilt, BuildTagPages(path)...)
case "technology":
newlyBuilt = append(newlyBuilt, BuildTechPages(path)...)
case "site":
newlyBuilt = append(newlyBuilt, BuildSitePages(path)...)
case "collection":
newlyBuilt = append(newlyBuilt, BuildCollectionPages(path)...)
}
}
} else {
newlyBuilt = append(newlyBuilt, BuildRegularPage(path)...)
}
builtMutex.Lock()
built = append(built, newlyBuilt...)
builtMutex.Unlock()
}
}(toBuildChannel)
}
LogDebug("starting to fill toBuild channel")
for _, path := range toBuild {
toBuildChannel <- path
}
close(toBuildChannel)
wg.Wait()
return
}
// ScanAll scans the given directory for paths to build, recursively.
func ScanAll(in string) (toBuild []string, err error) {
err = filepath.WalkDir(in, func(path string, entry fs.DirEntry, err error) error {
// LogDebug("Walking into %s", path)
currentDirectory := filepath.Dir(path)
if strings.Contains(path, "/mixins/") {
return nil
}
if !(strings.HasSuffix(path, ".pug") || strings.HasSuffix(path, ".html")) {
return nil
}
if err != nil {
return err
}
ortfoignore, err := closestOrtfoignore(currentDirectory)
if err != nil {
return err
}
if ortfoignore != nil && ortfoignore.Ignore(path) {
LogDebug("ignoring %s because of ortfoignore at %s", path, filepath.Join(ortfoignore.Base(), ".ortfoignore"))
return nil
}
toBuild = append(toBuild, path)
return err
})
return
}
// BuildTechPages builds all technology pages using `using`
func BuildTechPages(using string) (built []string) {
templateContent, err := os.ReadFile(using)
if err != nil {
LogError("couldn't read the template: %s", err)
return
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(using, templateContent)
if err != nil {
LogError("could build technology pages’ template: %s", err)
return
}
for _, tech := range g.Technologies {
SetCurrentObjectID(tech.URLName)
built = append(built, BuildPage(javascriptRuntime, using, compiledTemplate, &Hydration{tech: tech})...)
SetCurrentObjectID("")
}
javascriptRuntime.Dispose()
return
}
// BuildSitePages builds all site pages using the template at the given filename
func BuildSitePages(using string) (built []string) {
templateContent, err := os.ReadFile(using)
if err != nil {
LogError("couldn't read the template: %s", err)
return
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(using, templateContent)
if err != nil {
LogError("could build site pages’ template: %s", err)
return
}
for _, site := range g.Sites {
SetCurrentObjectID(site.Name)
built = append(built, BuildPage(javascriptRuntime, using, compiledTemplate, &Hydration{site: site})...)
SetCurrentObjectID("")
}
javascriptRuntime.Dispose()
return
}
// BuildTagPages builds all tag pages using the given filename
func BuildTagPages(using string) (built []string) {
templateContent, err := os.ReadFile(using)
if err != nil {
LogError("couldn't read the template: %s", err)
return
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(using, templateContent)
if err != nil {
LogError("could build tag pages’ template: %s", err)
return
}
for _, tag := range g.Tags {
SetCurrentObjectID(tag.Singular)
built = append(built, BuildPage(javascriptRuntime, using, compiledTemplate, &Hydration{tag: tag})...)
SetCurrentObjectID("")
}
javascriptRuntime.Dispose()
return
}
// BuildCollectionPages builds all collection pages using the given filename
func BuildCollectionPages(using string) (built []string) {
templateContent, err := os.ReadFile(using)
if err != nil {
LogError("couldn't read the template: %s", err)
return
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(using, templateContent)
if err != nil {
LogError("could build tag pages’ template: %s", err)
return
}
for _, collection := range g.Collections {
SetCurrentObjectID(collection.ID)
built = append(built, BuildPage(javascriptRuntime, using, compiledTemplate, &Hydration{collection: collection})...)
SetCurrentObjectID("")
}
javascriptRuntime.Dispose()
return
}
// BuildWorkPages builds all work pages using the given filepath
func BuildWorkPages(using string) (built []string) {
templateContent, err := os.ReadFile(using)
if err != nil {
LogError("coudln't read template: %s", err)
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(using, templateContent)
if err != nil {
LogError("couldn't build work pages’ template: %s", err)
return
}
for _, work := range g.Works {
SetCurrentObjectID(work.ID)
built = append(built, BuildPage(javascriptRuntime, using, compiledTemplate, &Hydration{work: work})...)
SetCurrentObjectID("")
}
javascriptRuntime.Dispose()
return
}
// BuildRegularPage builds a given page that isn't dynamic (i.e. does not require object data,
// as opposed to work, tag and tech pages)
func BuildRegularPage(path string) (built []string) {
SetCurrentObjectID(strings.TrimSuffix(filepath.Base(g.Progress.File), filepath.Ext(g.Progress.File)))
templateContent, err := os.ReadFile(path)
if err != nil {
LogError("couldn't read the template: %s", err)
return
}
javascriptRuntime := v8.NewIsolate()
compiledTemplate, err := CompileTemplate(path, templateContent)
if err != nil {
LogError("could not build the page’s template: %s", err)
return
}
LogDebug("finished compiling")
built = BuildPage(javascriptRuntime, path, compiledTemplate, &Hydration{})
javascriptRuntime.Dispose()
return built
}
// BuildPage builds a single page
func BuildPage(javascriptRuntime *v8.Isolate, pageName string, compiledTemplate []byte, hydration *Hydration) (built []string) {
// Add additional data to hydration
for _, language := range []string{"fr", "en"} {
hydration.language = language
outPath, err := hydration.GetDistFilepath(pageName)
if err != nil {
LogError("Invalid path: %s", err)
continue
}
if outPath == "" {
// LogDebug("Skipped path %s", pageName)
continue
}
Status(StepBuildPage, ProgressDetails{
File: pageName,
Language: language,
OutFile: outPath,
})
content, err := RunTemplate(
javascriptRuntime,
hydration,
pageName,
compiledTemplate,
)
if err != nil {
// PrintTemplateErrorMessage("executing template", NameOfTemplate(pageName, *hydration), string(compiledTemplate), err, "js")
LogError("couldn't execute template %s with %s: %s", pageName, hydration.Name(), err)
continue
}
content = g.Translations[language].TranslateHydrated(content)
g.mu.Lock()
for _, link_ := range AllLinks(content).ToSlice() {
link := link_.(string)
if _, exists := g.HTTPLinks[link]; exists {
g.HTTPLinks[link] = append(g.HTTPLinks[link], outPath)
}
g.HTTPLinks[link] = []string{outPath}
}
g.mu.Unlock()
os.MkdirAll(filepath.Dir(outPath), 0777)
LogDebug("outputting to %s", outPath)
if strings.HasSuffix(outPath, ".pdf") {
WritePDF(content, outPath)
ioutil.WriteFile(strings.TrimSuffix(outPath, ".pdf")+".html", []byte(content), 0777)
} else {
ioutil.WriteFile(outPath, []byte(content), 0777)
}
built = append(built, outPath)
progressWriteErr := IncrementProgress()
if progressWriteErr != nil {
LogError("couldn't write progress to file: %s", progressWriteErr)
}
}
return
}