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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
/*jslint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
var through2 = require('through2');
var PluginError = require('plugin-error');
var fancyLog = require('fancy-log');
var colors = require('ansi-colors');
var utils = require('./lib/utils');
var compress = require('./lib/compress.js');
var PLUGIN_NAME = 'gulp-gzip';
module.exports = function (options) {
// Combine user defined options with default options
var defaultConfig = {
append: true,
threshold: false,
gzipOptions: {},
skipGrowingFiles: false
};
var config = utils.merge(defaultConfig, options);
// Create a through2 object stream. This is our plugin export
var stream = through2.obj(gulpGzip);
// Expose the config so we can test it
stream.config = config;
function gulpGzip(file, enc, done) {
/*jshint validthis: true */
var self = this;
// Check for empty file
if (file.isNull()) {
// Pass along the empty file to the next plugin
self.push(file);
done();
return;
}
// Call when finished with compression
var finished = function(err, contents, wasCompressed) {
if (err) {
var error = new PluginError(PLUGIN_NAME, err, { showStack: true });
self.emit('error', error);
done();
return;
}
var complete = function() {
file.contents = contents;
self.push(file);
done();
};
var getFixedPath = function(filepath) {
if (config.extension) {
filepath += '.' + config.extension;
} else if (config.preExtension) {
filepath = filepath.replace(/(\.[^\.]+)$/, '.' + config.preExtension + '$1');
} else if (config.append) {
filepath += '.gz';
}
return filepath;
};
if (wasCompressed) {
if (file.contentEncoding) {
file.contentEncoding.push('gzip');
} else {
file.contentEncoding = [ 'gzip' ];
}
file.path = getFixedPath(file.path);
complete();
} else if (config.deleteMode) {
var cwd = path.resolve(config.deleteModeCwd || process.cwd());
var directory = typeof config.deleteMode === 'string' ? config.deleteMode : config.deleteMode(file);
var filepath = path.resolve(cwd, directory, getFixedPath(file.relative));
fs.exists(filepath, function(exists) {
if(exists) {
fancyLog(colors.green('Gzipped file ' + filepath + ' deleted'));
fs.unlink(filepath, complete);
} else {
complete();
}
});
} else {
complete();
}
return;
};
compress(file.contents, config, finished);
}
return stream;
};
|