Last active
December 20, 2017 15:54
-
-
Save axetroy/f273e47f82f670399d570859e9a3067b to your computer and use it in GitHub Desktop.
supershell初稿
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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