forked from broccolijs/broccoli-merge-trees
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
345 lines (302 loc) · 11.2 KB
/
index.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
var fs = require('fs')
var rimraf = require('rimraf');
var Plugin = require('broccoli-plugin')
var symlinkOrCopySync = require('symlink-or-copy').sync
var loggerGen = require('heimdalljs-logger');
var FSTree = require('fs-tree-diff');
var Entry = require('./entry');
var heimdall = require('heimdalljs');
var canSymlink = require('can-symlink')();
var defaultIsEqual = FSTree.defaultIsEqual;
function ApplyPatchesSchema() {
this.mkdir = 0;
this.rmdir = 0;
this.unlink = 0;
this.change = 0;
this.create = 0;
this.other = 0;
this.processed = 0;
this.linked = 0;
}
function unlinkOrRmrfSync(path) {
if (canSymlink) {
fs.unlinkSync(path);
} else {
rimraf.sync(path);
}
}
module.exports = BroccoliMergeTrees
BroccoliMergeTrees.prototype = Object.create(Plugin.prototype)
BroccoliMergeTrees.prototype.constructor = BroccoliMergeTrees
function BroccoliMergeTrees(inputNodes, options) {
if (!(this instanceof BroccoliMergeTrees)) return new BroccoliMergeTrees(inputNodes, options)
options = options || {}
var name = 'broccoli-merge-trees:' + (options.annotation || '')
if (!Array.isArray(inputNodes)) {
throw new TypeError(name + ': Expected array, got: [' + inputNodes +']')
}
Plugin.call(this, inputNodes, {
persistentOutput: true,
needsCache: false,
annotation: options.annotation
})
this._logger = loggerGen(name);
this.options = options
this._buildCount = 0;
this._currentTree = FSTree.fromPaths([]);
}
BroccoliMergeTrees.prototype.debug = function(message, args) {
this._logger.info(message, args);
}
function isLinkStateEqual(entryA, entryB) {
// We don't symlink files, only directories
if (!(entryA.isDirectory() && entryB.isDirectory())) {
return true;
}
// We only symlink on systems that support it
if (!canSymlink) {
return true;
}
// This can change between rebuilds if a dir goes from existing in multiple
// input sources to exactly one input source, or vice versa
return entryA.linkDir === entryB.linkDir;
}
function isEqual(entryA, entryB) {
return defaultIsEqual(entryA, entryB) && isLinkStateEqual(entryA, entryB);
}
BroccoliMergeTrees.prototype.build = function() {
this._logger.debug('deriving patches');
var instrumentation = heimdall.start('derivePatches');
var fileInfos = this._mergeRelativePath('');
var entries = fileInfos.map(function(fileInfo) {
return fileInfo.entry;
});
var newTree = FSTree.fromEntries(entries);
var patches = this._currentTree.calculatePatch(newTree, isEqual);
instrumentation.stats.patches = patches.length;
instrumentation.stats.entries = entries.length;
instrumentation.stop();
this._currentTree = newTree;
instrumentation = heimdall.start('applyPatches', ApplyPatchesSchema);
try {
this._logger.debug('applying patches');
this._applyPatch(patches, instrumentation.stats);
} catch(e) {
this._logger.warn('patch application failed, starting from scratch');
// Whatever the failure, start again and do a complete build next time
this._currentTree = FSTree.fromPaths([]);
rimraf.sync(this.outputPath);
throw e;
}
instrumentation.stop();
}
BroccoliMergeTrees.prototype._applyPatch = function (patch, instrumentation) {
patch.forEach(function(patch) {
var operation = patch[0];
var relativePath = patch[1];
var entry = patch[2];
var outputFilePath = this.outputPath + '/' + relativePath;
var inputFilePath = entry && entry.basePath + '/' + relativePath;
switch(operation) {
case 'mkdir': {
instrumentation.mkdir++;
return this._applyMkdir(entry, inputFilePath, outputFilePath);
}
case 'rmdir': {
instrumentation.rmdir++;
return this._applyRmdir(entry, inputFilePath, outputFilePath);
}
case 'unlink': {
instrumentation.unlink++;
return fs.unlinkSync(outputFilePath);
}
case 'create': {
instrumentation.create++;
return symlinkOrCopySync(inputFilePath, outputFilePath);
}
case 'change': {
instrumentation.change++;
return this._applyChange(entry, inputFilePath, outputFilePath);
}
}
}, this);
};
BroccoliMergeTrees.prototype._applyMkdir = function (entry, inputFilePath, outputFilePath) {
if (entry.linkDir) {
return symlinkOrCopySync(inputFilePath, outputFilePath);
} else {
return fs.mkdirSync(outputFilePath);
}
}
BroccoliMergeTrees.prototype._applyRmdir = function (entry, inputFilePath, outputFilePath) {
if (entry.linkDir) {
return unlinkOrRmrfSync(outputFilePath);
} else {
return fs.rmdirSync(outputFilePath);
}
}
BroccoliMergeTrees.prototype._applyChange = function (entry, inputFilePath, outputFilePath) {
if (entry.isDirectory()) {
if (entry.linkDir) {
// directory copied -> link
fs.rmdirSync(outputFilePath);
return symlinkOrCopySync(inputFilePath, outputFilePath);
} else {
// directory link -> copied
//
// we don't check for `canSymlink` here because that is handled in
// `isLinkStateEqual`. If symlinking is not supported we will not get
// directory change operations
fs.unlinkSync(outputFilePath);
fs.mkdirSync(outputFilePath);
return
}
} else {
// file changed
fs.unlinkSync(outputFilePath);
return symlinkOrCopySync(inputFilePath, outputFilePath);
}
}
BroccoliMergeTrees.prototype._mergeRelativePath = function (baseDir, possibleIndices) {
var inputPaths = this.inputPaths;
var overwrite = this.options.overwrite;
var result = [];
var isBaseCase = (possibleIndices === undefined);
// baseDir has a trailing path.sep if non-empty
var i, j, fileName, fullPath, subEntries;
// Array of readdir arrays
var names = inputPaths.map(function (inputPath, i) {
if (possibleIndices == null || possibleIndices.indexOf(i) !== -1) {
return fs.readdirSync(inputPath + '/' + baseDir).sort()
} else {
return []
}
})
// Guard against conflicting capitalizations
var lowerCaseNames = {}
for (i = 0; i < this.inputPaths.length; i++) {
for (j = 0; j < names[i].length; j++) {
fileName = names[i][j]
var lowerCaseName = fileName.toLowerCase()
// Note: We are using .toLowerCase to approximate the case
// insensitivity behavior of HFS+ and NTFS. While .toLowerCase is at
// least Unicode aware, there are probably better-suited functions.
if (lowerCaseNames[lowerCaseName] === undefined) {
lowerCaseNames[lowerCaseName] = {
index: i,
originalName: fileName
}
} else {
var originalIndex = lowerCaseNames[lowerCaseName].index
var originalName = lowerCaseNames[lowerCaseName].originalName
if (originalName !== fileName) {
throw new Error('Merge error: conflicting capitalizations:\n'
+ baseDir + originalName + ' in ' + this.inputPaths[originalIndex] + '\n'
+ baseDir + fileName + ' in ' + this.inputPaths[i] + '\n'
+ 'Remove one of the files and re-add it with matching capitalization.\n'
+ 'We are strict about this to avoid divergent behavior '
+ 'between case-insensitive Mac/Windows and case-sensitive Linux.'
)
}
}
}
}
// From here on out, no files and directories exist with conflicting
// capitalizations, which means we can use `===` without .toLowerCase
// normalization.
// Accumulate fileInfo hashes of { isDirectory, indices }.
// Also guard against conflicting file types and overwriting.
var fileInfo = {}
var inputPath;
var infoHash;
for (i = 0; i < inputPaths.length; i++) {
inputPath = inputPaths[i];
for (j = 0; j < names[i].length; j++) {
fileName = names[i][j]
// TODO: walk backwards to skip stating files we will just drop anyways
var entry = buildEntry(baseDir + fileName, inputPath);
var isDirectory = entry.isDirectory();
if (fileInfo[fileName] == null) {
fileInfo[fileName] = {
entry: entry,
isDirectory: isDirectory,
indices: [i] // indices into inputPaths in which this file exists
};
} else {
fileInfo[fileName].entry = entry;
fileInfo[fileName].indices.push(i)
// Guard against conflicting file types
var originallyDirectory = fileInfo[fileName].isDirectory
if (originallyDirectory !== isDirectory) {
throw new Error('Merge error: conflicting file types: ' + baseDir + fileName
+ ' is a ' + (originallyDirectory ? 'directory' : 'file')
+ ' in ' + this.inputPaths[fileInfo[fileName].indices[0]]
+ ' but a ' + (isDirectory ? 'directory' : 'file')
+ ' in ' + this.inputPaths[i] + '\n'
+ 'Remove or rename either of those.'
)
}
// Guard against overwriting when disabled
if (!isDirectory && !overwrite) {
throw new Error('Merge error: '
+ 'file ' + baseDir + fileName + ' exists in '
+ this.inputPaths[fileInfo[fileName].indices[0]] + ' and ' + this.inputPaths[i] + '\n'
+ 'Pass option { overwrite: true } to mergeTrees in order '
+ 'to have the latter file win.'
)
}
}
}
}
// Done guarding against all error conditions. Actually merge now.
for (i = 0; i < this.inputPaths.length; i++) {
for (j = 0; j < names[i].length; j++) {
fileName = names[i][j]
fullPath = this.inputPaths[i] + '/' + baseDir + fileName
infoHash = fileInfo[fileName]
if (infoHash.isDirectory) {
if (infoHash.indices.length === 1 && canSymlink) {
// This directory appears in only one tree: we can symlink it without
// reading the full tree
infoHash.entry.linkDir = true;
result.push(infoHash);
} else {
if (infoHash.indices[0] === i) { // avoid duplicate recursion
subEntries = this._mergeRelativePath(baseDir + fileName + '/', infoHash.indices);
// FSTreeDiff requires intermediate directory entries, so push
// `infoHash` (this dir) as well as sub entries.
result.push(infoHash);
result.push.apply(result, subEntries);
}
}
} else { // isFile
if (infoHash.indices[infoHash.indices.length-1] === i) {
result.push(infoHash);
} else {
// This file exists in a later inputPath. Do nothing here to have the
// later file win out and thus "overwrite" the earlier file.
}
}
}
}
if (isBaseCase) {
// FSTreeDiff requires entries to be sorted by `relativePath`.
return result.sort(function (a, b) {
var pathA = a.entry.relativePath;
var pathB = b.entry.relativePath;
if (pathA === pathB) {
return 0;
} else if (pathA < pathB) {
return -1;
} else {
return 1;
}
});
} else {
return result;
}
};
function buildEntry(relativePath, basePath) {
var stat = fs.statSync(basePath + '/' + relativePath);
return new Entry(relativePath, basePath, stat.mode, stat.size, stat.mtime);
}