1 | 'use strict';
|
2 |
|
3 | const log = require('npmlog');
|
4 | const execa = require('execa');
|
5 | const Bluebird = require('bluebird');
|
6 | const util = require('util');
|
7 | const EventEmitter = require('events').EventEmitter;
|
8 | const spawnargs = require('spawn-args');
|
9 | const extend = require('lodash.assignin');
|
10 |
|
11 | const envWithLocalPath = require('./utils/env-with-local-path');
|
12 | const fileutils = require('./utils/fileutils');
|
13 | const Process = require('./utils/process');
|
14 |
|
15 | const fileExists = fileutils.fileExists;
|
16 | const executableExists = fileutils.executableExists;
|
17 |
|
18 |
|
19 | module.exports = class ProcessCtl extends EventEmitter {
|
20 | constructor(name, config, options) {
|
21 | super();
|
22 |
|
23 | options = options || {};
|
24 |
|
25 | this.name = name;
|
26 | this.config = config;
|
27 | this.killTimeout = options.killTimeout || 5000;
|
28 | }
|
29 |
|
30 | prepareOptions(options) {
|
31 | let defaults = {
|
32 | env: envWithLocalPath(this.config)
|
33 | };
|
34 |
|
35 | return extend({}, defaults, options);
|
36 | }
|
37 |
|
38 | _spawn(exe, args, options) {
|
39 | log.info('spawning: ' + exe + ' - ' + util.inspect(args));
|
40 | let p = new Process(this.name, { killTimeout: this.killTimeout }, execa(exe, args, options));
|
41 | this.emit('processStarted', p);
|
42 | return Bluebird.resolve(p);
|
43 | }
|
44 |
|
45 | spawn(exe, args, options) {
|
46 | let _options = this.prepareOptions(options);
|
47 |
|
48 | if (Array.isArray(exe)) {
|
49 | return Bluebird.reduce(exe, (found, exe) => {
|
50 | if (found) {
|
51 | return found;
|
52 | }
|
53 |
|
54 | return this.exeExists(exe, _options).then(exists => {
|
55 | if (exists) {
|
56 | return exe;
|
57 | }
|
58 | });
|
59 | }, false).then(found => {
|
60 | if (!found) {
|
61 | throw new Error('No executable found in: ' + util.inspect(exe));
|
62 | }
|
63 |
|
64 | return this._spawn(found, args, _options);
|
65 | });
|
66 | }
|
67 |
|
68 | return this._spawn(exe, args, _options);
|
69 | }
|
70 |
|
71 | exec(cmd, options) {
|
72 | log.info('executing: ' + cmd);
|
73 | let cmdParts = spawnargs(cmd);
|
74 | let exe = cmdParts[0];
|
75 | let args = cmdParts.slice(1);
|
76 |
|
77 | options = options || {};
|
78 | options.shell = true;
|
79 |
|
80 | return this.spawn(exe, args, options);
|
81 | }
|
82 |
|
83 | exeExists(exe, options) {
|
84 | return fileExists(exe).then(exists => {
|
85 | if (exists) {
|
86 | return exists;
|
87 | }
|
88 |
|
89 | return executableExists(exe, options);
|
90 | });
|
91 | }
|
92 | };
|