2016-10-10 03:43:44 +02:00
|
|
|
'use strict';
|
2017-08-14 05:01:11 +02:00
|
|
|
const path = require('path');
|
|
|
|
const gutil = require('gulp-util');
|
|
|
|
const through = require('through2');
|
|
|
|
const Yazl = require('yazl');
|
|
|
|
const getStream = require('get-stream');
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
module.exports = (filename, opts) => {
|
2016-10-10 03:43:44 +02:00
|
|
|
if (!filename) {
|
2017-08-14 05:01:11 +02:00
|
|
|
throw new gutil.PluginError('gulp-zip', '`filename` required');
|
2016-10-10 03:43:44 +02:00
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
opts = Object.assign({
|
|
|
|
compress: true
|
|
|
|
}, opts);
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
let firstFile;
|
|
|
|
const zip = new Yazl.ZipFile();
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
return through.obj((file, enc, cb) => {
|
2016-10-10 03:43:44 +02:00
|
|
|
if (!firstFile) {
|
|
|
|
firstFile = file;
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
// Because Windows...
|
|
|
|
const pathname = file.relative.replace(/\\/g, '/');
|
2016-10-10 03:43:44 +02:00
|
|
|
|
|
|
|
if (!pathname) {
|
|
|
|
cb();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.isNull() && file.stat && file.stat.isDirectory && file.stat.isDirectory()) {
|
|
|
|
zip.addEmptyDirectory(pathname, {
|
|
|
|
mtime: file.stat.mtime || new Date(),
|
|
|
|
mode: file.stat.mode
|
|
|
|
});
|
|
|
|
} else {
|
2017-08-14 05:01:11 +02:00
|
|
|
const stat = {
|
2016-10-10 03:43:44 +02:00
|
|
|
compress: opts.compress,
|
|
|
|
mtime: file.stat ? file.stat.mtime : new Date(),
|
|
|
|
mode: file.stat ? file.stat.mode : null
|
|
|
|
};
|
|
|
|
|
|
|
|
if (file.isStream()) {
|
|
|
|
zip.addReadStream(file.contents, pathname, stat);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (file.isBuffer()) {
|
|
|
|
zip.addBuffer(file.contents, pathname, stat);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
cb();
|
|
|
|
}, function (cb) {
|
|
|
|
if (!firstFile) {
|
|
|
|
cb();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
getStream.buffer(zip.outputStream).then(data => {
|
|
|
|
this.push(new gutil.File({
|
|
|
|
cwd: firstFile.cwd,
|
|
|
|
base: firstFile.base,
|
|
|
|
path: path.join(firstFile.base, filename),
|
|
|
|
contents: data
|
|
|
|
}));
|
2016-10-10 03:43:44 +02:00
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
cb(); // eslint-disable-line promise/no-callback-in-promise
|
|
|
|
});
|
|
|
|
|
|
|
|
zip.end();
|
2016-10-10 03:43:44 +02:00
|
|
|
});
|
|
|
|
};
|