-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathindex.ts
830 lines (810 loc) · 28 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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
import is from '@sindresorhus/is';
import { DateTime } from 'luxon';
import { GlobalConfig } from '../../../../config/global';
import type { RenovateConfig } from '../../../../config/types';
import {
CONFIG_VALIDATION,
MANAGER_LOCKFILE_ERROR,
PLATFORM_AUTHENTICATION_ERROR,
PLATFORM_BAD_CREDENTIALS,
PLATFORM_INTEGRATION_UNAUTHORIZED,
PLATFORM_RATE_LIMIT_EXCEEDED,
REPOSITORY_CHANGED,
SYSTEM_INSUFFICIENT_DISK_SPACE,
TEMPORARY_ERROR,
WORKER_FILE_UPDATE_FAILED,
} from '../../../../constants/error-messages';
import { logger, removeMeta } from '../../../../logger';
import { getAdditionalFiles } from '../../../../modules/manager/npm/post-update';
import { Pr, platform } from '../../../../modules/platform';
import {
ensureComment,
ensureCommentRemoval,
} from '../../../../modules/platform/comment';
import { scm } from '../../../../modules/platform/scm';
import { ExternalHostError } from '../../../../types/errors/external-host-error';
import { getElapsedDays } from '../../../../util/date';
import { emojify } from '../../../../util/emoji';
import { checkoutBranch } from '../../../../util/git';
import {
getMergeConfidenceLevel,
isActiveConfidenceLevel,
satisfiesConfidenceLevel,
} from '../../../../util/merge-confidence';
import * as template from '../../../../util/template';
import { isLimitReached } from '../../../global/limits';
import type { BranchConfig, BranchResult, PrBlockedBy } from '../../../types';
import { embedChangelog, needsChangelogs } from '../../changelog';
import { ensurePr } from '../pr';
import { checkAutoMerge } from '../pr/automerge';
import { setArtifactErrorStatus } from './artifacts';
import { tryBranchAutomerge } from './automerge';
import { prAlreadyExisted } from './check-existing';
import { commitFilesToBranch } from './commit';
import executePostUpgradeCommands from './execute-post-upgrade-commands';
import { getUpdatedPackageFiles } from './get-updated';
import { handleClosedPr, handleModifiedPr } from './handle-existing';
import { shouldReuseExistingBranch } from './reuse';
import { isScheduledNow } from './schedule';
import { setConfidence, setStability } from './status-checks';
function rebaseCheck(config: RenovateConfig, branchPr: Pr): boolean {
const titleRebase = branchPr.title?.startsWith('rebase!');
const labelRebase = !!branchPr.labels?.includes(config.rebaseLabel!);
const prRebaseChecked = !!branchPr.bodyStruct?.rebaseRequested;
return titleRebase || labelRebase || prRebaseChecked;
}
async function deleteBranchSilently(branchName: string): Promise<void> {
try {
await scm.deleteBranch(branchName);
} catch (err) /* istanbul ignore next */ {
logger.debug({ branchName, err }, 'Branch auto-remove failed');
}
}
export interface ProcessBranchResult {
branchExists: boolean;
updatesVerified?: boolean;
prBlockedBy?: PrBlockedBy;
prNo?: number;
result: BranchResult;
commitSha?: string | null;
}
export async function processBranch(
branchConfig: BranchConfig
): Promise<ProcessBranchResult> {
let commitSha: string | null = null;
let config: BranchConfig = { ...branchConfig };
logger.trace({ config }, 'processBranch()');
let branchExists = await scm.branchExists(config.branchName);
let updatesVerified = false;
if (!branchExists && config.branchPrefix !== config.branchPrefixOld) {
const branchName = config.branchName.replace(
config.branchPrefix!,
config.branchPrefixOld!
);
branchExists = await scm.branchExists(branchName);
if (branchExists) {
config.branchName = branchName;
logger.debug('Found existing branch with branchPrefixOld');
}
}
let branchPr = await platform.getBranchPr(config.branchName);
logger.debug(`branchExists=${branchExists}`);
const dependencyDashboardCheck =
config.dependencyDashboardChecks?.[config.branchName];
logger.debug(`dependencyDashboardCheck=${dependencyDashboardCheck!}`);
if (branchPr) {
config.rebaseRequested = rebaseCheck(config, branchPr);
logger.debug(`PR rebase requested=${config.rebaseRequested}`);
}
const artifactErrorTopic = emojify(':warning: Artifact update problem');
try {
// Check if branch already existed
const existingPr = branchPr ? undefined : await prAlreadyExisted(config);
if (existingPr && !dependencyDashboardCheck) {
logger.debug(
{ prTitle: config.prTitle },
'Closed PR already exists. Skipping branch.'
);
await handleClosedPr(config, existingPr);
return {
branchExists: false,
prNo: existingPr.number,
result: 'already-existed',
};
}
// istanbul ignore if
if (!branchExists && config.dependencyDashboardApproval) {
if (dependencyDashboardCheck) {
logger.debug(`Branch ${config.branchName} is approved for creation`);
} else {
logger.debug(`Branch ${config.branchName} needs approval`);
return {
branchExists,
prNo: branchPr?.number,
result: 'needs-approval',
};
}
}
if (
!branchExists &&
isLimitReached('Branches') &&
!dependencyDashboardCheck &&
!config.isVulnerabilityAlert
) {
logger.debug('Reached branch limit - skipping branch creation');
return {
branchExists,
prNo: branchPr?.number,
result: 'branch-limit-reached',
};
}
if (
isLimitReached('Commits') &&
!dependencyDashboardCheck &&
!config.isVulnerabilityAlert
) {
logger.debug('Reached commits limit - skipping branch');
return {
branchExists,
prNo: branchPr?.number,
result: 'commit-limit-reached',
};
}
if (
!branchExists &&
branchConfig.pendingChecks &&
!dependencyDashboardCheck
) {
return {
branchExists: false,
prNo: branchPr?.number,
result: 'pending',
};
}
if (branchExists) {
// check if branch is labelled to stop
config.stopUpdating = branchPr?.labels?.includes(
config.stopUpdatingLabel!
);
const prRebaseChecked = !!branchPr?.bodyStruct?.rebaseRequested;
if (branchExists && !dependencyDashboardCheck && config.stopUpdating) {
if (!prRebaseChecked) {
logger.info(
'Branch updating is skipped because stopUpdatingLabel is present in config'
);
return {
branchExists: true,
prNo: branchPr?.number,
result: 'no-work',
};
}
}
logger.debug('Checking if PR has been edited');
const branchIsModified = await scm.isBranchModified(config.branchName);
if (branchPr) {
logger.debug('Found existing branch PR');
if (branchPr.state !== 'open') {
logger.debug(
'PR has been closed or merged since this run started - aborting'
);
throw new Error(REPOSITORY_CHANGED);
}
if (
branchIsModified ||
(branchPr.targetBranch &&
branchPr.targetBranch !== branchConfig.baseBranch)
) {
logger.debug(`PR has been edited, PrNo:${branchPr.number}`);
await handleModifiedPr(config, branchPr);
if (!(dependencyDashboardCheck || config.rebaseRequested)) {
return {
branchExists,
prNo: branchPr.number,
result: 'pr-edited',
};
}
}
} else if (branchIsModified) {
const oldPr = await platform.findPr({
branchName: config.branchName,
state: '!open',
});
if (!oldPr) {
logger.debug('Branch has been edited but found no PR - skipping');
return {
branchExists,
result: 'pr-edited',
};
}
const branchSha = await scm.getBranchCommit(config.branchName);
const oldPrSha = oldPr?.sha;
if (!oldPrSha || oldPrSha === branchSha) {
logger.debug(
{ oldPrNumber: oldPr.number, oldPrSha, branchSha },
'Found old PR matching this branch - will override it'
);
} else {
logger.debug(
{ oldPrNumber: oldPr.number, oldPrSha, branchSha },
'Found old PR but the SHA is different'
);
return {
branchExists,
result: 'pr-edited',
};
}
}
}
// Check schedule
config.isScheduledNow = isScheduledNow(config, 'schedule');
if (!config.isScheduledNow && !dependencyDashboardCheck) {
if (!branchExists) {
logger.debug('Skipping branch creation as not within schedule');
return {
branchExists,
prNo: branchPr?.number,
result: 'not-scheduled',
};
}
if (config.updateNotScheduled === false && !config.rebaseRequested) {
logger.debug('Skipping branch update as not within schedule');
return {
branchExists,
prNo: branchPr?.number,
result: 'update-not-scheduled',
};
}
// istanbul ignore if
if (!branchPr) {
logger.debug('Skipping PR creation out of schedule');
return {
branchExists,
result: 'not-scheduled',
};
}
logger.debug(
'Branch + PR exists but is not scheduled -- will update if necessary'
);
}
//stability checks
if (
config.upgrades.some(
(upgrade) =>
(upgrade.stabilityDays && upgrade.releaseTimestamp) ||
isActiveConfidenceLevel(upgrade.minimumConfidence!)
)
) {
// Only set a stability status check if one or more of the updates contain
// both a stabilityDays setting and a releaseTimestamp
config.stabilityStatus = 'green';
// Default to 'success' but set 'pending' if any update is pending
for (const upgrade of config.upgrades) {
if (is.number(upgrade.stabilityDays) && upgrade.releaseTimestamp) {
const daysElapsed = getElapsedDays(upgrade.releaseTimestamp);
if (daysElapsed < upgrade.stabilityDays) {
logger.debug(
{
depName: upgrade.depName,
daysElapsed,
stabilityDays: upgrade.stabilityDays,
},
'Update has not passed stability days'
);
config.stabilityStatus = 'yellow';
continue;
}
}
const datasource = upgrade.datasource!;
const depName = upgrade.depName!;
const minimumConfidence = upgrade.minimumConfidence!;
const updateType = upgrade.updateType!;
const currentVersion = upgrade.currentVersion!;
const newVersion = upgrade.newVersion!;
if (isActiveConfidenceLevel(minimumConfidence)) {
const confidence = await getMergeConfidenceLevel(
datasource,
depName,
currentVersion,
newVersion,
updateType
);
if (satisfiesConfidenceLevel(confidence, minimumConfidence)) {
config.confidenceStatus = 'green';
} else {
logger.debug(
{ depName, confidence, minimumConfidence },
'Update does not meet minimum confidence scores'
);
config.confidenceStatus = 'yellow';
continue;
}
}
}
// Don't create a branch if we know it will be status 'pending'
if (
!dependencyDashboardCheck &&
!branchExists &&
config.stabilityStatus === 'yellow' &&
['not-pending', 'status-success'].includes(config.prCreation!)
) {
logger.debug(
'Skipping branch creation due to internal status checks not met'
);
return {
branchExists,
prNo: branchPr?.number,
result: 'pending',
};
}
}
const userRebaseRequested =
dependencyDashboardCheck === 'rebase' ||
!!config.dependencyDashboardRebaseAllOpen ||
!!config.rebaseRequested;
const userApproveAllPendingPR = !!config.dependencyDashboardAllPending;
const userOpenAllRateLimtedPR = !!config.dependencyDashboardAllRateLimited;
if (userRebaseRequested) {
logger.debug('Manual rebase requested via Dependency Dashboard');
config.reuseExistingBranch = false;
} else if (userApproveAllPendingPR) {
logger.debug(
'A user manually approved all pending PRs via the Dependency Dashboard.'
);
} else if (userOpenAllRateLimtedPR) {
logger.debug(
'A user manually approved all rate-limited PRs via the Dependency Dashboard.'
);
} else if (
branchExists &&
config.rebaseWhen === 'never' &&
!dependencyDashboardCheck
) {
logger.debug('rebaseWhen=never so skipping branch update check');
return {
branchExists,
prNo: branchPr?.number,
result: 'no-work',
};
} else {
config = { ...config, ...(await shouldReuseExistingBranch(config)) };
}
// TODO: types (#7154)
logger.debug(`Using reuseExistingBranch: ${config.reuseExistingBranch!}`);
if (!(config.reuseExistingBranch && config.skipBranchUpdate)) {
await checkoutBranch(config.baseBranch);
const res = await getUpdatedPackageFiles(config);
// istanbul ignore if
if (res.artifactErrors && config.artifactErrors) {
res.artifactErrors = config.artifactErrors.concat(res.artifactErrors);
}
config = { ...config, ...res };
if (config.updatedPackageFiles?.length) {
logger.debug(
`Updated ${config.updatedPackageFiles.length} package files`
);
} else {
logger.debug('No package files need updating');
}
const additionalFiles = await getAdditionalFiles(
config,
branchConfig.packageFiles!
);
config.artifactErrors = (config.artifactErrors ?? []).concat(
additionalFiles.artifactErrors
);
config.updatedArtifacts = (config.updatedArtifacts ?? []).concat(
additionalFiles.updatedArtifacts
);
if (config.updatedArtifacts?.length) {
logger.debug(
{
updatedArtifacts: config.updatedArtifacts.map((f) =>
f.type === 'deletion' ? `${f.path} (delete)` : f.path
),
},
`Updated ${config.updatedArtifacts.length} lock files`
);
} else {
logger.debug('No updated lock files in branch');
}
const postUpgradeCommandResults = await executePostUpgradeCommands(
config
);
if (postUpgradeCommandResults !== null) {
const { updatedArtifacts, artifactErrors } = postUpgradeCommandResults;
config.updatedArtifacts = updatedArtifacts;
config.artifactErrors = artifactErrors;
}
removeMeta(['dep']);
if (config.artifactErrors?.length) {
if (config.releaseTimestamp) {
logger.debug(`Branch timestamp: ` + config.releaseTimestamp);
const releaseTimestamp = DateTime.fromISO(config.releaseTimestamp);
if (releaseTimestamp.plus({ hours: 2 }) < DateTime.local()) {
logger.debug(
'PR is older than 2 hours, raise PR with lock file errors'
);
} else if (branchExists) {
logger.debug(
'PR is less than 2 hours old but branchExists so updating anyway'
);
} else {
logger.debug(
'PR is less than 2 hours old - raise error instead of PR'
);
throw new Error(MANAGER_LOCKFILE_ERROR);
}
} else {
logger.debug('PR has no releaseTimestamp');
}
} else if (config.updatedArtifacts?.length && branchPr) {
// If there are artifacts, no errors, and an existing PR then ensure any artifacts error comment is removed
// istanbul ignore if
if (GlobalConfig.get('dryRun')) {
logger.info(
`DRY-RUN: Would ensure comment removal in PR #${branchPr.number}`
);
} else {
// Remove artifacts error comment only if this run has successfully updated artifacts
await ensureCommentRemoval({
type: 'by-topic',
number: branchPr.number,
topic: artifactErrorTopic,
});
}
}
const forcedManually = userRebaseRequested || !branchExists;
config.isConflicted ??=
branchExists &&
(await scm.isBranchConflicted(config.baseBranch, config.branchName));
config.forceCommit = forcedManually || config.isConflicted;
// compile commit message with body, which maybe needs changelogs
if (config.commitBody) {
if (
config.fetchReleaseNotes &&
needsChangelogs(config, ['commitBody'])
) {
// we only need first upgrade, the others are only needed on PR update
// we add it to first, so PR fetch can skip fetching for that update
await embedChangelog(config.upgrades[0]);
}
// changelog is on first upgrade
config.commitMessage = `${config.commitMessage!}\n\n${template.compile(
config.commitBody,
{
...config,
logJSON: config.upgrades[0].logJSON,
releases: config.upgrades[0].releases,
}
)}`;
logger.trace(`commitMessage: ` + JSON.stringify(config.commitMessage));
}
commitSha = await commitFilesToBranch(config);
// Checkout to base branch to ensure that the next branch processing always starts with git being on the baseBranch
// baseBranch is not checked out at the start of processBranch() due to pull/16246
await checkoutBranch(config.baseBranch);
updatesVerified = true;
}
// istanbul ignore if
if (branchPr && platform.refreshPr) {
await platform.refreshPr(branchPr.number);
}
if (!commitSha && !branchExists) {
return {
branchExists,
prNo: branchPr?.number,
result: 'no-work',
};
}
if (commitSha) {
const action = branchExists ? 'updated' : 'created';
logger.info({ commitSha }, `Branch ${action}`);
}
// Set branch statuses
await setArtifactErrorStatus(config);
await setStability(config);
await setConfidence(config);
// new commit means status check are pretty sure pending but maybe not reported yet
// if PR has not been created + new commit + prCreation !== immediate skip
// but do not break when there are artifact errors
if (
!branchPr &&
!config.artifactErrors?.length &&
!userRebaseRequested &&
commitSha &&
config.prCreation !== 'immediate'
) {
logger.debug(`Branch status pending, current sha: ${commitSha}`);
return {
branchExists: true,
updatesVerified,
result: 'pending',
commitSha,
};
}
// Try to automerge branch and finish if successful, but only if branch already existed before this run
// skip if we have a non-immediate pr and there is an existing PR,
// we want to update the PR and skip the Auto merge since status checks aren't done yet
if (!config.artifactErrors?.length && (!commitSha || config.ignoreTests)) {
const mergeStatus = await tryBranchAutomerge(config);
logger.debug(`mergeStatus=${mergeStatus}`);
if (mergeStatus === 'automerged') {
if (GlobalConfig.get('dryRun')) {
logger.info('DRY-RUN: Would delete branch' + config.branchName);
} else {
await deleteBranchSilently(config.branchName);
}
logger.debug('Branch is automerged - returning');
return { branchExists: false, result: 'automerged' };
}
if (mergeStatus === 'off schedule') {
logger.debug(
'Branch cannot automerge now because automergeSchedule is off schedule - skipping'
);
return {
branchExists,
result: 'not-scheduled',
commitSha,
};
}
if (
mergeStatus === 'stale' &&
['conflicted', 'never'].includes(config.rebaseWhen!)
) {
logger.warn(
'Branch cannot automerge because it is behind base branch and rebaseWhen setting disallows rebasing - raising a PR instead'
);
config.forcePr = true;
config.branchAutomergeFailureMessage = mergeStatus;
}
if (
mergeStatus === 'automerge aborted - PR exists' ||
mergeStatus === 'branch status error' ||
mergeStatus === 'failed'
) {
logger.debug(
`Branch automerge not possible, mergeStatus:${mergeStatus}`
);
config.forcePr = true;
config.branchAutomergeFailureMessage = mergeStatus;
}
}
} catch (err) /* istanbul ignore next */ {
if (err.statusCode === 404) {
logger.debug({ err }, 'Received a 404 error - aborting run');
throw new Error(REPOSITORY_CHANGED);
}
if (err.message === PLATFORM_RATE_LIMIT_EXCEEDED) {
logger.debug('Passing rate-limit-exceeded error up');
throw err;
}
if (err.message === REPOSITORY_CHANGED) {
logger.debug('Passing repository-changed error up');
throw err;
}
if (err.message?.startsWith('remote: Invalid username or password')) {
logger.debug('Throwing bad credentials');
throw new Error(PLATFORM_BAD_CREDENTIALS);
}
if (
err.message?.startsWith(
'ssh_exchange_identification: Connection closed by remote host'
)
) {
logger.debug('Throwing bad credentials');
throw new Error(PLATFORM_BAD_CREDENTIALS);
}
if (err.message === PLATFORM_BAD_CREDENTIALS) {
logger.debug('Passing bad-credentials error up');
throw err;
}
if (err.message === PLATFORM_INTEGRATION_UNAUTHORIZED) {
logger.debug('Passing integration-unauthorized error up');
throw err;
}
if (err.message === MANAGER_LOCKFILE_ERROR) {
logger.debug('Passing lockfile-error up');
throw err;
}
if (err.message?.includes('space left on device')) {
throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);
}
if (err.message === SYSTEM_INSUFFICIENT_DISK_SPACE) {
logger.debug('Passing disk-space error up');
throw err;
}
if (err.message.startsWith('Resource not accessible by integration')) {
logger.debug('Passing 403 error up');
throw err;
}
if (err.message === WORKER_FILE_UPDATE_FAILED) {
logger.warn('Error updating branch: update failure');
} else if (err.message.startsWith('bundler-')) {
// we have already warned inside the bundler artifacts error handling, so just return
return {
branchExists: true,
updatesVerified,
prNo: branchPr?.number,
result: 'error',
commitSha,
};
} else if (
err.messagee &&
err.message.includes('fatal: Authentication failed')
) {
throw new Error(PLATFORM_AUTHENTICATION_ERROR);
} else if (err.message?.includes('fatal: bad revision')) {
logger.debug({ err }, 'Aborting job due to bad revision error');
throw new Error(REPOSITORY_CHANGED);
} else if (err.message === CONFIG_VALIDATION) {
logger.debug('Passing config validation error up');
throw err;
} else if (err.message === TEMPORARY_ERROR) {
logger.debug('Passing TEMPORARY_ERROR error up');
throw err;
} else if (!(err instanceof ExternalHostError)) {
logger.warn({ err }, `Error updating branch`);
}
// Don't throw here - we don't want to stop the other renovations
return {
branchExists,
prNo: branchPr?.number,
result: 'error',
commitSha,
};
}
try {
logger.debug('Ensuring PR');
logger.debug(
`There are ${config.errors!.length} errors and ${
config.warnings!.length
} warnings`
);
const ensurePrResult = await ensurePr(config);
if (ensurePrResult.type === 'without-pr') {
const { prBlockedBy } = ensurePrResult;
branchPr = null;
if (prBlockedBy === 'RateLimited' && !config.isVulnerabilityAlert) {
logger.debug('Reached PR limit - skipping PR creation');
return {
branchExists,
prBlockedBy,
result: 'pr-limit-reached',
commitSha,
};
}
// TODO: ensurePr should check for automerge itself (#9719)
if (prBlockedBy === 'NeedsApproval') {
return {
branchExists,
prBlockedBy,
result: 'needs-pr-approval',
commitSha,
};
}
if (prBlockedBy === 'AwaitingTests') {
return {
branchExists,
prBlockedBy,
result: 'pending',
commitSha,
};
}
if (prBlockedBy === 'BranchAutomerge') {
return {
branchExists,
prBlockedBy,
result: 'done',
commitSha,
};
}
if (prBlockedBy === 'Error') {
return {
branchExists,
prBlockedBy,
result: 'error',
commitSha,
};
}
logger.warn({ prBlockedBy }, 'Unknown PrBlockedBy result');
return {
branchExists,
prBlockedBy,
result: 'error',
commitSha,
};
}
if (ensurePrResult.type === 'with-pr') {
const { pr } = ensurePrResult;
branchPr = pr;
if (config.artifactErrors?.length) {
logger.warn(
{ artifactErrors: config.artifactErrors },
'artifactErrors'
);
let content = `Renovate failed to update `;
content +=
config.artifactErrors.length > 1 ? 'artifacts' : 'an artifact';
content +=
' related to this branch. You probably do not want to merge this PR as-is.';
content += emojify(
`\n\n:recycle: Renovate will retry this branch, including artifacts, only when one of the following happens:\n\n`
);
content +=
' - any of the package files in this branch needs updating, or \n';
content += ' - the branch becomes conflicted, or\n';
content +=
' - you click the rebase/retry checkbox if found above, or\n';
content +=
' - you rename this PR\'s title to start with "rebase!" to trigger it manually';
content += '\n\nThe artifact failure details are included below:\n\n';
// TODO: types (#7154)
config.artifactErrors.forEach((error) => {
content += `##### File name: ${error.lockFile!}\n\n`;
content += `\`\`\`\n${error.stderr!}\n\`\`\`\n\n`;
});
content = platform.massageMarkdown(content);
if (
!(
config.suppressNotifications!.includes('artifactErrors') ||
config.suppressNotifications!.includes('lockFileErrors')
)
) {
if (GlobalConfig.get('dryRun')) {
logger.info(
`DRY-RUN: Would ensure lock file error comment in PR #${pr.number}`
);
} else {
await ensureComment({
number: pr.number,
topic: artifactErrorTopic,
content,
});
}
}
} else if (config.automerge) {
logger.debug('PR is configured for automerge');
// skip automerge if there is a new commit since status checks aren't done yet
if (!commitSha || config.ignoreTests) {
logger.debug('checking auto-merge');
const prAutomergeResult = await checkAutoMerge(pr, config);
if (prAutomergeResult?.automerged) {
return {
branchExists,
result: 'automerged',
commitSha,
};
}
}
} else {
logger.debug('PR is not configured for automerge');
}
}
} catch (err) /* istanbul ignore next */ {
if (
err instanceof ExternalHostError ||
[PLATFORM_RATE_LIMIT_EXCEEDED, REPOSITORY_CHANGED].includes(err.message)
) {
logger.debug('Passing PR error up');
throw err;
}
// Otherwise don't throw here - we don't want to stop the other renovations
logger.error({ err }, `Error ensuring PR: ${String(err.message)}`);
}
if (!branchExists) {
return {
branchExists: true,
updatesVerified,
prNo: branchPr?.number,
result: 'pr-created',
commitSha,
};
}
return {
branchExists,
updatesVerified,
prNo: branchPr?.number,
result: 'done',
commitSha,
};
}