forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.ts
More file actions
225 lines (194 loc) · 6.72 KB
/
process.ts
File metadata and controls
225 lines (194 loc) · 6.72 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import * as child_process from 'child_process';
import {blue, yellow} from 'chalk';
import {Subject, Observable} from 'rxjs';
import {getGlobalVariable} from './env';
import {rimraf} from './fs';
import {wait} from './utils';
const treeKill = require('tree-kill');
interface ExecOptions {
silent?: boolean;
waitForMatch?: RegExp;
}
let _processes: child_process.ChildProcess[] = [];
export type ProcessOutput = {
stdout: string;
stderr: string;
};
function _exec(options: ExecOptions, cmd: string, args: string[]): Promise<ProcessOutput> {
let stdout = '';
let stderr = '';
const cwd = process.cwd();
console.log(
`==========================================================================================`
);
args = args.filter(x => x !== undefined);
const flags = [
options.silent && 'silent',
options.waitForMatch && `matching(${options.waitForMatch})`
]
.filter(x => !!x) // Remove false and undefined.
.join(', ')
.replace(/^(.+)$/, ' [$1]'); // Proper formatting.
console.log(blue(`Running \`${cmd} ${args.map(x => `"${x}"`).join(' ')}\`${flags}...`));
console.log(blue(`CWD: ${cwd}`));
const spawnOptions: any = {cwd};
if (process.platform.startsWith('win')) {
args.unshift('/c', cmd);
cmd = 'cmd.exe';
spawnOptions['stdio'] = 'pipe';
}
const childProcess = child_process.spawn(cmd, args, spawnOptions);
childProcess.stdout.on('data', (data: Buffer) => {
stdout += data.toString('utf-8');
if (options.silent) {
return;
}
data.toString('utf-8')
.split(/[\n\r]+/)
.filter(line => line !== '')
.forEach(line => console.log(' ' + line));
});
childProcess.stderr.on('data', (data: Buffer) => {
stderr += data.toString('utf-8');
if (options.silent) {
return;
}
data.toString('utf-8')
.split(/[\n\r]+/)
.filter(line => line !== '')
.forEach(line => console.error(yellow(' ' + line)));
});
_processes.push(childProcess);
// Create the error here so the stack shows who called this function.
const err = new Error(`Running "${cmd} ${args.join(' ')}" returned error code `);
return new Promise((resolve, reject) => {
childProcess.on('exit', (error: any) => {
_processes = _processes.filter(p => p !== childProcess);
if (!error) {
resolve({ stdout, stderr });
} else {
err.message += `${error}...\n\nSTDOUT:\n${stdout}\n\nSTDERR:\n${stderr}\n`;
reject(err);
}
});
if (options.waitForMatch) {
childProcess.stdout.on('data', (data: Buffer) => {
if (data.toString().match(options.waitForMatch)) {
resolve({ stdout, stderr });
}
});
childProcess.stderr.on('data', (data: Buffer) => {
if (data.toString().match(options.waitForMatch)) {
resolve({ stdout, stderr });
}
});
}
});
}
export function waitForAnyProcessOutputToMatch(match: RegExp,
timeout = 30000): Promise<ProcessOutput> {
// Race between _all_ processes, and the timeout. First one to resolve/reject wins.
const timeoutPromise: Promise<ProcessOutput> = new Promise((_resolve, reject) => {
// Wait for 30 seconds and timeout.
setTimeout(() => {
reject(new Error(`Waiting for ${match} timed out (timeout: ${timeout}msec)...`));
}, timeout);
});
const matchPromises: Promise<ProcessOutput>[] = _processes.map(
childProcess => new Promise(resolve => {
let stdout = '';
let stderr = '';
childProcess.stdout.on('data', (data: Buffer) => {
stdout += data.toString();
if (data.toString().match(match)) {
resolve({ stdout, stderr });
}
});
childProcess.stderr.on('data', (data: Buffer) => {
stderr += data.toString();
if (data.toString().match(match)) {
resolve({ stdout, stderr });
}
});
}));
return Promise.race(matchPromises.concat([timeoutPromise]));
}
export function killAllProcesses(signal = 'SIGTERM') {
_processes.forEach(process => treeKill(process.pid, signal));
_processes = [];
}
export function exec(cmd: string, ...args: string[]) {
return _exec({}, cmd, args);
}
export function silentExec(cmd: string, ...args: string[]) {
return _exec({ silent: true }, cmd, args);
}
export function execAndWaitForOutputToMatch(cmd: string, args: string[], match: RegExp) {
if (cmd === 'ng' && args[0] === 'serve') {
// Accept matches up to 20 times after the initial match.
// Useful because the Webpack watcher can rebuild a few times due to files changes that
// happened just before the build (e.g. `git clean`).
// This seems to be due to host file system differences, see
// https://nodejs.org/docs/latest/api/fs.html#fs_caveats
return Observable.fromPromise(_exec({ waitForMatch: match }, cmd, args))
.concat(
Observable.defer(() =>
Observable.fromPromise(waitForAnyProcessOutputToMatch(match, 2500))
.repeat(20)
.catch(_x => Observable.empty())
)
)
.takeLast(1)
.toPromise();
} else {
return _exec({ waitForMatch: match }, cmd, args);
}
}
let npmInstalledEject = false;
export function ng(...args: string[]) {
const argv = getGlobalVariable('argv');
const maybeSilentNg = argv['nosilent'] ? noSilentNg : silentNg;
if (['build', 'serve', 'test', 'e2e', 'xi18n'].indexOf(args[0]) != -1) {
// If we have the --eject, use webpack for the test.
if (args[0] == 'build' && argv.eject) {
return maybeSilentNg('eject', ...args.slice(1), '--force')
.then(() => {
if (!npmInstalledEject) {
npmInstalledEject = true;
// We need to run npm install on the first eject.
return silentNpm('install');
}
})
.then(() => rimraf('dist'))
.then(() => _exec({silent: true}, 'node_modules/.bin/webpack', []));
} else if (args[0] == 'e2e') {
// Wait 1 second before running any end-to-end test.
return new Promise(resolve => setTimeout(resolve, 1000))
.then(() => maybeSilentNg(...args));
}
return maybeSilentNg(...args);
} else {
return noSilentNg(...args);
}
}
export function noSilentNg(...args: string[]) {
return _exec({}, 'ng', args);
}
export function silentNg(...args: string[]) {
return _exec({silent: true}, 'ng', args);
}
export function silentNpm(...args: string[]) {
return _exec({silent: true}, 'npm', args);
}
export function npm(...args: string[]) {
return _exec({}, 'npm', args);
}
export function node(...args: string[]) {
return _exec({}, 'node', args);
}
export function git(...args: string[]) {
return _exec({}, 'git', args);
}
export function silentGit(...args: string[]) {
return _exec({silent: true}, 'git', args);
}