-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
execute-lifecycle-script.js
192 lines (159 loc) · 5.66 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
/* @flow */
import type {ReporterSpinner} from '../reporters/types.js';
import type Config from '../config.js';
import {MessageError, SpawnError} from '../errors.js';
import * as constants from '../constants.js';
import * as child from './child.js';
import {registries} from '../resolvers/index.js';
const path = require('path');
export type LifecycleReturn = Promise<{
cwd: string,
command: string,
stdout: string,
}>;
const IGNORE_MANIFEST_KEYS = ['readme'];
// 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'];
async function makeEnv(stage: string, cwd: string, config: Config): {
[key: string]: string
} {
const env = Object.assign({}, process.env);
env.npm_lifecycle_event = stage;
env.npm_node_execpath = env.NODE || process.execPath;
env.npm_execpath = path.join(__dirname, '..', '..', 'bin', 'yarn.js');
// 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], original: [config.commandName]});
// add npm_package_*
const manifest = await config.maybeReadManifest(cwd);
if (manifest) {
const queue = [['', manifest]];
while (queue.length) {
const [key, val] = queue.pop();
if (key[0] === '_') {
continue;
}
if (typeof val === 'object') {
for (const subKey in val) {
const completeKey = [key, subKey]
.filter((part: ?string): boolean => !!part)
.join('_');
queue.push([completeKey, val[subKey]]);
}
} else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) {
let cleanVal = String(val);
if (cleanVal.indexOf('\n') >= 0) {
cleanVal = JSON.stringify(cleanVal);
}
env[`npm_package_${key}`] = cleanVal;
}
}
}
// add npm_config_*
const keys: Set<string> = new Set([
...Object.keys(config.registries.yarn.config),
...Object.keys(config.registries.npm.config),
]);
for (const key of keys) {
if (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) {
continue;
}
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);
}
const cleanKey = key.replace(/^_+/, '');
const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_');
env[envKey] = val;
}
return env;
}
export async function executeLifecycleScript(
stage: string,
config: Config,
cwd: string,
cmd: string,
spinner?: ReporterSpinner,
): LifecycleReturn {
// if we don't have a spinner then pipe everything to the terminal
const stdio = spinner ? undefined : 'inherit';
const env = await makeEnv(stage, cwd, config);
// split up the path
const pathParts = (env[constants.ENV_PATH_KEY] || '').split(path.delimiter);
// add node-gyp
pathParts.unshift(path.join(__dirname, '..', '..', 'bin', 'node-gyp-bin'));
// add .bin folders to PATH
for (const registry of Object.keys(registries)) {
const binFolder = path.join(config.registries[registry].folder, '.bin');
pathParts.unshift(path.join(config.linkFolder, binFolder));
pathParts.unshift(path.join(cwd, binFolder));
}
// join path back together
env[constants.ENV_PATH_KEY] = pathParts.join(path.delimiter);
// get shell
const conf = {windowsVerbatimArguments: false};
let sh = 'sh';
let shFlag = '-c';
if (process.platform === 'win32') {
// cmd or command.com
sh = process.env.comspec || 'cmd';
// d - Ignore registry AutoRun commands
// s - Strip " quote characters from command.
// c - Run Command and then terminate
shFlag = '/d /s /c';
// handle quotes properly in windows environments - https://github.com/nodejs/node/issues/5060
conf.windowsVerbatimArguments = true;
}
const stdout = await child.spawn(sh, [shFlag, cmd], {cwd, env, stdio, ...conf}, (data) => {
if (spinner) {
const line = data.toString() // turn buffer into string
.trim() // trim whitespace
.split('\n') // split into lines
.pop() // use only the last line
.replace(/\t/g, ' '); // change tabs to spaces as they can interfere with the console
if (line) {
spinner.tick(line);
}
}
});
return {cwd, command: cmd, stdout};
}
export default executeLifecycleScript;
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(commandName, config, cmd, cwd);
}
}
export async function execCommand(stage: string, config: Config, cmd: string, cwd: string): Promise<void> {
const {reporter} = config;
try {
reporter.command(cmd);
await executeLifecycleScript(stage, config, cwd, cmd);
return Promise.resolve();
} catch (err) {
if (err instanceof SpawnError) {
throw new MessageError(reporter.lang('commandFailed', err.EXIT_CODE));
} else {
throw err;
}
}
}