forked from sindresorhus/gulp-rev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (63 loc) · 1.69 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
'use strict';
var crypto = require('crypto');
var path = require('path');
var gutil = require('gulp-util');
var through = require('through2');
function md5(str) {
return crypto.createHash('md5').update(str, 'utf8').digest('hex');
}
function relPath(base, filePath) {
if (filePath.indexOf(base) !== 0) {
return filePath;
}
var newPath = filePath.substr(base.length);
if (newPath[0] === path.sep) {
return newPath.substr(1);
} else {
return newPath;
}
}
var plugin = function () {
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-rev', 'Streaming not supported'));
return cb();
}
// save the old path for later
file.revOrigPath = file.path;
file.revOrigBase = file.base;
var hash = md5(file.contents.toString()).slice(0, 8);
var ext = path.extname(file.path);
var filename = path.basename(file.path, ext) + '-' + hash + ext;
file.path = path.join(path.dirname(file.path), filename);
this.push(file);
cb();
});
};
plugin.manifest = function () {
var manifest = {};
var firstFile = null;
return through.obj(function (file, enc, cb) {
// ignore all non-rev'd files
if (file.path && file.revOrigPath) {
firstFile = firstFile || file;
manifest[relPath(firstFile.revOrigBase, file.revOrigPath)] = relPath(firstFile.base, file.path);
}
cb();
}, function (cb) {
if (firstFile) {
this.push(new gutil.File({
cwd: firstFile.cwd,
base: firstFile.base,
path: path.join(firstFile.base, 'rev-manifest.json'),
contents: new Buffer(JSON.stringify(manifest, null, ' '))
}));
}
cb();
});
};
module.exports = plugin;