-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathexecute-lifecycle-script.js
311 lines (269 loc) · 9.73 KB
/
execute-lifecycle-script.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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/* @flow */
import type Config from '../config.js';
import {MessageError, ProcessTermError} from '../errors.js';
import * as constants from '../constants.js';
import * as child from './child.js';
import {exists} from './fs.js';
import {registries} from '../resolvers/index.js';
import {fixCmdWinSlashes} from './fix-cmd-win-slashes.js';
import {getBinFolder as getGlobalBinFolder, run as globalRun} from '../cli/commands/global.js';
const path = require('path');
export type LifecycleReturn = Promise<{
cwd: string,
command: string,
stdout: string,
}>;
export const IGNORE_MANIFEST_KEYS: Set<string> = new Set(['readme', 'notice', 'licenseText']);
// We treat these configs as internal, thus not expose them to process.env.
// This helps us avoid some gyp issues when building native modules.
// See https://github.com/yarnpkg/yarn/issues/2286.
const IGNORE_CONFIG_KEYS = ['lastUpdateCheck'];
const INVALID_CHAR_REGEX = /\W/g;
export async function makeEnv(
stage: string,
cwd: string,
config: Config,
): {
[key: string]: string,
} {
const env = {
NODE: process.execPath,
INIT_CWD: process.cwd(),
// This lets `process.env.NODE` to override our `process.execPath`.
// This is a bit confusing but it is how `npm` was designed so we
// try to be compatible with that.
...process.env,
};
// Merge in the `env` object specified in .yarnrc
const customEnv = config.getOption('env');
if (customEnv && typeof customEnv === 'object') {
Object.assign(env, customEnv);
}
env.npm_lifecycle_event = stage;
env.npm_node_execpath = env.NODE;
env.npm_execpath = env.npm_execpath || (process.mainModule && process.mainModule.filename);
// Set the env to production for npm compat if production mode.
// https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336
if (config.production) {
env.NODE_ENV = 'production';
}
// Note: npm_config_argv environment variable contains output of nopt - command-line
// parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684)
env.npm_config_argv = JSON.stringify({
remain: [],
cooked: config.commandName === 'run' ? [config.commandName, stage] : [config.commandName],
original: process.argv.slice(2),
});
const manifest = await config.maybeReadManifest(cwd);
if (manifest) {
if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) {
env.npm_lifecycle_script = manifest.scripts[stage];
}
// add npm_package_*
const queue = [['', manifest]];
while (queue.length) {
const [key, val] = queue.pop();
if (typeof val === 'object') {
for (const subKey in val) {
const fullKey = [key, subKey].filter(Boolean).join('_');
if (fullKey && fullKey[0] !== '_' && !IGNORE_MANIFEST_KEYS.has(fullKey)) {
queue.push([fullKey, val[subKey]]);
}
}
} else {
let cleanVal = String(val);
if (cleanVal.indexOf('\n') >= 0) {
cleanVal = JSON.stringify(cleanVal);
}
//replacing invalid chars with underscore
const cleanKey = key.replace(INVALID_CHAR_REGEX, '_');
env[`npm_package_${cleanKey}`] = cleanVal;
}
}
}
// add npm_config_* and npm_package_config_* from yarn config
const keys: Set<string> = new Set([
...Object.keys(config.registries.yarn.config),
...Object.keys(config.registries.npm.config),
]);
const cleaned = Array.from(keys)
.filter(key => !key.match(/:_/) && IGNORE_CONFIG_KEYS.indexOf(key) === -1)
.map(key => {
let val = config.getOption(key);
if (!val) {
val = '';
} else if (typeof val === 'number') {
val = '' + val;
} else if (typeof val !== 'string') {
val = JSON.stringify(val);
}
if (val.indexOf('\n') >= 0) {
val = JSON.stringify(val);
}
return [key, val];
});
// add npm_config_*
for (const [key, val] of cleaned) {
const cleanKey = key.replace(/^_+/, '');
const envKey = `npm_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');
env[envKey] = val;
}
// add npm_package_config_*
if (manifest && manifest.name) {
const packageConfigPrefix = `${manifest.name}:`;
for (const [key, val] of cleaned) {
if (key.indexOf(packageConfigPrefix) !== 0) {
continue;
}
const cleanKey = key.replace(/^_+/, '').replace(packageConfigPrefix, '');
const envKey = `npm_package_config_${cleanKey}`.replace(INVALID_CHAR_REGEX, '_');
env[envKey] = val;
}
}
// split up the path
const envPath = env[constants.ENV_PATH_KEY];
const pathParts = envPath ? envPath.split(path.delimiter) : [];
// Include the directory that contains node so that we can guarantee that the scripts
// will always run with the exact same Node release than the one use to run Yarn
pathParts.unshift(path.dirname(process.execPath));
// Include node-gyp version that was bundled with the current Node.js version,
// if available.
pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin'));
pathParts.unshift(
path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),
);
// Include node-gyp version from homebrew managed npm, if available.
pathParts.unshift(
path.join(path.dirname(process.execPath), '..', 'libexec', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin'),
);
// Add global bin folder if it is not present already, as some packages depend
// on a globally-installed version of node-gyp.
const globalBin = await getGlobalBinFolder(config, {});
if (pathParts.indexOf(globalBin) === -1) {
pathParts.unshift(globalBin);
}
// add .bin folders to PATH
for (const registry of Object.keys(registries)) {
const binFolder = path.join(config.registries[registry].folder, '.bin');
if (config.workspacesEnabled && config.workspaceRootFolder) {
pathParts.unshift(path.join(config.workspaceRootFolder, binFolder));
}
pathParts.unshift(path.join(config.linkFolder, binFolder));
pathParts.unshift(path.join(cwd, binFolder));
}
if (config.scriptsPrependNodePath) {
pathParts.unshift(path.join(path.dirname(process.execPath)));
}
// join path back together
env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);
return env;
}
export async function executeLifecycleScript({
stage,
config,
cwd,
cmd,
isInteractive,
onProgress,
customShell,
}: {
stage: string,
config: Config,
cwd: string,
cmd: string,
isInteractive?: boolean,
onProgress?: (chunk: Buffer | string) => void,
customShell?: string,
}): LifecycleReturn {
const env = await makeEnv(stage, cwd, config);
await checkForGypIfNeeded(config, cmd, env[constants.ENV_PATH_KEY].split(path.delimiter));
if (process.platform === 'win32' && (!customShell || customShell === 'cmd')) {
// handle windows run scripts starting with a relative path
cmd = fixCmdWinSlashes(cmd);
}
// By default (non-interactive), pipe everything to the terminal and run child process detached
// as long as it's not Windows (since windows does not have /dev/tty)
let stdio = ['ignore', 'pipe', 'pipe'];
let detached = process.platform !== 'win32';
if (isInteractive) {
stdio = 'inherit';
detached = false;
}
const shell = customShell || true;
const stdout = await child.spawn(cmd, [], {cwd, env, stdio, detached, shell}, onProgress);
return {cwd, command: cmd, stdout};
}
export default executeLifecycleScript;
let checkGypPromise: ?Promise<void> = null;
/**
* Special case: Some packages depend on node-gyp, but don't specify this in
* their package.json dependencies. They assume that node-gyp is available
* globally. We need to detect this case and show an error message.
*/
function checkForGypIfNeeded(config: Config, cmd: string, paths: Array<string>): Promise<void> {
if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') {
return Promise.resolve();
}
// Ensure this only runs once, rather than multiple times in parallel.
if (!checkGypPromise) {
checkGypPromise = _checkForGyp(config, paths);
}
return checkGypPromise;
}
async function _checkForGyp(config: Config, paths: Array<string>): Promise<void> {
const {reporter} = config;
// Check every directory in the PATH
const allChecks = await Promise.all(paths.map(dir => exists(path.join(dir, 'node-gyp'))));
if (allChecks.some(Boolean)) {
// node-gyp is available somewhere
return;
}
reporter.info(reporter.lang('packageRequiresNodeGyp'));
try {
await globalRun(config, reporter, {}, ['add', 'node-gyp']);
} catch (e) {
throw new MessageError(reporter.lang('nodeGypAutoInstallFailed', e.message));
}
}
export async function execFromManifest(config: Config, commandName: string, cwd: string): Promise<void> {
const pkg = await config.maybeReadManifest(cwd);
if (!pkg || !pkg.scripts) {
return;
}
const cmd: ?string = pkg.scripts[commandName];
if (cmd) {
await execCommand({stage: commandName, config, cmd, cwd, isInteractive: true});
}
}
export async function execCommand({
stage,
config,
cmd,
cwd,
isInteractive,
customShell,
}: {
stage: string,
config: Config,
cmd: string,
cwd: string,
isInteractive: boolean,
customShell?: string,
}): Promise<void> {
const {reporter} = config;
try {
reporter.command(cmd);
await executeLifecycleScript({stage, config, cwd, cmd, isInteractive, customShell});
return Promise.resolve();
} catch (err) {
if (err instanceof ProcessTermError) {
throw new MessageError(
err.EXIT_SIGNAL
? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL)
: reporter.lang('commandFailedWithCode', err.EXIT_CODE),
);
} else {
throw err;
}
}
}