-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathrev.js
53 lines (42 loc) · 1.36 KB
/
rev.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
/*
* grunt-rev
* https://github.com/cbas/grunt-rev
*
* Copyright (c) 2013 Sebastiaan Deckers
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs'),
path = require('path'),
crypto = require('crypto');
module.exports = function(grunt) {
function md5(filepath, algorithm, encoding, fileEncoding) {
var hash = crypto.createHash(algorithm);
grunt.log.verbose.write('Hashing ' + filepath + '...');
hash.update(grunt.file.read(filepath), fileEncoding);
return hash.digest(encoding);
}
grunt.registerMultiTask('rev', 'Prefix static asset file names with a content hash', function() {
var options = this.options({
encoding: 'utf8',
algorithm: 'md5',
length: 8
});
var summary = {};
this.files.forEach(function(filePair) {
filePair.src.forEach(function(f) {
var hash = md5(f, options.algorithm, 'hex', options.encoding),
prefix = hash.slice(0, options.length),
renamed = [prefix, path.basename(f)].join('.'),
outPath = path.resolve(path.dirname(f), renamed);
summary[f] = path.join(path.dirname(f), renamed);
grunt.verbose.ok().ok(hash);
fs.renameSync(f, outPath);
grunt.log.write(f + ' ').ok(renamed);
});
});
if (options.summary) {
grunt.file.write(options.summary, JSON.stringify(summary));
}
});
};