supershell初稿

supershell.js
复制

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;

大牛们的评论:朕有话说

还没有人评论哦,赶紧抢沙发!