-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild.js
executable file
·481 lines (393 loc) · 12 KB
/
build.js
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
#!/usr/bin/env node
"use strict"
/* Remakable - the compile script for ddr0.ca!
Largely reimplements grunt/gulp/whatever, but
poorly. Learning! \o/
*/
const fs = require('fs').promises
const {watch} = require('fs')
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const {exit, stdout} = require('process')
const MAX_SUBPROCESS_RUN_TIME_MS = 2000
const REPEAT_BUILD_DEBOUNCE_MS = 10
const HELP_MESSAGE = `build.js: Compile ddr0.ca.
Options:
--dot: Don't build, but output a graph of what would be built on stdout.
Useful with imagemagick as ./build.js -dot | dot -Tsvg | display
--full-rebuild: Force recompile everything.
--help: Show this message and exit.
--print-events: Debug file events detected by --watch.
--show-task[s][=task-name]: Print information and status of build steps.
--watch: Watch for task changes. (Will [1mnot[0m reload the build script.)
`
const dump = (...args) => (console.info(...args), args.at(-1))
const scanTree = async path => {
const names = await fs.readdir(path)
const directoryContents = (await Promise.all(
names.map(name => fs.lstat(`${path}/${name}`, {bigint:true})))
).map((entry, i) => (entry.name=names[i], entry))
//Filter out hidden and non-normal files, we don't want to watch .git or a fifo or anything.
const filesAndFolders = directoryContents.filter(entry =>
(!entry.name.startsWith('.'))
&& (entry.isDirectory() || entry.isFile())
)
const subfolders = (
await Promise.all(filesAndFolders
.filter(entry => entry.isDirectory())
.map(entry => scanTree(`${path}/${entry.name}`))
)
).flat()
const files = filesAndFolders
.filter(entry => entry.isFile())
.map(entry => ({
name: `${path}/${entry.name}`,
date: entry.mtimeMs,
//toString: ()=>`${entry.name}@${entry.mtimeMs}`,
}))
return [...subfolders, ...files]
}
const findTasks = allFiles => {
const filter = pattern =>
allFiles.filter(
pattern instanceof RegExp
? (file => pattern.test(file.name))
: (file => pattern === file.name)
)
const replace = (files, target, replacement) =>
files.map(file =>
file.name.replace(target, replacement)
).map(path =>
allFiles.find(file => file.name === path) || {
name: path,
date: 0,
}
)
const tasks = []
const addTask = task => {
if(task.input.length < 1) throw new Error('Task missing input file.')
if(task.output.length < 1) throw new Error('Task missing output file.')
if(!task.command instanceof Function) throw new Error('Task missing run command.')
if(!task.name) throw new Error('Task missing name.')
for (let file of task.input) {
if(task.output.includes(file)) throw new Error(`Task input in output. ("${file.name}" found in both.)`)
}
tasks.push(task)
}
let input, output, deps
//Main HTML Files
deps = [
...filter(/^\.\/[^/]*?\.html\.frag$/),
...filter(/^\.\/[^/]*?\.html\.frag\.js$/),
...filter(/^\.\/compile-template.node.js$/),
...filter(/^\.\/render-file.node.js$/),
]
for(input of filter(/^\.\/[^/]*?\.html\.js$/)) {
output = replace([input], 'html.js', 'html')
//Blog is assembled from more parts.
const blogPosts = input.name === './blog.html.js'
? filter(/^\.\/blog-posts\/[^/]*?\.html\.frag(?:\.js)?$/)
: []
addTask({
name: 'main html',
input: [input, deps, blogPosts].flat(),
output,
command: `./compile-template.node.js "${input.name}" > "${output[0].name}"`,
})
}
//Blog HTML Files
deps = [
...filter(/^\.\/compile-blog\.node\.js$/),
...filter(/^\.\/blog-posts\/single-post\.html\.template\.js$/),
...filter(/^\.\/blog-posts\/tags\.html\.template\.js$/),
...filter(/^\.\/site shell intro\.html\.frag\.js$/),
...filter(/^\.\/site shell outro\.html\.frag$/),
]
input = [
...filter(/^\.\/blog-posts\/[^/]*?\.html\.frag(?:\.js)?$/),
...filter(/^\.\/blog-rss-feed\.xml\.js$/),
]
output = replace(input, /\.html\.frag(?:\.js)?$/, '.html')
output = replace(output, /\.xml\.js$/, '.xml')
input && addTask({
name: 'blog html',
input: [...input, ...deps],
output,
command: `./compile-blog.node.js`,
})
//Gallery RSS XML File (Blog RSS is compiled separately.)
deps = [
...filter(/^\.\/compile-template\.node\.js$/),
...filter(/^\.\/render-file\.node\.js$/),
]
for(input of filter(/^\.\/gallery-rss-feed\.xml\.js$/)) {
output = replace([input], '.xml.js', '.xml')
addTask({
name: 'rss xml',
input: [input].concat(deps),
output,
command: `./compile-template.node.js "${input.name}" > "${output[0].name}"`,
})
}
//Background Town's Coffeescript is no longer being maintained. It was an experiment. The outcome was that CoffeeScript has a rather error-prone syntax, and therefore isn't worth the added complexity.
//LESS CSS
for(input of filter(/^\.\/css\/.*?\.less$/)) {
output = replace([input], '.less', '.css')
addTask({
name: 'css',
input: [input].concat(deps),
output,
command: `node_modules/less/bin/lessc --source-map --math=strict "${input.name}" "${output[0].name}"`,
})
}
return tasks
}
const calculateRequirements = tasks => {
//link all tasks with pre/post-requisite tasks.
//TODO: TEST THIS!
for (const task of tasks) {
task.prereqs = [];
task.postreqs = [];
}
for (const task of tasks) {
task.prereqs = task.prereqs.concat(...
task.input.map(input =>
tasks.filter(prereq =>
prereq.output.find(output =>
input.name == output.name ) ) ) )
for (const prereq of task.prereqs) {
prereq.postreqs.push(task)
}
}
}
const markOutOfDate = tasks => {
//mark all out-of-date rules and anything which requires them as dirty
for (const task of tasks) {
task.dirty = false;
}
const markOutOfDate = task => {
if (task.dirty) { return }
task.dirty = true
task.postreqs.forEach(markOutOfDate)
}
for (const task of tasks) {
if (
task.output.find(output =>
task.input.find(input =>
output.date < input.date ) )
) {
markOutOfDate(task)
}
}
}
const markTasksDirty = tasks => {
for (const task of tasks) {
task.dirty = true
task.postreqs.forEach(markOutOfDate)
}
}
const refreshTimestamps = async tasks =>
Promise.all(...
tasks.map(task =>
task.input.map(async file =>
file.date = (await fs.lstat(file.name, {bigint:true})).mtimeMs
)
)
)
const markFileDirty = (tasks, updatedName) => {
for (const task of tasks) {
if (task.input.find(file => file.name == updatedName)) {
task.dirty = true
}
}
}
//Run tasks with up-to-date prerequisites.
const prereqIsDirty = task => //Returns true if prereq — or any of it's prereqs — are dirty.
task.dirty || task.prereqs.find(prereqIsDirty)
const isRunnable = task => //Returns true if task is dirty and prerequisite tasks are clean.
task.dirty && !task.prereqs.find(prereqIsDirty)
const runTask = async task => {
try {
const { stdout, stderr } = await exec(task.command, {timeout: MAX_SUBPROCESS_RUN_TIME_MS})
console.log(`\x1b[32m> ${task.command}\x1b[39m`)
stdout && console.log(stdout);
stderr && console.error(stderr);
task.dirty = false
return await task.postreqs.filter(isRunnable).map(runTask)
} catch (err) {
const { stdout, stderr } = err
console.log(`\x1b[31m> ${task.command}\x1b[39m`)
stdout && console.log(stdout);
stderr && console.error(stderr);
throw err
}
}
const runAllTasks = async tasks => {
let failed = 0
let ran = 0
for (const run of tasks.filter(isRunnable).map(runTask)) {
try {
ran++
await run
} catch (err) {
failed++
}
}
if (failed) {
console.log(`\x1b[31m${failed}/${ran} ${ran>1?'tasks':'task'} failed. Build incomplete.\x1b[39m`)
} else if (!ran) {
console.log(`\x1b[32mNothing to do. Build complete.\x1b[39m`)
} else {
console.log(`\x1b[32m${ran} ${ran>1?'tasks':'task'} ran. Build complete.\x1b[39m`)
}
return !failed
}
(async ()=>{
if (process.argv.find(a => a.match(/^-?-?help$/))) {
console.log(HELP_MESSAGE)
exit(0)
}
let allFiles = await scanTree('.') //Can't do anything until we have our tree.
let tasks = findTasks(allFiles) //Generates the list of files we work on. These are the nodes of our dependancy tree.
calculateRequirements(tasks) //Calculate the relations between the nodes of the dependancy tree.
process.argv.includes('--full-rebuild')
? markTasksDirty(tasks) //Marks all tasks as needed to be run, useful when developing.
: markOutOfDate(tasks) //Re-marks tasks as clean or dirty, useful when re-runnning.
let taskToShow = ''
let shownTasks = 0
if (process.argv.find(a => taskToShow=a.match(/^--show-tasks?(?:=(?<name>.+))?$/))) {
for (const task of tasks) {
if(!taskToShow.groups.name || task.name === taskToShow.groups.name) {
console.log(task)
shownTasks++
}
}
}
if (taskToShow && !shownTasks) {
console.log(`No task named ${
taskToShow.groups.name
} found. Available tasks:\n\t${
Array.from(tasks.reduce((a,b)=>a.add(b.name), new Set()).keys()).sort().join('\n\t')
}`)
exit(-2)
}
if(process.argv.includes('--dot')) {
stdout.write(dotify(tasks))
stdout.once('drain', () => process.exit(0)) //Needed or else graph gets corrupted.
return
}
if (!process.argv.includes('--watch')) {
exit((await runAllTasks(tasks))-1)
} else {
console.log('Watching for changes…')
watchForChanges(allFiles, tasks)
}
})()
const watchForChanges = async (allFiles, tasks)=>{
await runAllTasks(tasks)
let folderFragment = /(?<folder>.+?)[^\/]+$/
let folders = new Set()
for (const task of tasks) {
for (const {name} of task.input) {
folders.add(folderFragment.exec(name).groups.folder)
}
}
let dirChanged = false
let fileChanged = false
let timeout = null
const watchers = Array.from(folders).map(folder =>
watch(folder, (event, file) => {
process.argv.includes('--print-events') && console.log({event, folder, file})
if (event==='change' && file) {
fileChanged |= true
markFileDirty(tasks, folder+file)
} else if (event==='change' || event==='rename') {
dirChanged |= true
}
clearTimeout(timeout)
setTimeout(onTimeout, REPEAT_BUILD_DEBOUNCE_MS)
})
)
let building = false
const onTimeout = async ()=>{
if (building) {
timeout = setTimeout(onTimeout, REPEAT_BUILD_DEBOUNCE_MS)
return
}
building = true
if (dirChanged) {
watchers.forEach(watcher => watcher.close())
const allFiles = await scanTree('.')
const tasks = findTasks(allFiles)
calculateRequirements(tasks)
markOutOfDate(tasks)
watchForChanges(allFiles, tasks)
} else if (fileChanged) {
dirChanged = false
fileChanged = false
building = true
//refreshTimestamps(tasks)
//markOutOfDate(tasks)
await runAllTasks(tasks)
}
dirChanged = false
fileChanged = false
building = false
}
}
const dotify = tasks => {
const commonBuildFiles = ['./render-file.node.js', './compile-template.node.js']
let out = ''
out += `digraph G {
label="Dependencies"
labelloc = t
labelfontsize = 24
graph [rankdir=“LR”]
#layout="sfdp"
layout="neato"
concentrate=true
splines=true
labelfloat=true
ratio="compress"
overlap=prism
overlap_scaling=5
ratio=0.7
`
//style=filled, color=red
for (let [taskNum, task] of tasks.entries()) {
for (let input of task.input) {
if (commonBuildFiles.includes(input.name)) { continue; }
for (let output of task.output) {
if (prereqIsDirty(task)) {
if (isRunnable(task)) {
out += `\tedge [color=goldenrod]\n`
} else {
out += `\tedge [color=red]\n`
}
} else {
out += `\tedge [color=black]\n`
}
out += `\t"${input.name}" -> "${task.command.replace(/\"/g, '\\"')}" -> "${output.name}";\n`
}
}
for (let file of [...task.input, ...task.output]) {
if (commonBuildFiles.includes(file.name)) { continue; }
out += ` subgraph cluster${taskNum} {
label = "${task.name}";
"${file.name}" [
label="${file.name.split('/').slice(-1)}",
tooltip="${file.name}",
style=filled, fillcolor=white,
];
"${task.command.replace(/\"/g, '\\"')}" [
shape=box,
style=filled, fillcolor=lightgrey,
label="${task.command.split(' ')[0].split('/').slice(-1)}",
tooltip="${task.command.replace(/\"/g, '\\"')}",
];
}\n`
}
}
out += `}`
return out
}