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 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
78×
78×
78×
2×
11×
140×
137×
3×
140×
140×
140×
140×
279×
4×
4×
4×
4×
4×
4×
3×
3×
1×
24×
24×
24×
24×
37×
46×
24×
24×
15×
15×
15×
14×
14×
14×
11×
3×
1×
2×
27×
27×
74×
74×
72×
72×
70×
70×
8×
8×
7×
7×
6×
6×
12×
12×
12×
12×
12×
12×
23×
14×
13×
13×
11×
11×
9×
9×
5×
5×
4×
4×
3×
3×
6×
6×
6×
6×
6×
6×
9×
38×
2×
2×
2×
6×
2×
2×
6×
6×
6×
6×
6×
6×
6×
6×
6×
12×
6×
28×
10×
6×
3×
3×
3×
3×
3×
3×
7×
3×
7×
7×
3×
3×
3×
3×
3×
3×
5×
5×
5×
3×
5×
5×
3×
3×
3×
3×
3×
2×
2×
2×
2×
2×
2×
2×
2×
2×
1×
1×
2×
2×
1×
1×
304×
1×
37×
2×
35×
2×
33×
| 'use strict'
require('babel-polyfill-safer')
let assert = require('assert')
let bytes = require('bytes')
let debug = require('debug')('mako-tree')
let File = require('./file')
let iso = require('regex-iso-date')()
let Graph = require('graph.js/dist/graph.js')
let toposort = require('graph-toposort')
let utils = require('mako-utils')
/**
* Represents a dependency graph for the builder.
*
* @class
*/
class Tree {
/**
* Creates a new instance, particularly creating the Graph instance.
*
* @param {String} root The optional project root. (default: pwd)
*/
constructor (root) {
debug('initialize')
this.root = root || process.cwd()
this.graph = new Graph()
}
/**
* Implement the iterator interface to allow iterating the files in this
* tree topologically.
*
* TODO: allow configuring the iteration order (ie: turn topological off)
*/
[Symbol.iterator] () {
return this.getFiles({ topological: true }).values()
}
/**
* Checks to see if the given file ID exists in the tree.
*
* @param {String} file The file or string ID.
* @return {Boolean} has
*/
hasFile (file) {
return this.graph.hasVertex(id(file))
}
/**
* Adds the file with the given `params` to the tree. If a file with that
* path already exists in the tree, that is returned instead.
*
* @param {Object} params The vinyl params for this file.
* @return {File} file
*/
addFile (params) {
if (typeof params === 'string') {
params = { base: this.root, path: params }
} else {
params.base = this.root
}
let file = new File(params, this)
debug('adding file: %s', utils.relative(file.path))
this.graph.addNewVertex(file.id, file)
return file
}
/**
* Returns the `File` with the given `id`.
*
* @param {String} file The file ID.
* @return {File} file
*/
getFile (file) {
return this.graph.vertexValue(file)
}
/**
* Iterates through the files looking for one that matches the input path.
*
* @param {String} file The path to search for.
* @return {File} file
*/
findFile (file) {
let timer = utils.timer()
let path = typeof file === 'string' ? file : file.path
debug('searching for file with path %s', utils.relative(path))
for (let vertex of this.graph.vertices()) {
let file = vertex[1]
if (file.hasPath(path)) {
debug('match found: %s (took %s)', utils.relative(file.path), timer())
return file
}
}
debug('file not found (took %s)', timer())
}
/**
* Retrieve a list of file paths based on the given criteria.
*
* Available `options`:
* - `topological` sort the files topologically
*
* @param {Object} options The optional filter criteria.
* @return {Array} files
*/
getFiles (options) {
let timer = utils.timer()
let topological = options ? !!options.topological : false
debug('getting %d files: (topological: %j)', this.size(), topological)
let files = topological
? toposort(this.graph).map(id => this.getFile(id))
: Array.from(this.graph.vertices()).map(v => v[1])
debug('finished getting %d files (took %s)', files.length, timer())
return files
}
/**
* Remove the file with the given `id` from the graph.
*
* Available `options`:
* - `force` removes the file even if dependencies/dependants exist
*
* @param {String} node The file or string ID.
* @param {Object} options Additional options.
*/
removeFile (node, options) {
let force = options ? !!options.force : false
let file = this.getFile(id(node))
assert(file, `cannot find file ${node} in this tree`)
const relative = utils.relative(file.path)
debug('removing file %s: (force: %j)', relative, force)
if (force) {
this.graph.destroyVertex(file.id)
} else {
if (this.graph.degree(file.id) > 0) {
throw new Error(`cannot remove ${relative} while it still has dependencies in the tree (use force: true to override this)`)
}
this.graph.removeVertex(file.id)
}
}
/**
* Checks to see if the given `parent` has a link to dependency `child`.
*
* Available `options`:
* - `recursive`: check for the dependency recursively
*
* @param {String} parent The parent file (or it's string ID).
* @param {String} child The child file (or it's string ID).
* @param {Object} options Additional options.
* @return {Boolean} has
*/
hasDependency (parent, child, options) {
let recursive = options ? !!options.recursive : false
return recursive
? this.graph.hasPath(id(child), id(parent))
: this.graph.hasEdge(id(child), id(parent))
}
/**
* Sets up the file `child` as a dependency of `parent`.
*
* @param {String} parent The parent file (or it's string ID).
* @param {String} child The child file (or it's string ID).
*/
addDependency (parent, child) {
let childFile = this.getFile(id(child))
assert(childFile, `cannot add dependency because ${child} is not in the tree`)
let parentFile = this.getFile(id(parent))
assert(parentFile, `cannot add dependency because ${parent} is not in the tree`)
this.graph.addEdge(childFile.id, parentFile.id)
debug('added dependency %s -> %s', utils.relative(childFile.path), utils.relative(parentFile.path))
}
/**
* Removes the dependency `child` from the `parent` file.
*
* @param {String} parent The parent file (or it's string ID).
* @param {String} child The child file (or it's string ID).
*/
removeDependency (parent, child) {
let childFile = this.getFile(id(child))
assert(childFile, `cannot remove dependency because ${child} is not in the tree`)
let parentFile = this.getFile(id(parent))
assert(parentFile, `cannot remove dependency because ${parent} is not in the tree`)
this.graph.removeEdge(childFile.id, parentFile.id)
debug('removed dependency %s -> %s', utils.relative(childFile.path), utils.relative(parentFile.path))
}
/**
* Return a list of all files that the given `node` file depends on.
*
* Available `options`:
* - `recursive` when set, go recursively down the entire graph
*
* @param {String} node The parent file (or it's string ID).
* @param {Object} options Optional search criteria.
* @return {Array} files
*/
dependenciesOf (node, options) {
let timer = utils.timer()
let recursive = options ? !!options.recursive : false
let file = this.getFile(id(node))
debug('getting dependencies of %s: (recursive: %j)', utils.relative(file.path), recursive)
let deps = recursive
? Array.from(this.graph.verticesWithPathTo(file.id))
: Array.from(this.graph.verticesTo(file.id))
debug('%d dependencies found (took %s)', deps.length, timer())
return deps.map(v => v[1])
}
/**
* Checks to see if the given `child` has a link to dependant `parent`.
*
* Available `options`:
* - `recursive` looks for the dependant recursively.
*
* @param {String} child The child file (or it's string ID).
* @param {String} parent The parent file (or it's string ID).
* @param {Object} options Additional options.
* @return {Boolean} has
*/
hasDependant (child, parent, options) {
return this.hasDependency(parent, child, options)
}
/**
* Sets up the given `parent` as a dependant of `child`. In other words,
* the reverse of addDependency()
*
* @param {String} child The child file (or it's string ID).
* @param {String} parent The parent file (or it's string ID).
*/
addDependant (child, parent) {
let childFile = this.getFile(id(child))
assert(childFile, `cannot add dependant because ${child} is not in the tree`)
let parentFile = this.getFile(id(parent))
assert(parentFile, `cannot add dependant because ${parent} is not in the tree`)
this.graph.addEdge(childFile.id, parentFile.id)
debug('added dependant %s <- %s', utils.relative(childFile.path), utils.relative(parentFile.path))
}
/**
* Removes the dependant `parent` from the `child` file.
*
* @param {String} child The child file (or it's string ID).
* @param {String} parent The parent file (or it's string ID).
*/
removeDependant (child, parent) {
let childFile = this.getFile(id(child))
assert(childFile, `cannot remove dependant because ${child} is not in the tree`)
let parentFile = this.getFile(id(parent))
assert(parentFile, `cannot remove dependant because ${parent} is not in the tree`)
this.graph.removeEdge(childFile.id, parentFile.id)
debug('removed dependant %s <- %s', utils.relative(childFile.path), utils.relative(parentFile.path))
}
/**
* Return a list of all files that depend on the given `node` file.
*
* Available `options`:
* - `recursive` when set, go recursively down the entire graph
*
* @param {String} node The child file (or it's string ID).
* @param {Object} options The search criteria.
* @return {Array} files
*/
dependantsOf (node, options) {
let timer = utils.timer()
let recursive = options ? !!options.recursive : false
let file = this.getFile(id(node))
debug('getting dependants of %s: (recursive: %j)', utils.relative(file.path), recursive)
let deps = recursive
? Array.from(this.graph.verticesWithPathFrom(id(file)))
: Array.from(this.graph.verticesFrom(id(file)))
debug('%d dependants found (took %s)', deps.length, timer())
return deps.map(v => v[1])
}
/**
* Tells us how many files are in the tree.
*
* @return {Number} size
*/
size () {
return this.graph.vertexCount()
}
/**
* Returns a clone of the current `Tree` instance.
*
* @return {Tree} clone
*/
clone () {
debug('cloning tree')
let timer = utils.timer()
let tree = new Tree(this.root)
tree.graph = this.graph.clone(file => file.clone(tree), value => value)
debug('cloned tree (took %s)', timer())
return tree
}
/**
* Remove any files that cannot be reached from the given `anchors`.
*
* @param {Array} anchors A list of files to anchor others to.
*/
prune (anchors) {
let timer = utils.timer()
let initialSize = this.size()
let files = anchors.map(file => this.getFile(id(file)))
debug('pruning files from tree that are not accessible from:')
files.forEach(file => debug('> %s', utils.relative(file.path)))
let deps = new Set()
files.forEach(file => {
deps.add(file)
this.dependenciesOf(file, { recursive: true })
.forEach(file => deps.add(file))
})
this.getFiles()
.filter(file => !deps.has(file))
.forEach(file => this.removeFile(file, { force: true }))
debug('%d files pruned from tree (took %s)', initialSize, timer())
}
/**
* Forcibly make this graph acyclic.
*/
removeCycles () {
debug('removing cycles from tree')
let timer = utils.timer()
let graph = this.graph
let count = 0
while (graph.hasCycle()) {
let cycle = graph.cycle()
let files = cycle.map(file => this.getFile(file))
debug('cycle detected:')
files.forEach(file => debug('> %s (degree: %d)', utils.relative(file.path), graph.outDegree(file.id)))
// prefer to remove edges where the degree is higher, in an attempt to
// avoid altering the graph more than necessary.
let degrees = files.map(file => graph.outDegree(file.id))
let highest = degrees.indexOf(Math.max.apply(Math, degrees))
let child = files[highest]
let parent = files[highest + 1] ? files[highest + 1] : files[0]
this.removeDependency(parent, child)
count++
}
debug('removed %d cycles (took %s)', count, timer())
}
/**
* Returns a trimmed object that can be serialized as JSON. It includes a list
* of vertices and edges for reconstructing the underlying graph.
*
* @return {Object} obj
*/
toJSON () {
debug('convert to json')
let timer = utils.timer()
let o = {
root: this.root,
files: this.getFiles(),
dependencies: Array.from(this.graph.edges()).map(e => e.slice(0, 2))
}
debug('converted to json (took %s)', timer())
return o
}
/**
* Serializes the tree into a plain JSON string for writing to storage.
* (probably disk)
*
* @param {Number} space The JSON.stringify space parameter.
* @return {String} str
*/
toString (space) {
debug('convert to string')
let timer = utils.timer()
let str = JSON.stringify(this, null, space)
debug('converted to %s string (took %s)', bytes(str.length), timer())
return str
}
/**
* Used to parse a string value into a usable tree.
*
* @static
* @param {String} input The raw JSON string to parse.
* @return {Tree} tree
*/
static fromString (input) {
debug('convert from string')
let timer = utils.timer()
let parsed = JSON.parse(input, reviver)
let tree = new Tree(parsed.root)
parsed.files.forEach(o => {
let file = File.fromObject(o, tree)
debug('file from cache: %s', file.id)
tree.graph.addNewVertex(file.id, file)
})
parsed.dependencies.forEach(e => {
debug('dependency from cache: %s', e.join(' '))
tree.graph.addNewEdge(e[0], e[1])
})
debug('converted from %s string (took %s)', bytes(input.length), timer())
return tree
}
}
// single export
module.exports = Tree
/**
* Helper for retrieving a file id.
*
* @param {File} file The file object or a string id.
* @return {String} id
*/
function id (file) {
return file instanceof File ? file.id : file
}
/**
* JSON.parse reviver param for restoring buffers and dates to file objects.
*
* @param {String} key See JSON.parse reviver documentation
* @param {String} value See JSON.parse reviver documentation
* @return {Mixed} revived
*/
function reviver (key, value) {
if (value && value.type === 'Buffer') {
return Buffer.from(value.data)
}
if (typeof value === 'string' && iso.test(value)) {
return new Date(value)
}
return value
}
|