-
Notifications
You must be signed in to change notification settings - Fork 12k
/
install-package.ts
255 lines (225 loc) · 7.41 KB
/
install-package.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { spawn, spawnSync } from 'child_process';
import { existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join, resolve } from 'path';
import * as rimraf from 'rimraf';
import { PackageManager } from '../lib/config/workspace-schema';
import { NgAddSaveDepedency } from '../utilities/package-metadata';
import { Spinner } from './spinner';
interface PackageManagerOptions {
silent: string;
saveDev: string;
install: string;
installAll?: string;
prefix: string;
noLockfile: string;
}
export async function installAllPackages(
packageManager: PackageManager = PackageManager.Npm,
extraArgs: string[] = [],
cwd = process.cwd(),
): Promise<1 | 0> {
const packageManagerArgs = getPackageManagerArguments(packageManager);
const installArgs: string[] = [];
if (packageManagerArgs.installAll) {
installArgs.push(packageManagerArgs.installAll);
}
installArgs.push(packageManagerArgs.silent);
const spinner = new Spinner();
spinner.start('Installing packages...');
const bufferedOutput: { stream: NodeJS.WriteStream; data: Buffer }[] = [];
return new Promise((resolve, reject) => {
const childProcess = spawn(packageManager, [...installArgs, ...extraArgs], {
stdio: 'pipe',
shell: true,
cwd,
}).on('close', (code: number) => {
if (code === 0) {
spinner.succeed('Packages successfully installed.');
resolve(0);
} else {
spinner.stop();
bufferedOutput.forEach(({ stream, data }) => stream.write(data));
spinner.fail('Package install failed, see above.');
reject(1);
}
});
childProcess.stdout?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stdout, data: data }),
);
childProcess.stderr?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stderr, data: data }),
);
});
}
export async function installPackage(
packageName: string,
packageManager: PackageManager = PackageManager.Npm,
save: Exclude<NgAddSaveDepedency, false> = true,
extraArgs: string[] = [],
cwd = process.cwd(),
): Promise<1 | 0> {
const packageManagerArgs = getPackageManagerArguments(packageManager);
const installArgs: string[] = [
packageManagerArgs.install,
packageName,
packageManagerArgs.silent,
];
const spinner = new Spinner();
spinner.start('Installing package...');
if (save === 'devDependencies') {
installArgs.push(packageManagerArgs.saveDev);
}
const bufferedOutput: { stream: NodeJS.WriteStream; data: Buffer }[] = [];
return new Promise((resolve, reject) => {
const childProcess = spawn(packageManager, [...installArgs, ...extraArgs], {
stdio: 'pipe',
shell: true,
cwd,
}).on('close', (code: number) => {
if (code === 0) {
spinner.succeed('Package successfully installed.');
resolve(0);
} else {
spinner.stop();
bufferedOutput.forEach(({ stream, data }) => stream.write(data));
spinner.fail('Package install failed, see above.');
reject(1);
}
});
childProcess.stdout?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stdout, data: data }),
);
childProcess.stderr?.on('data', (data: Buffer) =>
bufferedOutput.push({ stream: process.stderr, data: data }),
);
});
}
export async function installTempPackage(
packageName: string,
packageManager: PackageManager = PackageManager.Npm,
extraArgs?: string[],
): Promise<{
status: 1 | 0;
tempNodeModules: string;
}> {
const tempPath = mkdtempSync(join(realpathSync(tmpdir()), 'angular-cli-packages-'));
// clean up temp directory on process exit
process.on('exit', () => {
try {
rimraf.sync(tempPath);
} catch {}
});
// NPM will warn when a `package.json` is not found in the install directory
// Example:
// npm WARN enoent ENOENT: no such file or directory, open '/tmp/.ng-temp-packages-84Qi7y/package.json'
// npm WARN .ng-temp-packages-84Qi7y No description
// npm WARN .ng-temp-packages-84Qi7y No repository field.
// npm WARN .ng-temp-packages-84Qi7y No license field.
// While we can use `npm init -y` we will end up needing to update the 'package.json' anyways
// because of missing fields.
writeFileSync(
join(tempPath, 'package.json'),
JSON.stringify({
name: 'temp-cli-install',
description: 'temp-cli-install',
repository: 'temp-cli-install',
license: 'MIT',
}),
);
// setup prefix/global modules path
const packageManagerArgs = getPackageManagerArguments(packageManager);
const tempNodeModules = join(tempPath, 'node_modules');
// Yarn will not append 'node_modules' to the path
const prefixPath = packageManager === PackageManager.Yarn ? tempNodeModules : tempPath;
const installArgs: string[] = [
...(extraArgs || []),
`${packageManagerArgs.prefix}="${prefixPath}"`,
packageManagerArgs.noLockfile,
];
return {
status: await installPackage(packageName, packageManager, true, installArgs, tempPath),
tempNodeModules,
};
}
export async function runTempPackageBin(
packageName: string,
packageManager: PackageManager = PackageManager.Npm,
args: string[] = [],
): Promise<number> {
const { status: code, tempNodeModules } = await installTempPackage(packageName, packageManager);
if (code !== 0) {
return code;
}
// Remove version/tag etc... from package name
// Ex: @angular/cli@latest -> @angular/cli
const packageNameNoVersion = packageName.substring(0, packageName.lastIndexOf('@'));
const pkgLocation = join(tempNodeModules, packageNameNoVersion);
const packageJsonPath = join(pkgLocation, 'package.json');
// Get a binary location for this package
let binPath: string | undefined;
if (existsSync(packageJsonPath)) {
const content = readFileSync(packageJsonPath, 'utf-8');
if (content) {
const { bin = {} } = JSON.parse(content);
const binKeys = Object.keys(bin);
if (binKeys.length) {
binPath = resolve(pkgLocation, bin[binKeys[0]]);
}
}
}
if (!binPath) {
throw new Error(`Cannot locate bin for temporary package: ${packageNameNoVersion}.`);
}
const argv = [binPath, ...args];
const { status, error } = spawnSync('node', argv, {
stdio: 'inherit',
shell: true,
env: {
...process.env,
NG_DISABLE_VERSION_CHECK: 'true',
NG_CLI_ANALYTICS: 'false',
},
});
if (status === null && error) {
throw error;
}
return status || 0;
}
function getPackageManagerArguments(packageManager: PackageManager): PackageManagerOptions {
switch (packageManager) {
case PackageManager.Yarn:
return {
silent: '--silent',
saveDev: '--dev',
install: 'add',
prefix: '--modules-folder',
noLockfile: '--no-lockfile',
};
case PackageManager.Pnpm:
return {
silent: '--silent',
saveDev: '--save-dev',
install: 'add',
installAll: 'install',
prefix: '--prefix',
noLockfile: '--no-lockfile',
};
default:
return {
silent: '--quiet',
saveDev: '--save-dev',
install: 'install',
installAll: 'install',
prefix: '--prefix',
noLockfile: '--no-package-lock',
};
}
}