-
Notifications
You must be signed in to change notification settings - Fork 10
/
zopfli.js
80 lines (66 loc) · 2.23 KB
/
zopfli.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
var execFile = require('child_process').execFile;
var shellEscape = require('shellwords').escape;
var statSync = require('fs').statSync;
module.exports = function(grunt) {
var zopfli = function(filePath, options, callback) {
var args = [
'-c',
'--i' + options.iterations,
options.format == 'gzip' ? '--gzip'
: options.format == 'deflate' ? '--deflate'
: '--zlib',
filePath
];
if (options.splitLast) {
args.unshift('--splitlast');
};
execFile('zopfli', args, function(error, stdout, stderr) {
callback.call(this, error || stderr, stdout);
});
};
grunt.registerMultiTask('zopfli', 'Compress files using Zopfli.', function() {
var done = this.async();
// Merge task-specific and/or target-specific options with these defaults:
var options = this.options({
'report': true, // show original and compressed size
'iterations': 15, // min value: 1; (undocumented) max value: 99999999999
'format': 'gzip', // 'gzip', 'zlib', 'deflate'
'splitLast': false // perform block splitting first instead of last
});
// Double-check options
if (options.iterations < 1 || options.iterations > 99999999999) {
// invalid `iterations` value given; fall back to the default
options.iterations = 15;
}
if (['gzip', 'zlib', 'deflate'].indexOf(options.format) == -1) {
// invalid `format` value given; fall back to the default
options.format = 'gzip';
}
// Iterate over all specified file groups
this.files.forEach(function(file) {
var srcPath = file.src[0];
var destPath = file.dest;
// Warn on invalid source files
if (!grunt.file.exists(srcPath)) {
grunt.log.warn('Source file `' + srcPath + '` not found.');
}
// Compress the file
zopfli(srcPath, options, function(error, stdout) {
if (error) {
grunt.log.warn(error);
done(false);
}
// Write the destination file
grunt.file.write(destPath, stdout);
// Print a success message
grunt.log.writeln('File `' + destPath + '` created.');
// Print file size info
if (options.report) {
grunt.log.writeln('Original: ' + String(statSync(srcPath).size).green + ' bytes.');
grunt.log.writeln('Compressed: ' + String(stdout.length).green + ' bytes.');
}
done();
});
});
});
};