-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (79 loc) · 2.29 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
'use strict';
var mkdirp = require('mkdirp');
var path = require('path');
var bust = require('gulp-buster');
var fs = require('fs');
var minimatch = require('minimatch');
module.exports = function hash(gulp, conf) {
conf = conf || {};
conf.gwd = conf.gwd || process.cwd();
conf.glob = conf.glob || '**/*.*';
conf.symbol = conf.symbol || '.';
conf.preservePath = conf.preservePath || true;
conf.md5Length = conf.md5Length || 7;
if (conf.copy) {
if (typeof conf.copy === 'string') {
conf.copy = [conf.copy];
}
}
function copyMatch(asset) {
var match = false;
if (!conf.copy) {
return false;
}
conf.copy.forEach(function(glob) {
if (minimatch(asset, glob)) {
match = true;
}
});
return match;
}
return function(cb) {
bust.config({
algo: 'md5',
length: conf.md5Length
});
gulp.src(conf.glob, {
cwd: conf.cwd
})
.pipe(bust(path.relative(conf.gwd, conf.hash)))
.pipe(gulp.dest('.'))
.on('end', function() {
var hash;
try {
hash = require(conf.hash);
delete require.cache[conf.hash];
} catch (e) {
hash = {};
}
var hashMap = {};
Object.keys(hash).forEach(function(c) {
if (conf.mapping === 'dev' || copyMatch(c)) {
hashMap['/' + c] = '/' + c;
} else {
var loc = '/';
if (conf.preservePath) {
loc += c.substr(0, (c.length - path.extname(c).length)) + conf.symbol + hash[c] + path.extname(c);
} else {
loc += hash[c] + path.extname(c);
// split into a 2 char length leading subdirectory
loc = loc.substr(0, 3) + '/' + loc.substr(3);
}
hashMap['/' + c] = loc;
}
});
fs.writeFileSync(conf.hash, JSON.stringify(hashMap, 0, 2));
var hashes = Object.keys(hashMap);
if (hashes.length) {
hashes.forEach(function(c) {
if (conf.verbose) {
console.log(hashMap[c]);
}
mkdirp.sync(path.dirname(path.join(conf.output, hashMap[c])));
fs.writeFileSync(path.join(conf.output, hashMap[c]), fs.readFileSync(path.join(conf.cwd, c)));
});
}
cb();
});
};
};