All files / lib shell.ts

31.82% Statements 14/44
20.59% Branches 7/34
70% Functions 7/10
30.77% Lines 12/39
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 62 63 64 65  1x 1x 1x   2x 1x     1x 1x     1x 1x 1x               1x                                                                                  
import { IShell, IShellRunOptions } from '../definitions';
import { FatalException } from './errors';
import { runcmd } from './utils/shell';

export class Shell implements IShell {
  async exists(command: string): Promise<boolean> {
    try {
      await runcmd('type', [command]);
    } catch (e) {
      if (Array.isArray(e)) {
        return false;
      }
 
      throw e;
    }
 
    return true;
  }

  async run(command: string, args?: string[], options: IShellRunOptions = {}): Promise<string> {
    if (typeof options.show === 'undefined') {
      options.show = true;
    }
 
    if (typeof options.fatal === 'undefined') {
      options.fatal = true;
    }

    if (options.show) {
      console.log(`\n> ${command} ${args && args.length > 0 ? args.join(' ') : ''}\n`);
    }

    try {
      const out = await runcmd(command, args, options);

      if (options.stdio === 'inherit') {
        process.stdout.write('\n');
      }

      return out;
    } catch (e) {
      if (e.code === 'ENOENT') {
        throw new FatalException(`Command not found: ${command}`, 127);
      }
 
      if (!Array.isArray(e)) {
        throw e;
      }

      let [code, err] = e;
 
      if (options.fatal) {
        if (options.show) {
          const helpLine = options.stdio === 'inherit' ? '.\n' : (err ? `:\n\n${err}` : ' with no output.\n');
          throw new FatalException(`An error occurred while running the above command (exit code ${code})` + helpLine, code);
        } else {
          throw new FatalException(`Subprocess (${command}) encountered an error (exit code ${code}).`, code);
        }
      }
 
      throw e;
    }
  }
}