-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
cli.js
99 lines (86 loc) · 2.28 KB
/
cli.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
97
98
99
/**
* External dependencies
*/
const minimist = require( 'minimist' );
const spawn = require( 'cross-spawn' );
/**
* Internal dependencies
*/
const { fromScriptsRoot, hasScriptFile, getScripts } = require( './file' );
const { exit, getArgsFromCLI } = require( './process' );
const getArgFromCLI = ( arg ) => {
for ( const cliArg of getArgsFromCLI() ) {
const [ name, value ] = cliArg.split( '=' );
if ( name === arg ) {
return value || null;
}
}
};
const hasArgInCLI = ( arg ) => getArgFromCLI( arg ) !== undefined;
const getFileArgsFromCLI = () => minimist( getArgsFromCLI() )._;
const getNodeArgsFromCLI = () => {
const args = getArgsFromCLI();
const scripts = getScripts();
const scriptIndex = args.findIndex( ( arg ) => scripts.includes( arg ) );
return {
nodeArgs: args.slice( 0, scriptIndex ),
scriptName: args[ scriptIndex ],
scriptArgs: args.slice( scriptIndex + 1 ),
};
};
const hasFileArgInCLI = () => getFileArgsFromCLI().length > 0;
const handleSignal = ( signal ) => {
if ( signal === 'SIGKILL' ) {
// eslint-disable-next-line no-console
console.log(
'The script failed because the process exited too early. ' +
'This probably means the system ran out of memory or someone called ' +
'`kill -9` on the process.'
);
} else if ( signal === 'SIGTERM' ) {
// eslint-disable-next-line no-console
console.log(
'The script failed because the process exited too early. ' +
'Someone might have called `kill` or `killall`, or the system could ' +
'be shutting down.'
);
}
exit( 1 );
};
const spawnScript = ( scriptName, args = [], nodeArgs = [] ) => {
if ( ! scriptName ) {
// eslint-disable-next-line no-console
console.log( 'Script name is missing.' );
exit( 1 );
}
if ( ! hasScriptFile( scriptName ) ) {
// eslint-disable-next-line no-console
console.log(
'Unknown script "' +
scriptName +
'". ' +
'Perhaps you need to update @wordpress/scripts?'
);
exit( 1 );
}
const { signal, status } = spawn.sync(
'node',
[ ...nodeArgs, fromScriptsRoot( scriptName ), ...args ],
{
stdio: 'inherit',
}
);
if ( signal ) {
handleSignal( signal );
}
exit( status );
};
module.exports = {
getArgFromCLI,
getArgsFromCLI,
getFileArgsFromCLI,
getNodeArgsFromCLI,
hasArgInCLI,
hasFileArgInCLI,
spawnScript,
};