pur
Version:
Alias and glob powered multi-threaded shell execution
96 lines (82 loc) • 3 kB
JavaScript
;
var _dealias = require('./dealias');
var _file = require('./file');
var _run = require('./run');
var _print = require('./print');
var glob = require('glob');
var args = process.argv.splice(2);
var configstore = require('configstore');
var conf = new configstore(require('../package.json').name);
var chalk = require('chalk');
var _ = require('underscore');
console.log(chalk.red('m') + chalk.blue('e') + chalk.green('o') + chalk.yellow('w!') + '🐱');
// Look for --save to set an alias
var newAlias = undefined;
for (var i = 0; i < args.length; i++) {
if (args[i].toLowerCase() === '--save') {
newAlias = args.splice(i, 2)[1];
break;
}
}
// First arg may be an alias, check to see if it is.
if (conf.get(args[0])) {
var paths = conf.get(args.splice(0, 1));
args = paths.concat(args);
} else if (!(0, _file.isDir)(args[0]) && conf.get('default')) {
var paths = conf.get('default');
args = paths.concat(args);
}
// Separate the paths from the arguments
var p = new Promise(function (resolve) {
// If the first argument is a directory, assume an array of directories was
// passed. Walk the arguments until a non-path is found.
if ((0, _file.isDir)(args[0])) {
var paths = [];
while (args.length > 0 && (0, _file.isDir)(args[0])) {
paths.push(args.splice(0, 1)[0]);
}
resolve(paths);
} else {
// The first argument needs to be globbed, glob it.
glob(args.splice(0, 1)[0], {}, function (er, paths) {
resolve(paths.filter(function (path) {
return fs.lstatSync(path).isDirectory();
}));
});
}
})['catch'](function (err) {
console.error('Globbing error: ', err);
process.exit(1);
// Save the path alias if specified
}).then(function (paths) {
if (newAlias) {
console.log('Saving alias ', newAlias);
conf.set(newAlias, paths);
}
// Dealiasify the first command argument.
if (args.length > 0) {
return (0, _dealias.dealias)(args.splice(0, 1)[0]).then(function (command) {
return { paths: paths, args: command.concat(args) };
});
}
})['catch'](function (err) {
console.error('Alias error: ', err);
process.exit(1);
// Execute the command across each directory asynchronously.
}).then(function (kwargs) {
var cmd = kwargs.args.splice(0, 1)[0];
kwargs.paths.forEach(function (path, index) {
(0, _print.printHeader)(index, [path, cmd, String(kwargs.args)].join(' '));
(0, _run.spawn)(cmd, kwargs.args, function (stdout) {
(0, _print.print)(index, false, stdout, path);
}, function (stdin) {
(0, _print.print)(index, false, stdin, path);
}, function (stderr) {
(0, _print.print)(index, true, stderr, path);
}, path);
});
})['catch'](function (err) {
console.error('Launching error: ', err);
process.exit(1);
});