-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathrevisioner.js
569 lines (496 loc) · 16.5 KB
/
revisioner.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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import Vinyl from "vinyl";
import fancyLog from "fancy-log";
import chalk from "chalk";
import Path from "path";
import {
get_reference_representations_absolute,
get_reference_representations_relative,
get_relative_path,
is_binary_file,
join_path,
join_path_url,
md5,
path_without_ext,
} from "./tool.js";
var Revisioner = function (options) {
var defaults = {
hashLength: 8,
dontGlobal: [/^\/favicon.ico$/g],
dontRenameFile: [],
dontUpdateReference: [],
dontSearchFile: [],
fileNameVersion: "rev-version.json",
fileNameManifest: "rev-manifest.json",
prefix: "",
referenceToRegexs: referenceToRegexs,
annotator: annotator,
replacer: replacer,
debug: false,
includeFilesInManifest: [".css", ".js"],
};
this.options = { ...defaults, ... options };
// File pool, any file passed into the Revisioner is stored in this object
this.files = {};
this.filesTemp = [];
// Stores the combined hash of all processed files, used to create the version file
this.hashCombined = "";
// Stores the before : after path of assets, used to create the manifset file
this.manifest = {};
// Enable / Disable logger based on supplied options
this.log = this.options.debug ? fancyLog : function () {};
var nonFileNameChar = "[^a-zA-Z0-9\\.\\-\\_\\/]";
var qoutes = "'|\"";
function referenceToRegexs(reference) {
var escapedRefPathBase = path_without_ext(reference.path).replace(
/([^0-9a-z])/gi,
"\\$1"
);
var escapedRefPathExt = Path.extname(reference.path).replace(
/([^0-9a-z])/gi,
"\\$1"
);
var regExp,
regExps = [];
var isJSReference = reference.path.match(/\.js$/);
// Extensionless javascript file references has to to be qouted
if (isJSReference) {
regExp =
"(" + qoutes + ")(" + escapedRefPathBase + ")()(" + qoutes + "|$)";
regExps.push(new RegExp(regExp, "g"));
}
// Expect left and right sides of the reference to be a non-filename type character, escape special regex chars
regExp =
"(" +
nonFileNameChar +
")(" +
escapedRefPathBase +
")(" +
escapedRefPathExt +
")(" +
nonFileNameChar +
"|$)";
regExps.push(new RegExp(regExp, "g"));
return regExps;
}
function annotator(contents) {
return [{ contents: contents }];
}
function replacer(fragment, replaceRegExp, newReference) {
fragment.contents = fragment.contents.replace(
replaceRegExp,
"$1" + newReference + "$3$4"
);
}
};
Revisioner.prototype.versionFile = function () {
var out = {
hash: this.hashCombined,
timestamp: new Date(),
};
var file = new Vinyl({
cwd: this.pathCwd,
base: this.pathBase,
path: Path.join(this.pathBase, this.options.fileNameVersion),
contents: Buffer.from(JSON.stringify(out, null, 2)),
revisioner: this,
});
file.revisioner = this;
return file;
};
Revisioner.prototype.manifestFile = function () {
var file = new Vinyl({
cwd: this.pathCwd,
base: this.pathBase,
path: Path.join(this.pathBase, this.options.fileNameManifest),
contents: Buffer.from(JSON.stringify(this.manifest, null, 2)),
});
file.revisioner = this;
return file;
};
/**
* Used to feed files into the Revisioner, sets up the original filename and hash.
*/
Revisioner.prototype.processFile = function (file) {
if (!this.pathCwd) {
this.pathCwd = file.cwd;
}
// Chnage relative paths to absolute
if (!file.base.match(/^(\/|[a-z]:)/i)) {
file.base = join_path(file.cwd, file.base);
}
// Normalize the base common to all the files
if (!this.pathBase) {
this.pathBase = file.base;
} else if (file.base.indexOf(this.pathBase) === -1) {
var levelsBase = this.pathBase.split(/[/|\\]/);
var levelsFile = file.base.split(/[/|\\]/);
var common = [];
for (var level = 0, length = levelsFile.length; level < length; level++) {
if (
level < levelsBase.length &&
level < levelsFile.length &&
levelsBase[level] === levelsFile[level]
) {
common.push(levelsFile[level]);
continue;
}
}
if (common[common.length - 1] !== "") {
common.push("");
}
this.pathBase = common.join("/");
}
// Set original values before any processing occurs
file.revPathOriginal = file.revOrigPath = file.path;
file.revFilenameExtOriginal = Path.extname(file.path);
file.revFilenameOriginal = Path.basename(
file.path,
file.revFilenameExtOriginal
);
file.revHashOriginal = md5(file.contents);
file.revContentsOriginal = file.contents;
this.filesTemp.push(file);
};
/**
* Resolves references, renames files, updates references. To be called after all the files
* have been fed into the Revisioner (ie. At the end of the file stream)
*/
Revisioner.prototype.run = function () {
this.hashCombined = "";
// Go through and correct the base path now that we have proccessed all the files coming in
for (var i = 0, length = this.filesTemp.length; i < length; i++) {
this.filesTemp[i].base = this.pathBase;
var path = get_relative_path(
this.pathBase,
this.filesTemp[i].path
);
this.files[path] = this.filesTemp[i];
}
// Resolve references to other files
for (path in this.files) {
this.resolveReferences(this.files[path]);
}
// Resolve and set revisioned filename based on hash + reference hashes and ignore rules
for (path in this.files) {
this.revisionFilename(this.files[path]);
}
// Consolidate the concatinated hash of all the files, into a single hash for the version file
this.hashCombined = md5(this.hashCombined);
// Update references to revisioned filenames
for (path in this.files) {
this.updateReferences(this.files[path]);
}
};
/**
* Go through each file in the file pool, search for references to any other file in the pool.
*/
Revisioner.prototype.resolveReferences = function (fileResolveReferencesIn) {
var contents = String(fileResolveReferencesIn.revContentsOriginal);
fileResolveReferencesIn.revReferencePaths = {};
fileResolveReferencesIn.revReferenceFiles = {};
var referenceGroupRelative = [];
var referenceGroupAbsolute = [];
fileResolveReferencesIn.referenceGroupsContainer = {
relative: referenceGroupRelative,
absolute: referenceGroupAbsolute,
};
// Don't try and resolve references in binary files or files that have been blacklisted
if (
is_binary_file(fileResolveReferencesIn) ||
!this.shouldSearchFile(fileResolveReferencesIn)
) {
return;
}
// For the current file (fileResolveReferencesIn), look for references to any other file in the project
for (var path in this.files) {
// Organize them by relative vs absolute reference types
var fileCurrentReference = this.files[path];
var references;
references = get_reference_representations_relative(
fileCurrentReference,
fileResolveReferencesIn
);
for (var i = 0, length = references.length; i < length; i++) {
referenceGroupRelative.push({
file: this.files[path],
path: references[i],
});
}
references = get_reference_representations_absolute(
fileCurrentReference,
fileResolveReferencesIn
);
for (i = 0, length = references.length; i < length; i++) {
referenceGroupAbsolute.push({
file: this.files[path],
path: references[i],
});
}
}
// Priority relative references higher than absolute
for (var referenceType in fileResolveReferencesIn.referenceGroupsContainer) {
var referenceGroup =
fileResolveReferencesIn.referenceGroupsContainer[referenceType];
for (
var referenceIndex = 0, referenceGroupLength = referenceGroup.length;
referenceIndex < referenceGroupLength;
referenceIndex++
) {
var reference = referenceGroup[referenceIndex];
var regExps = this.options.referenceToRegexs(reference);
for (var j = 0; j < regExps.length; j++) {
if (contents.match(regExps[j])) {
// Only register this reference if we don't have one already by the same path
if (!fileResolveReferencesIn.revReferencePaths[reference.path]) {
fileResolveReferencesIn.revReferenceFiles[reference.file.path] =
reference.file;
fileResolveReferencesIn.revReferencePaths[reference.path] = {
regExps: [regExps[j]],
file: reference.file,
path: reference.path,
};
this.log(
"gulp-rev-all:",
"Found",
referenceType,
"reference [",
chalk.magenta(reference.path),
"] -> [",
chalk.green(reference.file.path),
"] in [",
chalk.blue(fileResolveReferencesIn.revPathOriginal),
"]"
);
} else if (
fileResolveReferencesIn.revReferencePaths[reference.path].file
.revPathOriginal === reference.file.revPathOriginal
) {
// Append the other regexes to account for inconsitent use
fileResolveReferencesIn.revReferencePaths[
reference.path
].regExps.push(regExps[j]);
} else {
this.log(
"gulp-rev-all:",
"Possible ambiguous reference detected [",
chalk.red(
fileResolveReferencesIn.revReferencePaths[reference.path].path
),
" (",
fileResolveReferencesIn.revReferencePaths[reference.path].file
.revPathOriginal,
")] <-> [",
chalk.red(reference.path),
"(",
chalk.red(reference.file.revPathOriginal),
")]"
);
}
}
}
}
}
};
/**
* Calculate hash based contents and references.
* hash = hash(file hash + hash(hash references 1 + hash reference N)..)
*/
Revisioner.prototype.calculateHash = function (file, stack) {
stack = stack || [];
var hash = file.revHashOriginal;
stack.push(file);
// Resolve hash for child references
if (Object.keys(file.revReferenceFiles).length > 0) {
for (var key in file.revReferenceFiles) {
// Prevent infinite loops caused by circular references, don't recurse if we've already encountered this file
if (stack.indexOf(file.revReferenceFiles[key]) === -1) {
hash += this.calculateHash(file.revReferenceFiles[key], stack);
}
}
// This file's hash should change if any of its references will be prefixed.
if (
this.options.prefix &&
Object.keys(file.referenceGroupsContainer.absolute).length
) {
hash += this.options.prefix;
}
// Consolidate many hashes into one
hash = md5(hash);
}
return hash;
};
/**
* Revision filename based on internal contents + references.
*/
Revisioner.prototype.revisionFilename = function (file) {
var filename = file.revFilenameOriginal;
var ext = file.revFilenameExtOriginal;
file.revHash = this.calculateHash(file);
// Allow the client to transform the final filename
if (this.options.transformFilename) {
filename = this.options.transformFilename.call(this, file, file.revHash);
} else {
filename =
filename + "." + file.revHash.substr(0, this.options.hashLength) + ext;
}
file.revFilename = filename;
// file.revFilenameNoExt = Tool.path_without_ext(file.revFilename);
if (this.shouldFileBeRenamed(file)) {
file.path = join_path(Path.dirname(file.path), filename);
}
// Maintain the combined hash used in version file
this.hashCombined += file.revHash;
// Maintain the manifset file
var pathOriginal = get_relative_path(
this.pathBase,
file.revPathOriginal,
true
);
var pathRevisioned = get_relative_path(
file.base,
file.path,
true
);
// Add only specific file types to the manifest file
if (this.options.includeFilesInManifest.indexOf(ext) !== -1) {
this.manifest[pathOriginal] = pathRevisioned;
}
file.revPath = pathRevisioned;
};
/**
* Update the contents of a file with the revisioned filenames of its references.
*/
Revisioner.prototype.updateReferences = function (file) {
// Don't try and update references in binary files or blacklisted files
if (is_binary_file(file) || !this.shouldSearchFile(file)) {
return;
}
var contents = String(file.revContentsOriginal);
var annotatedContent = this.options.annotator(
contents,
file.revPathOriginal
);
for (var pathReference in file.revReferencePaths) {
var reference = file.revReferencePaths[pathReference];
// Replace regular filename with revisioned version
var referencePath = reference.path.substr(
0,
reference.path.length -
(reference.file.revFilenameOriginal.length +
reference.file.revFilenameExtOriginal.length)
);
var pathReferenceReplace = referencePath + reference.file.revFilename;
if (this.options.transformPath) {
// Transform path using client supplied transformPath callback,
pathReferenceReplace = this.options.transformPath.call(
this,
pathReferenceReplace,
reference.path,
reference.file,
file
);
} else if (this.options.prefix && pathReferenceReplace[0] === "/") {
// Append with user supplied prefix
pathReferenceReplace = join_path_url(
this.options.prefix,
pathReferenceReplace
);
}
if (this.shouldUpdateReference(reference.file)) {
// The extention should remain constant so we dont add extentions to references without extentions
var noExtReplace = path_without_ext(pathReferenceReplace);
for (var i = 0; i < annotatedContent.length; i++) {
for (var j = 0; j < reference.regExps.length; j++) {
this.options.replacer(
annotatedContent[i],
reference.regExps[j],
noExtReplace,
reference.file
);
}
}
}
}
contents = annotatedContent
.map(function (annotation) {
return annotation.contents;
})
.join("");
file.contents = Buffer.from(contents);
};
/**
* Determines if a file should be renamed based on dontRenameFile supplied in options.
*/
Revisioner.prototype.shouldFileBeRenamed = function (file) {
var filename = get_relative_path(file.base, file.revPathOriginal);
for (var i = this.options.dontGlobal.length; i--; ) {
var regex =
this.options.dontGlobal[i] instanceof RegExp
? this.options.dontGlobal[i]
: new RegExp(this.options.dontGlobal[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
for (i = this.options.dontRenameFile.length; i--; ) {
regex =
this.options.dontRenameFile[i] instanceof RegExp
? this.options.dontRenameFile[i]
: new RegExp(this.options.dontRenameFile[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
return true;
};
/**
* Determines if a particular reference should be updated across assets based on dontUpdateReference supplied in options.
*/
Revisioner.prototype.shouldUpdateReference = function (file) {
var filename = get_relative_path(file.base, file.revPathOriginal);
for (var i = this.options.dontGlobal.length; i--; ) {
var regex =
this.options.dontGlobal[i] instanceof RegExp
? this.options.dontGlobal[i]
: new RegExp(this.options.dontGlobal[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
for (i = this.options.dontUpdateReference.length; i--; ) {
regex =
this.options.dontUpdateReference[i] instanceof RegExp
? this.options.dontUpdateReference[i]
: new RegExp(this.options.dontUpdateReference[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
return true;
};
/**
* Determines if a particular reference should be updated across assets based on dontUpdateReference supplied in options.
*/
Revisioner.prototype.shouldSearchFile = function (file) {
var filename = get_relative_path(file.base, file.revPathOriginal);
for (var i = this.options.dontGlobal.length; i--; ) {
var regex =
this.options.dontGlobal[i] instanceof RegExp
? this.options.dontGlobal[i]
: new RegExp(this.options.dontGlobal[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
for (i = this.options.dontSearchFile.length; i--; ) {
regex =
this.options.dontSearchFile[i] instanceof RegExp
? this.options.dontSearchFile[i]
: new RegExp(this.options.dontSearchFile[i] + "$", "ig");
if (filename.match(regex)) {
return false;
}
}
return true;
};
export default Revisioner;