all files / lib/common/command/ index.js

27.27% Statements 6/22
0% Branches 0/6
33.33% Functions 1/3
27.27% Lines 6/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61    1× 1× 1× 1×             1×                                                                                             1×  
'use strict';
 
const child   = require('child_process');
const Promise = require('bluebird');
const colors  = require('colors');
const path    = require('path');
 
/**
 * Class for running spawning commands
 */
class Command {
  constructor(sqz) {
    this.sqz = sqz;
  }
 
  /**
   *
   * @param bin
   * @param args
   */
  run(description, bin, args, noExit) {
    return new Promise((resolve, reject) => {
      const normalizedBin = path.normalize(bin);
      this.sqz.cli.log.info(`Executing command: ${colors.blue.bold(description)}`);
      process.stdout.write(`\n$ ${normalizedBin} ${args.join(' ')}\n`);
 
      process.stdout.write('\n');
 
      const exec = child.spawn(normalizedBin, args, {
        shell  : true,
        stderr : 'inherit',
        stdio  : 'inherit',
        stdin  : 'inherit'
      });
 
      exec.on('close', (code) => {
        if (code !== 0 && !noExit) {
          reject(`command exit code ${code}`);
        } else {
          process.stdout.write('\n');
          resolve(code);
        }
      });
    });
  }
 
  bulk(commands) {
    return new Promise((resolve) => {
      Promise.each(Object.keys(commands), (key) => {
        const command = commands[key];
 
        return this.run(command.description, command.bin, command.args || []);
      }).then(() => {
        resolve();
      });
    });
  }
}
 
module.exports = Command;