Skip to content

Instantly share code, notes, and snippets.

@axetroy
Last active Dec 20, 2017
Embed
What would you like to do?
supershell初稿
const { spawn, exec } = require('child_process');
const COMMAND = Symbol('command');
class Shell {
constructor(command) {
this[COMMAND] = [command];
}
}
const run = new Proxy(
{},
{
get: function(nil, command, receiver) {
let shell = new Shell(command); // key is command here
const proxy = new Proxy(shell, {
get: function(target, argv, _receiver) {
const commands = shell[COMMAND].filter(
v => typeof v === 'string' && ['valueOf', 'toString'].indexOf(v) < 0
).map(v => v);
switch (argv) {
case '$$flag':
return function() {
const args = [].slice.call(arguments);
for (let i = 0; i < args.length; i++) {
shell[COMMAND].push(args[i]);
}
return proxy;
};
break;
case '$$exec':
shell[COMMAND] = [];
return function(cb, options = {}) {
exec(commands.join(' '), options, cb);
};
break;
case '$$spawn':
shell[COMMAND] = [];
return function(options = {}) {
return spawn(commands.shift(), commands, options);
};
break;
default:
shell[COMMAND].push(argv);
return proxy;
}
}
});
return proxy;
}
}
);
module.exports = run;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment