This repository was archived by the owner on Mar 26, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathfilerev.js
64 lines (55 loc) · 2.07 KB
/
filerev.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
'use strict';
var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var chalk = require('chalk');
var eachAsync = require('each-async');
module.exports = function (grunt) {
grunt.registerMultiTask('filerev', 'File revisioning based on content hashing', function () {
var options = this.options({
encoding: 'utf8',
algorithm: 'md5',
length: 8,
copy: null
});
var target = this.target;
var filerev = grunt.filerev || {summary: {}};
eachAsync(this.files, function (el, i, next) {
// If dest is furnished it should indicate a directory
if (el.dest) {
// When globbing is used, el.dest contains basename, we remove it
if(el.orig.expand) {
el.dest = path.dirname(el.dest);
}
try {
var stat = fs.lstatSync(el.dest);
if (stat && !stat.isDirectory()) {
grunt.fail.fatal('Destination for target %s is not a directory', target);
}
} catch (err) {
grunt.log.writeln('Destination dir ' + el.dest + ' does not exists for target ' + target + ': creating');
grunt.file.mkdir(el.dest);
}
}
el.src.forEach(function (file) {
var dirname;
var hash = crypto.createHash(options.algorithm).update(grunt.file.read(file), options.encoding).digest('hex');
var suffix = hash.slice(0, options.length);
var ext = path.extname(file);
var newName = [path.basename(file, ext), suffix, ext.slice(1)].join('.');
var resultPath;
dirname = el.dest ? el.dest : path.dirname(file);
resultPath = path.resolve(dirname, newName);
if (options.copy || (options.copy === null && el.dest)) {
grunt.file.copy(file, resultPath);
} else {
fs.renameSync(file, resultPath);
}
filerev.summary[path.normalize(file)] = path.join(dirname, newName);
grunt.log.writeln(chalk.green('✔ ') + file + chalk.gray(' changed to ') + newName);
});
next();
}, this.async());
grunt.filerev = filerev;
});
};