-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathnpm.ts
337 lines (310 loc) · 11 KB
/
npm.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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// TODO: types (#22198)
import is from '@sindresorhus/is';
import semver from 'semver';
import upath from 'upath';
import { GlobalConfig } from '../../../../config/global';
import {
SYSTEM_INSUFFICIENT_DISK_SPACE,
TEMPORARY_ERROR,
} from '../../../../constants/error-messages';
import { logger } from '../../../../logger';
import { exec } from '../../../../util/exec';
import type {
ExecOptions,
ExtraEnv,
ToolConstraint,
} from '../../../../util/exec/types';
import {
deleteLocalFile,
localPathExists,
readLocalFile,
renameLocalFile,
} from '../../../../util/fs';
import { minimatch } from '../../../../util/minimatch';
import { Result } from '../../../../util/result';
import { trimSlashes } from '../../../../util/url';
import type { PostUpdateConfig, Upgrade } from '../../types';
import { PackageLock } from '../schema';
import { composeLockFile, parseLockFile } from '../utils';
import { getNodeToolConstraint } from './node-version';
import type { GenerateLockFileResult } from './types';
import { getPackageManagerVersion, lazyLoadPackageJson } from './utils';
async function getNpmConstraintFromPackageLock(
lockFileDir: string,
filename: string,
): Promise<string | null> {
const packageLockFileName = upath.join(lockFileDir, filename);
const packageLockContents = await readLocalFile(packageLockFileName, 'utf8');
const packageLockJson = Result.parse(
packageLockContents,
PackageLock,
).unwrapOrNull();
if (!packageLockJson) {
logger.debug(`Could not parse ${packageLockFileName}`);
return null;
}
const { lockfileVersion } = packageLockJson;
if (lockfileVersion === 1) {
logger.debug(`Using npm constraint <7 for lockfileVersion=1`);
return `<7`;
}
if (lockfileVersion === 2) {
logger.debug(`Using npm constraint <9 for lockfileVersion=2`);
return `<9`;
}
logger.debug(
`Using npm constraint >=9 for lockfileVersion=${lockfileVersion}`,
);
return `>=9`;
}
export async function generateLockFile(
lockFileDir: string,
env: NodeJS.ProcessEnv,
filename: string,
config: Partial<PostUpdateConfig> = {},
upgrades: Upgrade[] = [],
): Promise<GenerateLockFileResult> {
// TODO: don't assume package-lock.json is in the same directory
const lockFileName = upath.join(lockFileDir, filename);
logger.debug(`Spawning npm install to create ${lockFileDir}/${filename}`);
const { skipInstalls, postUpdateOptions } = config;
let lockFile: string | null = null;
try {
const lazyPkgJson = lazyLoadPackageJson(lockFileDir);
const npmToolConstraint: ToolConstraint = {
toolName: 'npm',
constraint:
config.constraints?.npm ??
getPackageManagerVersion('npm', await lazyPkgJson.getValue()) ??
(await getNpmConstraintFromPackageLock(lockFileDir, filename)) ??
null,
};
const supportsPreferDedupeFlag =
!npmToolConstraint.constraint ||
semver.intersects('>=7.0.0', npmToolConstraint.constraint);
const commands: string[] = [];
let cmdOptions = '';
if (
(postUpdateOptions?.includes('npmDedupe') === true &&
!supportsPreferDedupeFlag) ||
skipInstalls === false
) {
logger.debug('Performing node_modules install');
cmdOptions += '--no-audit';
} else {
logger.debug('Updating lock file only');
cmdOptions += '--package-lock-only --no-audit';
}
if (postUpdateOptions?.includes('npmDedupe') && supportsPreferDedupeFlag) {
logger.debug('Deduplicate dependencies on installation');
cmdOptions += ' --prefer-dedupe';
}
if (!GlobalConfig.get('allowScripts') || config.ignoreScripts) {
cmdOptions += ' --ignore-scripts';
}
const extraEnv: ExtraEnv = {
NPM_CONFIG_CACHE: env.NPM_CONFIG_CACHE,
npm_config_store: env.npm_config_store,
};
const execOptions: ExecOptions = {
cwdFile: lockFileName,
userConfiguredEnv: config.env,
extraEnv,
toolConstraints: [
await getNodeToolConstraint(config, upgrades, lockFileDir, lazyPkgJson),
npmToolConstraint,
],
docker: {},
};
// istanbul ignore if
if (GlobalConfig.get('exposeAllEnv')) {
extraEnv.NPM_AUTH = env.NPM_AUTH;
extraEnv.NPM_EMAIL = env.NPM_EMAIL;
}
if (!upgrades.every((upgrade) => upgrade.isLockfileUpdate)) {
// This command updates the lock file based on package.json
commands.push(`npm install ${cmdOptions}`.trim());
}
// rangeStrategy = update-lockfile
const lockUpdates = upgrades.filter((upgrade) => upgrade.isLockfileUpdate);
// divide the deps in two categories: workspace and root
const { lockRootUpdates, lockWorkspacesUpdates, workspaces, rootDeps } =
divideWorkspaceAndRootDeps(lockFileDir, lockUpdates);
if (workspaces.size && lockWorkspacesUpdates.length) {
logger.debug('Performing lockfileUpdate (npm-workspaces)');
for (const workspace of workspaces) {
const currentWorkspaceUpdates = lockWorkspacesUpdates
.filter((update) => update.workspace === workspace)
.map((update) => update.managerData?.packageKey)
.filter((packageKey) => !rootDeps.has(packageKey));
if (currentWorkspaceUpdates.length) {
const updateCmd = `npm install ${cmdOptions} --workspace=${workspace} ${currentWorkspaceUpdates.join(
' ',
)}`;
commands.push(updateCmd);
}
}
}
if (lockRootUpdates.length) {
logger.debug('Performing lockfileUpdate (npm)');
const updateCmd =
`npm install ${cmdOptions} ` +
lockRootUpdates
.map((update) => update.managerData?.packageKey)
.join(' ');
commands.push(updateCmd);
}
if (upgrades.some((upgrade) => upgrade.isRemediation)) {
// We need to run twice to get the correct lock file
commands.push(`npm install ${cmdOptions}`.trim());
}
// postUpdateOptions
if (
config.postUpdateOptions?.includes('npmDedupe') &&
!supportsPreferDedupeFlag
) {
logger.debug('Performing npm dedupe after installation');
commands.push('npm dedupe');
}
if (upgrades.find((upgrade) => upgrade.isLockFileMaintenance)) {
logger.debug(
`Removing ${lockFileName} first due to lock file maintenance upgrade`,
);
try {
await deleteLocalFile(lockFileName);
} catch (err) /* istanbul ignore next */ {
logger.debug(
{ err, lockFileName },
'Error removing `package-lock.json` for lock file maintenance',
);
}
}
// Run the commands
await exec(commands, execOptions);
// massage to shrinkwrap if necessary
if (
filename === 'npm-shrinkwrap.json' &&
(await localPathExists(upath.join(lockFileDir, 'package-lock.json')))
) {
await renameLocalFile(
upath.join(lockFileDir, 'package-lock.json'),
upath.join(lockFileDir, 'npm-shrinkwrap.json'),
);
}
// Read the result
// TODO #22198
lockFile = (await readLocalFile(
upath.join(lockFileDir, filename),
'utf8',
))!;
// Massage lockfile counterparts of package.json that were modified
// because npm install was called with an explicit version for rangeStrategy=update-lockfile
if (lockUpdates.length) {
const { detectedIndent, lockFileParsed } = parseLockFile(lockFile);
if (
lockFileParsed?.lockfileVersion === 2 ||
lockFileParsed?.lockfileVersion === 3
) {
lockUpdates.forEach((lockUpdate) => {
const depType = lockUpdate.depType as
| 'dependencies'
| 'optionalDependencies';
// TODO #22198
if (
lockFileParsed.packages?.['']?.[depType]?.[lockUpdate.packageName!]
) {
lockFileParsed.packages[''][depType][lockUpdate.packageName!] =
lockUpdate.newValue!;
}
});
lockFile = composeLockFile(lockFileParsed, detectedIndent);
}
}
} catch (err) /* istanbul ignore next */ {
if (err.message === TEMPORARY_ERROR) {
throw err;
}
logger.debug(
{
err,
type: 'npm',
},
'lock file error',
);
if (err.stderr?.includes('ENOSPC: no space left on device')) {
throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);
}
return { error: true, stderr: err.stderr };
}
return { error: !lockFile, lockFile };
}
export function divideWorkspaceAndRootDeps(
lockFileDir: string,
lockUpdates: Upgrade[],
): {
lockRootUpdates: Upgrade[];
lockWorkspacesUpdates: Upgrade[];
workspaces: Set<string>;
rootDeps: Set<string>;
} {
const lockRootUpdates: Upgrade[] = []; // stores all upgrades which are present in root package.json
const lockWorkspacesUpdates: Upgrade[] = []; // stores all upgrades which are present in workspaces package.json
const workspaces = new Set<string>(); // name of all workspaces
const rootDeps = new Set<string>(); // packageName of all upgrades in root package.json (makes it check duplicate deps in root)
// divide the deps in two categories: workspace and root
for (const upgrade of lockUpdates) {
upgrade.managerData ??= {};
upgrade.managerData.packageKey = generatePackageKey(
upgrade.packageName!,
upgrade.newVersion!,
);
if (
upgrade.managerData.workspacesPackages?.length &&
is.string(upgrade.packageFile)
) {
const workspacePatterns = upgrade.managerData.workspacesPackages; // glob pattern or directory name/path
const packageFileDir = trimSlashes(
upgrade.packageFile.replace('package.json', ''),
);
// workspaceDir = packageFileDir - lockFileDir
const workspaceDir = trimSlashes(packageFileDir.replace(lockFileDir, ''));
if (is.nonEmptyString(workspaceDir)) {
let workspaceName: string | undefined;
// compare workspaceDir to workspace patterns
// stop when the first match is found and
// add workspaceDir to workspaces set and upgrade object
for (const workspacePattern of workspacePatterns) {
const massagedPattern = (workspacePattern as string).replace(
/^\.\//,
'',
);
if (minimatch(massagedPattern).match(workspaceDir)) {
workspaceName = workspaceDir;
break;
}
}
if (workspaceName) {
if (
!rootDeps.has(upgrade.managerData.packageKey) // prevent same dep from existing in root and workspace
) {
workspaces.add(workspaceName);
upgrade.workspace = workspaceName;
lockWorkspacesUpdates.push(upgrade);
}
} else {
logger.warn(
{ workspacePatterns, workspaceDir },
'workspaceDir not found',
);
}
continue;
}
}
lockRootUpdates.push(upgrade);
rootDeps.add(upgrade.managerData.packageKey);
}
return { lockRootUpdates, lockWorkspacesUpdates, workspaces, rootDeps };
}
function generatePackageKey(packageName: string, version: string): string {
return `${packageName}@${version}`;
}