-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
95 lines (76 loc) · 2.12 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
'use strict';
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var del = require('del');
var through = require('through2');
function revDel(options, cb) {
if (!_.isObject(options)) {
options = { oldManifest: options };
}
// Useful when testing
options.delFn = options.delFn || del;
options.dest = options.dest || '.';
options.suppress = (options.suppress !== false);
if (options.newManifest) {
options.oldManifest = options.oldManifest || path.join(options.dest, 'rev-manifest.json');
var oldManifest = getManifest(options.oldManifest, options.suppress);
var newManifest = getManifest(options.newManifest);
var oldFiles = getChanged(oldManifest, newManifest);
if (options.base) {
oldFiles = _.map(oldFiles, function (file) {
return path.join(options.dest || options.base, file);
});
}
return options.delFn(oldFiles, { force: options.force }, cb);
}
// newManifest isn't specified, return a stream
return through.obj(function (file, enc, cb) {
if (!options.base && file.base) {
options.base = file.base;
}
if (options.oldManifest) {
options.oldManifest = getManifest(options.oldManifest, options.suppress);
} else {
options.oldManifest = getManifest(path.join(options.dest, file.path), options.suppress);
}
try {
options.newManifest = JSON.parse(file.contents.toString(enc));
} catch (e) {
return cb(e);
}
revDel(options, function (err, filesDeleted) {
if (err) {
return cb(err);
}
file.revDeleted = filesDeleted;
cb(null, file);
});
});
}
function getChanged(oldObject, newObject) {
return _.reduce(oldObject, function (result, fingerprinted, path) {
if (newObject[path] !== fingerprinted) {
result.push(fingerprinted);
}
return result;
}, []);
}
function getManifest(manifest, suppress) {
if (_.isObject(manifest)) {
return manifest;
}
if (_.isString(manifest)) {
try {
return JSON.parse(fs.readFileSync(manifest));
} catch (e) {
if (suppress === true) {
return {};
} else {
throw e;
}
}
}
throw new TypeError('Manifest file must be an object or a string');
}
module.exports = revDel;