gulp-choose-files
Version:
Gulp plugin that prompts you to choose the files to pass through the stream.
53 lines (44 loc) • 1.27 kB
JavaScript
;
const through = require('through2');
const { prompt } = require('enquirer');
const fileKey = (file, options) => {
if (typeof options.key === 'string') return file[options.key];
if (typeof options.key === 'function') return options.key(file);
return file.relative;
};
module.exports = options => {
const opts = Object.assign({ key: 'relative' }, options);
const message = opts.message || 'Which files do you want to write?';
const predefined = [].concat(opts.paths || []);
const choices = [];
const files = {};
return through.obj((file, enc, next) => {
if (opts.skip) {
next(null, file);
return;
}
let key = fileKey(file, opts);
if (predefined.length && predefined.includes(key)) {
next(null, file);
return;
}
if (!predefined.length) {
choices.push(key);
files[key] = file;
}
next();
}, function(next) {
if (!choices.length) {
next();
return;
}
prompt({ type: 'multiselect', name: 'paths', message, choices, ...options })
.then(answers => {
if (answers.paths && answers.paths.length) {
answers.paths.forEach(filename => this.push(files[filename]));
}
next();
})
.catch(next);
});
};