-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.es
359 lines (311 loc) · 11 KB
/
index.es
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
import {
relative as relativePath,
resolve as resolvePath,
isAbsolute as isAbsolutePath,
} from "path"
import async from "async"
import gaze from "gaze"
import color from "chalk"
import multimatch from "multimatch"
import unyield from "unyield"
import metalsmithFilenames from "metalsmith-filenames"
import livereloadServer from "./livereload"
const jsFileRE = /\.(jsx?|es\d{0,1})$/
const addFilenames = metalsmithFilenames()
const ok = color.green("✔︎")
const nok = color.red("✗")
// only first file that require something has it in its children
// so relying on children to invalidate sibling is not doable
// function invalidateCache(from, path, options) {
// // we invalidate cache only for files in metalsmith root
// if (require.cache[path] && path.indexOf(from) === 0) {
// Object.keys(require.cache)
// .filter(file => file.indexOf(from) === 0)
// .filter(file => require.cache[file].children.indexOf(require.cache[path]) > -1)
// .forEach(file => {
// console.log(file, "is in children")
// invalidateCache(from, file, options)
// })
//
// delete require.cache[path]
// options.log(`${relativePath(from, path)} cache deleted`)
// return true
// }
// return false
// }
function livereloadFiles(livereload, files, options) {
if(livereload) {
const keys = Object.keys(files)
const nbOfFiles = Object.keys(files).length
options.log(`${ok} ${nbOfFiles} file${nbOfFiles > 1 ? "s" : ""} reloaded`)
livereload.changed({body: {files: keys}})
}
}
// metalsmith-collections fix: collections are mutable
// fuck mutability
function backupCollections(collections) {
const collectionsBackup = {}
if (typeof collections === "object") {
Object.keys(collections).forEach(key => {
collectionsBackup[key] = [...collections[key]]
})
}
return collectionsBackup
}
// metalsmith-collections fix: collections are in metadata as is + under metadata.collections
function updateCollections(metalsmith, collections) {
const metadata = {
...metalsmith.metadata(),
collections,
}
// copy ref to metadata root since metalsmith-collections use this references
// as primary location (*facepalm*)
Object.keys(collections).forEach(key => {
metadata[key] = collections[key]
})
metalsmith.metadata(metadata)
}
// metalsmith-collections fix: helps to update fix collections
function saveFilenameInFilesData(files) {
addFilenames(files)
}
// metalsmith-collections fix: remove items from collections that will be readded by the partial build
function removeFilesFromCollection(files, collections) {
const filenames = Object.keys(files)
Object.keys(collections).forEach(key => {
for (let i = 0; i < collections[key].length; i++) {
if (filenames.indexOf(collections[key][i].filename) > -1) {
collections[key] = [
...collections[key].slice(0, i),
...collections[key].slice(i + 1),
]
i--
}
}
})
}
function runAndUpdate(metalsmith, files, livereload, options, previousFilesMap) {
// metalsmith-collections fix: metalsmith-collections plugin add files to
// collection when run() is called which create problem since we use run()
// with only new files.
// In order to prevent prevent duplicate issue (some contents will be available
// in collections with the new and the previous version),
// we remove from existing collections files that will be updated
// (file already in the collections)
// we iterate on collections with reference to previous files data
// and skip old files that match the paths that will be updated
saveFilenameInFilesData(files)
const collections = metalsmith.metadata().collections
const collectionsBackup = backupCollections(collections)
if (collections) {
// mutability ftl :(
removeFilesFromCollection(files, collections)
// metalsmith-collections fix: prepare collections with partials items
// run() below will add the new files to the collections
updateCollections(metalsmith, collections)
}
metalsmith.run(files, function(err, freshFiles) {
if (err) {
if (collections) {
// metalsmith-collections fix: rollback collections
updateCollections(metalsmith, collectionsBackup)
}
options.log(color.red(`${nok} ${err.toString()}`))
// babel use that to share information :)
if (err.codeFrame) {
err.codeFrame.split("\n").forEach(line => options.log(line))
}
return
}
// metalsmith-collections fix: update ref for future tests
Object.keys(freshFiles).forEach(path => {
previousFilesMap[path] = freshFiles[path]
})
metalsmith.write(freshFiles, function(writeErr) {
if(writeErr) {throw writeErr}
livereloadFiles(livereload, freshFiles, options)
})
})
}
function buildFiles(metalsmith, paths, livereload, options, previousFilesMap) {
const files = {}
async.each(
paths,
(path, cb) => {
metalsmith.readFile(path, function(err, file) {
if (err) {
options.log(color.red(`${nok} ${err}`))
return
}
files[path] = file
cb()
})
},
(err) => {
if (err) {
options.log(color.red(`${nok} ${err}`))
return
}
const nbOfFiles = Object.keys(files).length
options.log(color.gray(`- Updating ${nbOfFiles} file${nbOfFiles > 1 ? "s" : ""}...`))
runAndUpdate(metalsmith, files, livereload, options, previousFilesMap)
}
)
}
function buildPattern(metalsmith, patterns, livereload, options, previousFilesMap) {
unyield(metalsmith.read())((err, files) => {
if (err) {
options.log(color.red(`${nok} ${err}`))
return
}
const filesToUpdate = {}
multimatch(Object.keys(files), patterns).forEach(path => filesToUpdate[path] = files[path])
const nbOfFiles = Object.keys(filesToUpdate).length
options.log(color.gray(`- Updating ${nbOfFiles} file${nbOfFiles > 1 ? "s" : ""}...`))
runAndUpdate(metalsmith, filesToUpdate, livereload, options, previousFilesMap)
})
}
export default function(options) {
options = {
...{
paths: "${source}/**/*",
livereload: false,
log: (...args) => {
console.log(color.gray("[metalsmith-watch]"), ...args)
},
invalidateCache: true,
},
...(options || {}),
}
if (typeof options.paths === "string") {
options.paths = {[options.paths]: true}
}
let livereload
if(options.livereload) {
livereload = livereloadServer(options.livereload, options.log)
}
let watched = false
const plugin = function metalsmithWatch(files, metalsmith, cb) {
// only run this plugin once
if (watched) {
cb()
return
}
watched = true
// metalsmith-collections fix: keep filename as metadata
saveFilenameInFilesData(files)
const patterns = {}
Object.keys(options.paths).map(pattern => {
let watchPattern = pattern.replace("${source}", metalsmith.source())
if (!isAbsolutePath(watchPattern)){
watchPattern = resolvePath(metalsmith.directory(), pattern);
}
const watchPatternRelative = relativePath(metalsmith.directory(), watchPattern)
patterns[watchPatternRelative] = options.paths[pattern]
})
gaze(
Object.keys(patterns),
{
...options.gaze,
cwd: metalsmith._directory,
},
function watcherReady(err, watcher) {
if (err) {throw err}
Object.keys(patterns).forEach(pattern => {
options.log(`${ok} Watching ${color.cyan(pattern)}`)
})
const previousFilesMap = {...files}
// Delay watch update to be able to bundle multiples update in the same build
// Saving multiples files at the same time create multiples build otherwise
let updateDelay = 50
let updatePlanned = false
let pathsToUpdate = []
const update = () => {
// since I can't find a way to do a smart cache cleaning
// (see commented invalidateCache() method)
// here is a more brutal way (that works)
if (
options.invalidateCache &&
// only if there is a js file
pathsToUpdate.some(file => file.match(jsFileRE))
) {
const filesToInvalidate = Object.keys(patterns)
.reduce((acc, pattern) => {
return [
...acc,
...multimatch(
Object.keys(require.cache),
`${resolvePath(metalsmith._directory)}/${pattern}`
),
]
}, [])
if (filesToInvalidate.length) {
options.log(color.gray(`- Deleting cache for ${filesToInvalidate.length} entries...`))
filesToInvalidate.forEach(file => delete require.cache[file])
options.log(`${ok} Cache deleted`)
}
}
const patternsToUpdate = Object.keys(patterns).filter(pattern => patterns[pattern] === true)
const filesToUpdate = multimatch(pathsToUpdate, patternsToUpdate).map((file) => {
const filepath = resolvePath(metalsmith.path(), file)
return relativePath(metalsmith.source(), filepath)
})
if (filesToUpdate.length) {
buildFiles(metalsmith, filesToUpdate, livereload, options, previousFilesMap)
}
const patternsToUpdatePattern = Object.keys(patterns)
.filter(pattern => patterns[pattern] !== true)
.filter(pattern => multimatch(pathsToUpdate, pattern).length > 0)
.map(pattern => patterns[pattern])
if (patternsToUpdatePattern.length) {
buildPattern(metalsmith, patternsToUpdatePattern, livereload, options, previousFilesMap)
}
// console.log(pathsToUpdate, filesToUpdate, patternsToUpdatePattern)
// cleanup
pathsToUpdate = []
}
watcher.on("all", (event, path) => {
const filename = relativePath(metalsmith._directory, path)
if (
event === "added" ||
event === "changed" ||
event === "renamed" ||
event === "deleted"
) {
options.log(`${ok} ${color.cyan(filename)} ${event}`)
}
// if (event === "changed") {
// if (options.invalidateCache) {
// invalidateCache(
// resolvePath(metalsmith._directory),
// resolvePath(path),
// options
// )
// }
// }
if (
event === "added" ||
event === "changed" ||
event === "renamed"
) {
pathsToUpdate.push(relativePath(metalsmith.path(), path))
if (updatePlanned) {
clearTimeout(updatePlanned)
}
updatePlanned = setTimeout(update, updateDelay)
}
})
plugin.close = () => {
if (typeof watcher === "object") {
watcher.close()
watcher = undefined
}
}
}
)
cb()
}
// convenience for testing
plugin.options = options
return plugin
}