-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
815 lines (787 loc) · 25.8 KB
/
index.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import is from '@sindresorhus/is';
import { parseSyml } from '@yarnpkg/parsers';
import upath from 'upath';
import { SYSTEM_INSUFFICIENT_DISK_SPACE } from '../../../constants/error-messages';
import { id as npmId } from '../../../datasource/npm';
import { logger } from '../../../logger';
import { ExternalHostError } from '../../../types/errors/external-host-error';
import { getChildProcessEnv } from '../../../util/exec/env';
import {
deleteLocalFile,
ensureDir,
getSubDirectory,
outputFile,
readFile,
remove,
unlink,
writeFile,
} from '../../../util/fs';
import { branchExists, getFile, getRepoStatus } from '../../../util/git';
import * as hostRules from '../../../util/host-rules';
import type { PackageFile, PostUpdateConfig, Upgrade } from '../../types';
import * as lerna from './lerna';
import * as npm from './npm';
import * as pnpm from './pnpm';
import * as yarn from './yarn';
// Strips empty values, deduplicates, and returns the directories from filenames
// istanbul ignore next
const getDirs = (arr: string[]): string[] =>
Array.from(new Set(arr.filter(Boolean)));
export interface DetermineLockFileDirsResult {
yarnLockDirs: string[];
npmLockDirs: string[];
pnpmShrinkwrapDirs: string[];
lernaJsonFiles: string[];
}
// istanbul ignore next
export function determineLockFileDirs(
config: PostUpdateConfig,
packageFiles: AdditionalPackageFiles
): DetermineLockFileDirsResult {
const npmLockDirs = [];
const yarnLockDirs = [];
const pnpmShrinkwrapDirs = [];
const lernaJsonFiles = [];
for (const upgrade of config.upgrades) {
if (upgrade.updateType === 'lockFileMaintenance' || upgrade.isRemediation) {
// Return every directory that contains a lockfile
if (upgrade.managerData?.lernaJsonFile && upgrade.npmLock) {
lernaJsonFiles.push(upgrade.managerData.lernaJsonFile);
} else {
yarnLockDirs.push(upgrade.yarnLock);
npmLockDirs.push(upgrade.npmLock);
pnpmShrinkwrapDirs.push(upgrade.pnpmShrinkwrap);
}
continue; // eslint-disable-line no-continue
}
if (upgrade.isLockfileUpdate) {
yarnLockDirs.push(upgrade.yarnLock);
npmLockDirs.push(upgrade.npmLock);
}
}
if (
config.upgrades.every(
(upgrade: Upgrade) =>
upgrade.updateType === 'lockFileMaintenance' || upgrade.isLockfileUpdate
)
) {
return {
yarnLockDirs: getDirs(yarnLockDirs),
npmLockDirs: getDirs(npmLockDirs),
pnpmShrinkwrapDirs: getDirs(pnpmShrinkwrapDirs),
lernaJsonFiles: getDirs(lernaJsonFiles),
};
}
function getPackageFile(fileName: string): Partial<PackageFile> {
logger.trace('Looking for packageFile: ' + fileName);
for (const packageFile of packageFiles.npm) {
if (packageFile.packageFile === fileName) {
logger.trace({ packageFile }, 'Found packageFile');
return packageFile;
}
logger.trace('No match');
}
return {};
}
for (const p of config.updatedPackageFiles) {
logger.trace(`Checking ${String(p.name)} for lock files`);
const packageFile = getPackageFile(p.name);
// lerna first
if (packageFile.managerData?.lernaJsonFile && packageFile.npmLock) {
logger.debug(`${packageFile.packageFile} has lerna lock file`);
lernaJsonFiles.push(packageFile.managerData.lernaJsonFile);
} else if (
packageFile.managerData?.lernaJsonFile &&
packageFile.yarnLock &&
!packageFile.hasYarnWorkspaces
) {
lernaJsonFiles.push(packageFile.managerData.lernaJsonFile);
} else {
// push full lock file names and convert them later
yarnLockDirs.push(packageFile.yarnLock);
npmLockDirs.push(packageFile.npmLock);
pnpmShrinkwrapDirs.push(packageFile.pnpmShrinkwrap);
}
}
return {
yarnLockDirs: getDirs(yarnLockDirs),
npmLockDirs: getDirs(npmLockDirs),
pnpmShrinkwrapDirs: getDirs(pnpmShrinkwrapDirs),
lernaJsonFiles: getDirs(lernaJsonFiles),
};
}
// istanbul ignore next
export async function writeExistingFiles(
config: PostUpdateConfig,
packageFiles: AdditionalPackageFiles
): Promise<void> {
if (!packageFiles.npm) {
return;
}
const npmFiles = packageFiles.npm;
logger.debug(
{ packageFiles: npmFiles.map((n) => n.packageFile) },
'Writing package.json files'
);
for (const packageFile of npmFiles) {
const basedir = upath.join(
config.localDir,
upath.dirname(packageFile.packageFile)
);
const npmrc: string = packageFile.npmrc || config.npmrc;
const npmrcFilename = upath.join(basedir, '.npmrc');
if (is.string(npmrc)) {
await outputFile(npmrcFilename, `${npmrc}\n`);
}
if (packageFile.yarnrc) {
logger.debug(`Writing .yarnrc to ${basedir}`);
const yarnrcFilename = upath.join(basedir, '.yarnrc');
await outputFile(
yarnrcFilename,
packageFile.yarnrc
.replace('--install.pure-lockfile true', '')
.replace('--install.frozen-lockfile true', '')
);
}
const { npmLock } = packageFile;
if (npmLock) {
const npmLockPath = upath.join(config.localDir, npmLock);
if (
process.env.RENOVATE_REUSE_PACKAGE_LOCK === 'false' ||
config.reuseLockFiles === false
) {
logger.debug(`Ensuring ${npmLock} is removed`);
await remove(npmLockPath);
} else {
logger.debug(`Writing ${npmLock}`);
let existingNpmLock = await getFile(npmLock);
const widens = [];
for (const upgrade of config.upgrades) {
if (
upgrade.rangeStrategy === 'widen' &&
upgrade.npmLock === npmLock
) {
widens.push(upgrade.depName);
}
}
if (widens.length) {
logger.debug(
`Removing ${String(widens)} from ${npmLock} to force an update`
);
try {
const npmLockParsed = JSON.parse(existingNpmLock);
if (npmLockParsed.dependencies) {
widens.forEach((depName) => {
delete npmLockParsed.dependencies[depName];
});
}
existingNpmLock = JSON.stringify(npmLockParsed, null, 2);
} catch (err) {
logger.warn(
{ npmLock },
'Error massaging package-lock.json for widen'
);
}
}
await outputFile(npmLockPath, existingNpmLock);
}
}
const { yarnLock } = packageFile;
if (yarnLock && config.reuseLockFiles === false) {
await deleteLocalFile(yarnLock);
}
// istanbul ignore next
if (packageFile.pnpmShrinkwrap && config.reuseLockFiles === false) {
await deleteLocalFile(packageFile.pnpmShrinkwrap);
}
}
}
// istanbul ignore next
export async function writeUpdatedPackageFiles(
config: PostUpdateConfig
): Promise<void> {
logger.trace({ config }, 'writeUpdatedPackageFiles');
logger.debug('Writing any updated package files');
if (!config.updatedPackageFiles) {
logger.debug('No files found');
return;
}
for (const packageFile of config.updatedPackageFiles) {
if (packageFile.name.endsWith('package-lock.json')) {
logger.debug(`Writing package-lock file: ${packageFile.name}`);
await outputFile(
upath.join(config.localDir, packageFile.name),
packageFile.contents
);
continue; // eslint-disable-line
}
if (!packageFile.name.endsWith('package.json')) {
continue; // eslint-disable-line
}
logger.debug(`Writing ${String(packageFile.name)}`);
const massagedFile = JSON.parse(packageFile.contents.toString());
try {
const { token } = hostRules.find({
hostType: config.platform,
url: 'https://api.github.com/',
});
for (const upgrade of config.upgrades) {
if (upgrade.gitRef && upgrade.packageFile === packageFile.name) {
massagedFile[upgrade.depType][upgrade.depName] = massagedFile[
upgrade.depType
][upgrade.depName].replace(
'git+https://github.com',
`git+https://${token}@github.com`
);
}
}
} catch (err) {
logger.warn({ err }, 'Error adding token to package files');
}
await outputFile(
upath.join(config.localDir, packageFile.name),
JSON.stringify(massagedFile)
);
}
}
export interface AdditionalPackageFiles {
npm?: Partial<PackageFile>[];
}
interface ArtifactError {
lockFile: string;
stderr: string;
}
interface UpdatedArtifacts {
name: string;
contents: string | Buffer;
}
// istanbul ignore next
async function getNpmrcContent(dir: string): Promise<string | null> {
const npmrcFilePath = upath.join(dir, '.npmrc');
let originalNpmrcContent = null;
try {
originalNpmrcContent = await readFile(npmrcFilePath, 'utf8');
logger.debug('npmrc file found in repository');
} catch {
logger.debug('No npmrc file found in repository');
originalNpmrcContent = null;
}
return originalNpmrcContent;
}
// istanbul ignore next
async function updateNpmrcContent(
dir: string,
originalContent: string,
additionalLines: string[]
): Promise<void> {
const npmrcFilePath = upath.join(dir, '.npmrc');
const newNpmrc = originalContent
? [originalContent, ...additionalLines]
: additionalLines;
const newContent = newNpmrc.join('\n');
if (newContent !== originalContent) {
logger.debug(`Writing updated .npmrc file to ${npmrcFilePath}`);
await writeFile(npmrcFilePath, `${newContent}\n`);
}
}
// istanbul ignore next
async function resetNpmrcContent(
dir: string,
originalContent: string
): Promise<void> {
const npmrcFilePath = upath.join(dir, '.npmrc');
if (originalContent) {
try {
await writeFile(npmrcFilePath, originalContent);
} catch {
logger.warn('Unable to reset npmrc to original contents');
}
} else {
try {
await unlink(npmrcFilePath);
} catch {
logger.warn('Unable to delete custom npmrc');
}
}
}
// istanbul ignore next
async function updateYarnOffline(
lockFileDir: string,
localDir: string,
updatedArtifacts: UpdatedArtifacts[]
): Promise<void> {
try {
const resolvedPaths: string[] = [];
const yarnrcYml = await getFile(upath.join(lockFileDir, '.yarnrc.yml'));
const yarnrc = await getFile(upath.join(lockFileDir, '.yarnrc'));
// As .yarnrc.yml overrides .yarnrc in Yarn 1 (https://git.io/JUcco)
// both files may exist, so check for .yarnrc.yml first
if (yarnrcYml) {
// Yarn 2 (offline cache and zero-installs)
const config = parseSyml(yarnrcYml);
resolvedPaths.push(
upath.join(lockFileDir, config.cacheFolder || './.yarn/cache')
);
resolvedPaths.push(upath.join(lockFileDir, '.pnp'));
if (config.pnpDataPath) {
resolvedPaths.push(upath.join(lockFileDir, config.pnpDataPath));
}
} else if (yarnrc) {
// Yarn 1 (offline mirror)
const mirrorLine = yarnrc
.split('\n')
.find((line) => line.startsWith('yarn-offline-mirror '));
if (mirrorLine) {
const mirrorPath = mirrorLine
.split(' ')[1]
.replace(/"/g, '')
.replace(/\/?$/, '/');
resolvedPaths.push(upath.join(lockFileDir, mirrorPath));
}
}
logger.debug({ resolvedPaths }, 'updateYarnOffline resolvedPaths');
if (resolvedPaths.length) {
const status = await getRepoStatus();
for (const f of status.modified.concat(status.not_added)) {
if (resolvedPaths.some((p) => f.startsWith(p))) {
const localModified = upath.join(localDir, f);
updatedArtifacts.push({
name: f,
contents: await readFile(localModified),
});
}
}
for (const f of status.deleted || []) {
if (resolvedPaths.some((p) => f.startsWith(p))) {
updatedArtifacts.push({
name: '|delete|',
contents: f,
});
}
}
}
} catch (err) {
logger.error({ err }, 'Error updating yarn offline packages');
}
}
export interface WriteExistingFilesResult {
artifactErrors: ArtifactError[];
updatedArtifacts: UpdatedArtifacts[];
}
// istanbul ignore next
export async function getAdditionalFiles(
config: PostUpdateConfig,
packageFiles: AdditionalPackageFiles
): Promise<WriteExistingFilesResult> {
logger.trace({ config }, 'getAdditionalFiles');
const artifactErrors: ArtifactError[] = [];
const updatedArtifacts: UpdatedArtifacts[] = [];
if (!packageFiles.npm?.length) {
return { artifactErrors, updatedArtifacts };
}
if (!config.updateLockFiles) {
logger.debug('Skipping lock file generation');
return { artifactErrors, updatedArtifacts };
}
if (
!config.updatedPackageFiles?.length &&
config.upgrades?.every((upgrade) => upgrade.isRemediation)
) {
logger.debug('Skipping lock file generation for remediations');
return { artifactErrors, updatedArtifacts };
}
logger.debug('Getting updated lock files');
if (
config.updateType === 'lockFileMaintenance' &&
config.reuseExistingBranch &&
branchExists(config.branchName)
) {
logger.debug('Skipping lockFileMaintenance update');
return { artifactErrors, updatedArtifacts };
}
const dirs = determineLockFileDirs(config, packageFiles);
logger.trace({ dirs }, 'lock file dirs');
await writeExistingFiles(config, packageFiles);
await writeUpdatedPackageFiles(config);
// Determine the additional npmrc content to add based on host rules
const additionalNpmrcContent = [];
const npmHostRules = hostRules.findAll({
hostType: 'npm',
});
for (const hostRule of npmHostRules) {
if (hostRule.token) {
if (hostRule.baseUrl) {
additionalNpmrcContent.push(
`${hostRule.baseUrl}:_authToken=${hostRule.token}`
.replace('https://', '//')
.replace('http://', '//')
);
} else if (hostRule.hostName) {
additionalNpmrcContent.push(
`//${hostRule.hostName}/:_authToken=${hostRule.token}`
);
}
} else if (is.string(hostRule.username) && is.string(hostRule.password)) {
const password = Buffer.from(hostRule.password).toString('base64');
if (hostRule.baseUrl) {
const uri = hostRule.baseUrl.replace(/^https?:/, '');
additionalNpmrcContent.push(`${uri}:username=${hostRule.username}`);
additionalNpmrcContent.push(`${uri}:_password=${password}`);
} else if (hostRule.hostName) {
const uri = `//${hostRule.hostName}/`;
additionalNpmrcContent.push(`${uri}:username=${hostRule.username}`);
additionalNpmrcContent.push(`${uri}:_password=${password}`);
}
}
}
const env = getChildProcessEnv([
'NPM_CONFIG_CACHE',
'YARN_CACHE_FOLDER',
'npm_config_store',
]);
env.NPM_CONFIG_CACHE =
env.NPM_CONFIG_CACHE || upath.join(config.cacheDir, './others/npm');
await ensureDir(env.NPM_CONFIG_CACHE);
env.YARN_CACHE_FOLDER =
env.YARN_CACHE_FOLDER || upath.join(config.cacheDir, './others/yarn');
await ensureDir(env.YARN_CACHE_FOLDER);
env.npm_config_store =
env.npm_config_store || upath.join(config.cacheDir, './others/pnpm');
await ensureDir(env.npm_config_store);
env.NODE_ENV = 'dev';
let token = '';
try {
({ token } = hostRules.find({
hostType: config.platform,
url: 'https://api.github.com/',
}));
token += '@';
} catch (err) {
logger.warn({ err }, 'Error getting token for packageFile');
}
for (const npmLock of dirs.npmLockDirs) {
const lockFileDir = upath.dirname(npmLock);
const fullLockFileDir = upath.join(config.localDir, lockFileDir);
const npmrcContent = await getNpmrcContent(fullLockFileDir);
await updateNpmrcContent(
fullLockFileDir,
npmrcContent,
additionalNpmrcContent
);
const fileName = upath.basename(npmLock);
logger.debug(`Generating ${fileName} for ${lockFileDir}`);
const upgrades = config.upgrades.filter(
(upgrade) => upgrade.npmLock === npmLock
);
const res = await npm.generateLockFile(
fullLockFileDir,
env,
fileName,
config,
upgrades
);
if (res.error) {
// istanbul ignore if
if (res.stderr?.includes('No matching version found for')) {
for (const upgrade of config.upgrades) {
if (
res.stderr.includes(
`No matching version found for ${upgrade.depName}`
)
) {
logger.debug(
{ dependency: upgrade.depName, type: 'npm' },
'lock file failed for the dependency being updated - skipping branch creation'
);
const err = new Error(
'lock file failed for the dependency being updated - skipping branch creation'
);
throw new ExternalHostError(err, npmId);
}
}
}
artifactErrors.push({
lockFile: npmLock,
stderr: res.stderr,
});
} else {
const existingContent = await getFile(
npmLock,
config.reuseExistingBranch ? config.branchName : config.baseBranch
);
if (res.lockFile === existingContent) {
logger.debug(`${npmLock} hasn't changed`);
} else {
logger.debug(`${npmLock} needs updating`);
updatedArtifacts.push({
name: npmLock,
contents: res.lockFile.replace(new RegExp(`${token}`, 'g'), ''),
});
}
}
await resetNpmrcContent(fullLockFileDir, npmrcContent);
}
for (const yarnLock of dirs.yarnLockDirs) {
const lockFileDir = upath.dirname(yarnLock);
const fullLockFileDir = upath.join(config.localDir, lockFileDir);
const npmrcContent = await getNpmrcContent(fullLockFileDir);
await updateNpmrcContent(
fullLockFileDir,
npmrcContent,
additionalNpmrcContent
);
logger.debug(`Generating yarn.lock for ${lockFileDir}`);
const lockFileName = upath.join(lockFileDir, 'yarn.lock');
const upgrades = config.upgrades.filter(
(upgrade) => upgrade.yarnLock === yarnLock
);
const res = await yarn.generateLockFile(
upath.join(config.localDir, lockFileDir),
env,
config,
upgrades
);
if (res.error) {
// istanbul ignore if
if (res.stderr?.includes(`Couldn't find any versions for`)) {
for (const upgrade of config.upgrades) {
/* eslint-disable no-useless-escape */
if (
res.stderr.includes(
`Couldn't find any versions for \\\"${upgrade.depName}\\\"`
)
) {
logger.debug(
{ dependency: upgrade.depName, type: 'yarn' },
'lock file failed for the dependency being updated - skipping branch creation'
);
throw new ExternalHostError(
new Error(
'lock file failed for the dependency being updated - skipping branch creation'
),
npmId
);
}
/* eslint-enable no-useless-escape */
}
}
artifactErrors.push({
lockFile: yarnLock,
stderr: res.stderr,
});
} else {
const existingContent = await getFile(
lockFileName,
config.reuseExistingBranch ? config.branchName : config.baseBranch
);
if (res.lockFile === existingContent) {
logger.debug("yarn.lock hasn't changed");
} else {
logger.debug('yarn.lock needs updating');
updatedArtifacts.push({
name: lockFileName,
contents: res.lockFile,
});
await updateYarnOffline(lockFileDir, config.localDir, updatedArtifacts);
}
}
await resetNpmrcContent(fullLockFileDir, npmrcContent);
}
for (const pnpmShrinkwrap of dirs.pnpmShrinkwrapDirs) {
const lockFileDir = upath.dirname(pnpmShrinkwrap);
const fullLockFileDir = upath.join(config.localDir, lockFileDir);
const npmrcContent = await getNpmrcContent(fullLockFileDir);
await updateNpmrcContent(
fullLockFileDir,
npmrcContent,
additionalNpmrcContent
);
logger.debug(`Generating pnpm-lock.yaml for ${lockFileDir}`);
const upgrades = config.upgrades.filter(
(upgrade) => upgrade.pnpmShrinkwrap === pnpmShrinkwrap
);
const res = await pnpm.generateLockFile(
upath.join(config.localDir, lockFileDir),
env,
config,
upgrades
);
if (res.error) {
// istanbul ignore if
if (res.stdout?.includes(`No compatible version found:`)) {
for (const upgrade of config.upgrades) {
if (
res.stdout.includes(
`No compatible version found: ${upgrade.depName}`
)
) {
logger.debug(
{ dependency: upgrade.depName, type: 'pnpm' },
'lock file failed for the dependency being updated - skipping branch creation'
);
throw new ExternalHostError(
Error(
'lock file failed for the dependency being updated - skipping branch creation'
),
npmId
);
}
}
}
artifactErrors.push({
lockFile: pnpmShrinkwrap,
stderr: res.stderr,
});
} else {
const existingContent = await getFile(
pnpmShrinkwrap,
config.reuseExistingBranch ? config.branchName : config.baseBranch
);
if (res.lockFile === existingContent) {
logger.debug("pnpm-lock.yaml hasn't changed");
} else {
logger.debug('pnpm-lock.yaml needs updating');
updatedArtifacts.push({
name: pnpmShrinkwrap,
contents: res.lockFile,
});
}
}
await resetNpmrcContent(fullLockFileDir, npmrcContent);
}
for (const lernaJsonFile of dirs.lernaJsonFiles) {
let lockFile: string;
logger.debug(`Finding package.json for lerna location "${lernaJsonFile}"`);
const lernaPackageFile = packageFiles.npm.find(
(p) => getSubDirectory(p.packageFile) === getSubDirectory(lernaJsonFile)
);
if (!lernaPackageFile) {
logger.debug('No matching package.json found');
throw new Error('lerna-no-lockfile');
}
if (lernaPackageFile.lernaClient === 'npm') {
lockFile = config.npmLock || 'package-lock.json';
} else {
lockFile = config.yarnLock || 'yarn.lock';
}
const skipInstalls =
lockFile === 'npm-shrinkwrap.json' ? false : config.skipInstalls;
const fullLearnaFileDir = upath.join(
config.localDir,
getSubDirectory(lernaJsonFile)
);
const npmrcContent = await getNpmrcContent(fullLearnaFileDir);
await updateNpmrcContent(
fullLearnaFileDir,
npmrcContent,
additionalNpmrcContent
);
const res = await lerna.generateLockFiles(
lernaPackageFile,
fullLearnaFileDir,
config,
env,
skipInstalls
);
// istanbul ignore else
if (res.stderr) {
// istanbul ignore if
if (res.stderr.includes('ENOSPC: no space left on device')) {
throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);
}
for (const upgrade of config.upgrades) {
/* eslint-disable no-useless-escape */
if (
res.stderr.includes(
`Couldn't find any versions for \\\"${upgrade.depName}\\\"`
)
) {
logger.debug(
{ dependency: upgrade.depName, type: 'yarn' },
'lock file failed for the dependency being updated - skipping branch creation'
);
throw new ExternalHostError(
Error(
'lock file failed for the dependency being updated - skipping branch creation'
),
npmId
);
}
/* eslint-enable no-useless-escape */
if (
res.stderr.includes(
`No matching version found for ${upgrade.depName}`
)
) {
logger.debug(
{ dependency: upgrade.depName, type: 'npm' },
'lock file failed for the dependency being updated - skipping branch creation'
);
throw new ExternalHostError(
Error(
'lock file failed for the dependency being updated - skipping branch creation'
),
npmId
);
}
}
artifactErrors.push({
lockFile,
stderr: res.stderr,
});
} else {
for (const packageFile of packageFiles.npm) {
const filename = packageFile.npmLock || packageFile.yarnLock;
logger.trace('Checking for ' + filename);
const existingContent = await getFile(
filename,
config.reuseExistingBranch ? config.branchName : config.baseBranch
);
if (existingContent) {
logger.trace('Found lock file');
const lockFilePath = upath.join(config.localDir, filename);
logger.trace('Checking against ' + lockFilePath);
try {
let newContent: string;
try {
newContent = await readFile(lockFilePath, 'utf8');
} catch (err) {
newContent = await readFile(
lockFilePath.replace(
'npm-shrinkwrap.json',
'package-lock.json'
),
'utf8'
);
}
if (newContent === existingContent) {
logger.trace('File is unchanged');
} else {
logger.debug('File is updated: ' + lockFilePath);
updatedArtifacts.push({
name: filename,
contents: newContent,
});
}
} catch (err) {
if (config.updateType === 'lockFileMaintenance') {
logger.debug(
{ packageFile, lockFilePath },
'No lock file found after lerna lockFileMaintenance'
);
} else {
logger.warn(
{ packageFile, lockFilePath },
'No lock file found after lerna bootstrap'
);
}
}
} else {
logger.trace('No lock file found');
}
}
}
await resetNpmrcContent(fullLearnaFileDir, npmrcContent);
}
return { artifactErrors, updatedArtifacts };
}