-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
96 lines (74 loc) · 2.68 KB
/
index.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const spawn = require( 'child_process' ).spawn;
const platform = require( 'os' ).platform;
const splitToObject = require( 'split-cmd' ).splitToObject;
if ( ! Helper ) {
var Helper = require( 'codeceptjs/lib/helper' );
}
/**
* Command helper
*
* @author Thiago Delgado Pinto
*/
class CmdHelper extends Helper {
/**
* Constructor
*
* @param {object} config Configuration declared in the CodeceptJS configuration file.
*/
constructor( config ) {
super( config );
const defaultOptions = {
options: {
// spawn() options
// stdio: 'inherit', // <<< not working on windows!
shell: true,
// additional options
showOutput: true
}
};
// Attributes
this.options = Object.assign( defaultOptions, config ); // Copy from config
}
/**
* Executes the given command.
*
* @param {string} command Command to execute.
* @param {object} [options] Same options as in NodeJS' spawn(), plus `showOutput: boolean`. Optional. Default is `{ shell: true, showOutput: true }`.
*
* @returns {Promise< number >} Promise with the returning execution status code (0 means success).
*/
runCommand( command, options ) {
if ( 'string' !== typeof command ) {
throw new Error( 'Command must be a string' );
}
if ( [ 'object', 'undefined', 'null' ].indexOf( typeof options ) < 0 ) {
throw new Error( 'Options must be an object, undefined or null.' );
}
let opt = Object.assign( this.options.options || {}, options );
const showOutput = opt.showOutput;
// Removes 'showOutput' from options, because it is not accepted by spawn()
opt.showOutput = undefined;
// Fix problem with spawn() on Windows OSes
if ( 'win32' === platform() ) {
opt[ 'shell' ] = true;
}
const cmdObj = splitToObject( command );
return new Promise( ( resolve, reject ) => {
const child = spawn( cmdObj.command, cmdObj.args, opt );
child.stdout.on( 'data', ( chunk ) => {
if ( showOutput && ( chunk !== undefined && chunk !== null ) ) {
console.log( chunk.toString() );
}
} );
child.stderr.on( 'data', ( chunk ) => {
if ( showOutput && ( chunk !== undefined && chunk !== null ) ) {
console.warn( chunk.toString() );
}
} );
child.on( 'exit', ( code ) => {
resolve( code );
} );
} );
}
}
module.exports = CmdHelper;