-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
index.ts
1343 lines (1258 loc) · 37.7 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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import URL from 'node:url';
import { setTimeout } from 'timers/promises';
import is from '@sindresorhus/is';
import fs from 'fs-extra';
import semver from 'semver';
import {
Options,
ResetMode,
SimpleGit,
TaskOptions,
simpleGit,
} from 'simple-git';
import upath from 'upath';
import { configFileNames } from '../../config/app-strings';
import { GlobalConfig } from '../../config/global';
import type { RenovateConfig } from '../../config/types';
import {
CONFIG_VALIDATION,
INVALID_PATH,
REPOSITORY_CHANGED,
REPOSITORY_DISABLED,
REPOSITORY_EMPTY,
SYSTEM_INSUFFICIENT_DISK_SPACE,
TEMPORARY_ERROR,
} from '../../constants/error-messages';
import { logger } from '../../logger';
import { ExternalHostError } from '../../types/errors/external-host-error';
import type { GitProtocol } from '../../types/git';
import { incLimitedValue } from '../../workers/global/limits';
import { getCache } from '../cache/repository';
import { newlineRegex, regEx } from '../regex';
import { parseGitAuthor } from './author';
import {
getCachedBehindBaseResult,
setCachedBehindBaseResult,
} from './behind-base-branch-cache';
import { getNoVerify, simpleGitConfig } from './config';
import {
getCachedConflictResult,
setCachedConflictResult,
} from './conflicts-cache';
import {
bulkChangesDisallowed,
checkForPlatformFailure,
handleCommitError,
} from './error';
import {
getCachedModifiedResult,
setCachedModifiedResult,
} from './modified-cache';
import { configSigningKey, writePrivateKey } from './private-key';
import type {
CommitFilesConfig,
CommitResult,
LocalConfig,
LongCommitSha,
PushFilesConfig,
StatusResult,
StorageConfig,
TreeItem,
} from './types';
export { setNoVerify } from './config';
export { setPrivateKey } from './private-key';
// Retry parameters
const retryCount = 5;
const delaySeconds = 3;
const delayFactor = 2;
// A generic wrapper for simpleGit.* calls to make them more fault-tolerant
export async function gitRetry<T>(gitFunc: () => Promise<T>): Promise<T> {
let round = 0;
let lastError: Error | undefined;
while (round <= retryCount) {
if (round > 0) {
logger.debug(`gitRetry round ${round}`);
}
try {
const res = await gitFunc();
if (round > 1) {
logger.debug('Successful retry of git function');
}
return res;
} catch (err) {
lastError = err;
logger.debug({ err }, `Git function thrown`);
// Try to transform the Error to ExternalHostError
const errChecked = checkForPlatformFailure(err);
if (errChecked instanceof ExternalHostError) {
logger.debug(
{ err: errChecked },
`ExternalHostError thrown in round ${
round + 1
} of ${retryCount} - retrying in the next round`,
);
} else {
throw err;
}
}
const nextDelay = delayFactor ^ ((round - 1) * delaySeconds);
logger.trace({ nextDelay }, `Delay next round`);
await setTimeout(1000 * nextDelay);
round++;
}
throw lastError;
}
async function isDirectory(dir: string): Promise<boolean> {
try {
return (await fs.stat(dir)).isDirectory();
} catch (err) {
return false;
}
}
async function getDefaultBranch(git: SimpleGit): Promise<string> {
// see https://stackoverflow.com/a/62352647/3005034
try {
let res = await git.raw(['rev-parse', '--abbrev-ref', 'origin/HEAD']);
// istanbul ignore if
if (!res) {
logger.debug('Could not determine default branch using git rev-parse');
const headPrefix = 'HEAD branch: ';
res = (await git.raw(['remote', 'show', 'origin']))
.split('\n')
.map((line) => line.trim())
.find((line) => line.startsWith(headPrefix))!
.replace(headPrefix, '');
}
return res.replace('origin/', '').trim();
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
if (
err.message.startsWith(
'fatal: ref refs/remotes/origin/HEAD is not a symbolic ref',
)
) {
throw new Error(REPOSITORY_EMPTY);
}
// istanbul ignore if
if (err.message.includes("fatal: ambiguous argument 'origin/HEAD'")) {
logger.warn({ err }, 'Error getting default branch');
throw new Error(TEMPORARY_ERROR);
}
throw err;
}
}
let config: LocalConfig = {} as any;
// TODO: can be undefined
let git: SimpleGit;
let gitInitialized: boolean;
let submodulesInitizialized: boolean;
let privateKeySet = false;
export const GIT_MINIMUM_VERSION = '2.33.0'; // git show-current
export async function validateGitVersion(): Promise<boolean> {
let version: string | undefined;
const globalGit = simpleGit();
try {
const { major, minor, patch, installed } = await globalGit.version();
// istanbul ignore if
if (!installed) {
logger.error('Git not installed');
return false;
}
version = `${major}.${minor}.${patch}`;
} catch (err) /* istanbul ignore next */ {
logger.error({ err }, 'Error fetching git version');
return false;
}
// istanbul ignore if
if (!(version && semver.gte(version, GIT_MINIMUM_VERSION))) {
logger.error(
{ detectedVersion: version, minimumVersion: GIT_MINIMUM_VERSION },
'Git version needs upgrading',
);
return false;
}
logger.debug(`Found valid git version: ${version}`);
return true;
}
async function fetchBranchCommits(): Promise<void> {
config.branchCommits = {};
const opts = ['ls-remote', '--heads', config.url];
if (config.extraCloneOpts) {
Object.entries(config.extraCloneOpts).forEach((e) =>
// TODO: types (#22198)
opts.unshift(e[0], `${e[1]!}`),
);
}
try {
(await gitRetry(() => git.raw(opts)))
.split(newlineRegex)
.filter(Boolean)
.map((line) => line.trim().split(regEx(/\s+/)))
.forEach(([sha, ref]) => {
config.branchCommits[ref.replace('refs/heads/', '')] =
sha as LongCommitSha;
});
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
logger.debug({ err }, 'git error');
if (err.message?.includes('Please ask the owner to check their account')) {
throw new Error(REPOSITORY_DISABLED);
}
throw err;
}
}
export async function fetchRevSpec(revSpec: string): Promise<void> {
await gitRetry(() => git.fetch(['origin', revSpec]));
}
export async function initRepo(args: StorageConfig): Promise<void> {
config = { ...args } as any;
config.ignoredAuthors = [];
config.additionalBranches = [];
config.branchIsModified = {};
git = simpleGit(GlobalConfig.get('localDir'), simpleGitConfig()).env({
...process.env,
LANG: 'C.UTF-8',
LC_ALL: 'C.UTF-8',
});
gitInitialized = false;
submodulesInitizialized = false;
await fetchBranchCommits();
}
async function resetToBranch(branchName: string): Promise<void> {
logger.debug(`resetToBranch(${branchName})`);
await git.raw(['reset', '--hard']);
await gitRetry(() => git.checkout(branchName));
await git.raw(['reset', '--hard', 'origin/' + branchName]);
await git.raw(['clean', '-fd']);
}
// istanbul ignore next
export async function resetToCommit(commit: LongCommitSha): Promise<void> {
logger.debug(`resetToCommit(${commit})`);
await git.raw(['reset', '--hard', commit]);
}
async function deleteLocalBranch(branchName: string): Promise<void> {
await git.branch(['-D', branchName]);
}
async function cleanLocalBranches(): Promise<void> {
const existingBranches = (await git.raw(['branch']))
.split(newlineRegex)
.map((branch) => branch.trim())
.filter((branch) => branch.length)
.filter((branch) => !branch.startsWith('* '));
logger.debug({ existingBranches });
for (const branchName of existingBranches) {
await deleteLocalBranch(branchName);
}
}
export function setGitAuthor(gitAuthor: string | undefined): void {
const gitAuthorParsed = parseGitAuthor(
gitAuthor ?? 'Renovate Bot <renovate@whitesourcesoftware.com>',
);
if (!gitAuthorParsed) {
const error = new Error(CONFIG_VALIDATION);
error.validationSource = 'None';
error.validationError = 'Invalid gitAuthor';
error.validationMessage = `\`gitAuthor\` is not parsed as valid RFC5322 format: \`${gitAuthor!}\``;
throw error;
}
config.gitAuthorName = gitAuthorParsed.name;
config.gitAuthorEmail = gitAuthorParsed.address;
}
export async function writeGitAuthor(): Promise<void> {
const { gitAuthorName, gitAuthorEmail, writeGitDone } = config;
// istanbul ignore if
if (writeGitDone) {
return;
}
config.writeGitDone = true;
try {
if (gitAuthorName) {
logger.debug(`Setting git author name: ${gitAuthorName}`);
await git.addConfig('user.name', gitAuthorName);
}
if (gitAuthorEmail) {
logger.debug(`Setting git author email: ${gitAuthorEmail}`);
await git.addConfig('user.email', gitAuthorEmail);
}
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
logger.debug(
{ err, gitAuthorName, gitAuthorEmail },
'Error setting git author config',
);
throw new Error(TEMPORARY_ERROR);
}
}
export function setUserRepoConfig({
gitIgnoredAuthors,
gitAuthor,
}: RenovateConfig): void {
config.ignoredAuthors = gitIgnoredAuthors ?? [];
setGitAuthor(gitAuthor);
}
export async function getSubmodules(): Promise<string[]> {
try {
return (
(await git.raw([
'config',
'--file',
'.gitmodules',
'--get-regexp',
'\\.path',
])) || ''
)
.trim()
.split(regEx(/[\n\s]/))
.filter((_e: string, i: number) => i % 2);
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'Error getting submodules');
return [];
}
}
export async function cloneSubmodules(shouldClone: boolean): Promise<void> {
if (!shouldClone || submodulesInitizialized) {
return;
}
submodulesInitizialized = true;
await syncGit();
const submodules = await getSubmodules();
for (const submodule of submodules) {
try {
logger.debug(`Cloning git submodule at ${submodule}`);
await gitRetry(() => git.submoduleUpdate(['--init', submodule]));
} catch (err) {
logger.warn(
{ err },
`Unable to initialise git submodule at ${submodule}`,
);
}
}
}
export function isCloned(): boolean {
return gitInitialized;
}
export async function syncGit(): Promise<void> {
if (gitInitialized) {
// istanbul ignore if
if (process.env.RENOVATE_X_CLEAR_HOOKS) {
await git.raw(['config', 'core.hooksPath', '/dev/null']);
}
return;
}
// istanbul ignore if: failsafe
if (GlobalConfig.get('platform') === 'local') {
throw new Error('Cannot sync git when platform=local');
}
gitInitialized = true;
const localDir = GlobalConfig.get('localDir')!;
logger.debug(`Initializing git repository into ${localDir}`);
const gitHead = upath.join(localDir, '.git/HEAD');
let clone = true;
if (await fs.pathExists(gitHead)) {
try {
await git.raw(['remote', 'set-url', 'origin', config.url]);
await resetToBranch(await getDefaultBranch(git));
const fetchStart = Date.now();
await gitRetry(() => git.pull());
await gitRetry(() => git.fetch());
config.currentBranch =
config.currentBranch || (await getDefaultBranch(git));
await resetToBranch(config.currentBranch);
await cleanLocalBranches();
await gitRetry(() => git.raw(['remote', 'prune', 'origin']));
const durationMs = Math.round(Date.now() - fetchStart);
logger.info({ durationMs }, 'git fetch completed');
clone = false;
} catch (err) /* istanbul ignore next */ {
if (err.message === REPOSITORY_EMPTY) {
throw err;
}
logger.info({ err }, 'git fetch error');
}
}
if (clone) {
const cloneStart = Date.now();
try {
const opts: string[] = [];
if (config.defaultBranch) {
opts.push('-b', config.defaultBranch);
}
if (config.fullClone) {
logger.debug('Performing full clone');
} else {
logger.debug('Performing blobless clone');
opts.push('--filter=blob:none');
}
if (config.extraCloneOpts) {
Object.entries(config.extraCloneOpts).forEach((e) =>
// TODO: types (#22198)
opts.push(e[0], `${e[1]!}`),
);
}
const emptyDirAndClone = async (): Promise<void> => {
await fs.emptyDir(localDir);
await git.clone(config.url, '.', opts);
};
await gitRetry(() => emptyDirAndClone());
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'git clone error');
if (err.message?.includes('No space left on device')) {
throw new Error(SYSTEM_INSUFFICIENT_DISK_SPACE);
}
if (err.message === REPOSITORY_EMPTY) {
throw err;
}
throw new ExternalHostError(err, 'git');
}
const durationMs = Math.round(Date.now() - cloneStart);
logger.debug({ durationMs }, 'git clone completed');
}
try {
config.currentBranchSha = (
await git.raw(['rev-parse', 'HEAD'])
).trim() as LongCommitSha;
} catch (err) /* istanbul ignore next */ {
if (err.message?.includes('fatal: not a git repository')) {
throw new Error(REPOSITORY_CHANGED);
}
throw err;
}
// This will only happen now if set in global config
await cloneSubmodules(!!config.cloneSubmodules);
try {
const latestCommit = (await git.log({ n: 1 })).latest;
logger.debug({ latestCommit }, 'latest repository commit');
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
if (err.message.includes('does not have any commits yet')) {
throw new Error(REPOSITORY_EMPTY);
}
logger.warn({ err }, 'Cannot retrieve latest commit');
}
config.currentBranch =
config.currentBranch ??
config.defaultBranch ??
(await getDefaultBranch(git));
delete getCache()?.semanticCommits;
}
// istanbul ignore next
export async function getRepoStatus(path?: string): Promise<StatusResult> {
if (is.string(path)) {
const localDir = GlobalConfig.get('localDir');
const localPath = upath.resolve(localDir, path);
if (!localPath.startsWith(upath.resolve(localDir))) {
logger.warn(
{ localPath, localDir },
'Preventing access to file outside the local directory',
);
throw new Error(INVALID_PATH);
}
}
await syncGit();
return git.status(path ? [path] : []);
}
export function branchExists(branchName: string): boolean {
return !!config.branchCommits[branchName];
}
// Return the commit SHA for a branch
export function getBranchCommit(branchName: string): LongCommitSha | null {
return config.branchCommits[branchName] || null;
}
export async function getCommitMessages(): Promise<string[]> {
logger.debug('getCommitMessages');
if (GlobalConfig.get('platform') !== 'local') {
await syncGit();
}
try {
const res = await git.log({
n: 20,
format: { message: '%s' },
});
return res.all.map((commit) => commit.message);
} catch (err) /* istanbul ignore next */ {
return [];
}
}
export async function checkoutBranch(
branchName: string,
): Promise<LongCommitSha> {
logger.debug(`Setting current branch to ${branchName}`);
await syncGit();
try {
await gitRetry(() =>
git.checkout(
submodulesInitizialized
? ['-f', '--recurse-submodules', branchName, '--']
: ['-f', branchName, '--'],
),
);
config.currentBranch = branchName;
config.currentBranchSha = (
await git.raw(['rev-parse', 'HEAD'])
).trim() as LongCommitSha;
const latestCommitDate = (await git.log({ n: 1 }))?.latest?.date;
if (latestCommitDate) {
logger.debug({ branchName, latestCommitDate }, 'latest commit');
}
await git.reset(ResetMode.HARD);
return config.currentBranchSha;
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
if (err.message?.includes('fatal: ambiguous argument')) {
logger.warn({ err }, 'Failed to checkout branch');
throw new Error(TEMPORARY_ERROR);
}
throw err;
}
}
export async function getFileList(): Promise<string[]> {
await syncGit();
const branch = config.currentBranch;
let files: string;
try {
files = await git.raw(['ls-tree', '-r', branch]);
} catch (err) /* istanbul ignore next */ {
if (err.message?.includes('fatal: Not a valid object name')) {
logger.debug(
{ err },
'Branch not found when checking branch list - aborting',
);
throw new Error(REPOSITORY_CHANGED);
}
throw err;
}
// istanbul ignore if
if (!files) {
return [];
}
// submodules are starting with `160000 commit`
return files
.split(newlineRegex)
.filter(is.string)
.filter((line) => line.startsWith('100'))
.map((line) => line.split(regEx(/\t/)).pop()!);
}
export function getBranchList(): string[] {
return Object.keys(config.branchCommits ?? /* istanbul ignore next */ {});
}
export async function isBranchBehindBase(
branchName: string,
baseBranch: string,
): Promise<boolean> {
const baseBranchSha = getBranchCommit(baseBranch);
const branchSha = getBranchCommit(branchName);
let isBehind = getCachedBehindBaseResult(
branchName,
branchSha,
baseBranch,
baseBranchSha,
);
if (isBehind !== null) {
logger.debug(`branch.isBehindBase(): using cached result "${isBehind}"`);
return isBehind;
}
logger.debug('branch.isBehindBase(): using git to calculate');
await syncGit();
try {
const behindCount = (
await git.raw(['rev-list', '--count', `${branchSha!}..${baseBranchSha!}`])
).trim();
isBehind = behindCount !== '0';
logger.debug(
{ baseBranch, branchName },
`branch.isBehindBase(): ${isBehind}`,
);
setCachedBehindBaseResult(branchName, isBehind);
return isBehind;
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
throw err;
}
}
export async function isBranchModified(branchName: string): Promise<boolean> {
if (!branchExists(branchName)) {
logger.debug('branch.isModified(): no cache');
return false;
}
// First check local config
if (config.branchIsModified[branchName] !== undefined) {
return config.branchIsModified[branchName];
}
// Second check repository cache
const isModified = getCachedModifiedResult(
branchName,
getBranchCommit(branchName), // branch sha
);
if (isModified !== null) {
logger.debug(`branch.isModified(): using cached result "${isModified}"`);
config.branchIsModified[branchName] = isModified;
return isModified;
}
logger.debug('branch.isModified(): using git to calculate');
await syncGit();
// Retrieve the author of the most recent commit
let lastAuthor: string | undefined;
try {
lastAuthor = (
await git.raw([
'log',
'-1',
'--pretty=format:%ae',
`origin/${branchName}`,
'--',
])
).trim();
} catch (err) /* istanbul ignore next */ {
if (err.message?.includes('fatal: bad revision')) {
logger.debug(
{ err },
'Remote branch not found when checking last commit author - aborting run',
);
throw new Error(REPOSITORY_CHANGED);
}
logger.warn({ err }, 'Error checking last author for isBranchModified');
}
const { gitAuthorEmail } = config;
if (
lastAuthor === gitAuthorEmail ||
config.ignoredAuthors.some((ignoredAuthor) => lastAuthor === ignoredAuthor)
) {
// author matches - branch has not been modified
logger.debug('branch.isModified() = false');
config.branchIsModified[branchName] = false;
setCachedModifiedResult(branchName, false);
return false;
}
logger.debug(
{ branchName, lastAuthor, gitAuthorEmail },
'branch.isModified() = true',
);
config.branchIsModified[branchName] = true;
setCachedModifiedResult(branchName, true);
return true;
}
export async function isBranchConflicted(
baseBranch: string,
branch: string,
): Promise<boolean> {
logger.debug(`isBranchConflicted(${baseBranch}, ${branch})`);
const baseBranchSha = getBranchCommit(baseBranch);
const branchSha = getBranchCommit(branch);
if (!baseBranchSha || !branchSha) {
logger.warn(
{ baseBranch, branch },
'isBranchConflicted: branch does not exist',
);
return true;
}
const isConflicted = getCachedConflictResult(
branch,
branchSha,
baseBranch,
baseBranchSha,
);
if (is.boolean(isConflicted)) {
logger.debug(
`branch.isConflicted(): using cached result "${isConflicted}"`,
);
return isConflicted;
}
logger.debug('branch.isConflicted(): using git to calculate');
let result = false;
await syncGit();
await writeGitAuthor();
const origBranch = config.currentBranch;
try {
await git.reset(ResetMode.HARD);
//TODO: see #18600
if (origBranch !== baseBranch) {
await git.checkout(baseBranch);
}
await git.merge(['--no-commit', '--no-ff', `origin/${branch}`]);
} catch (err) {
result = true;
// istanbul ignore if: not easily testable
if (!err?.git?.conflicts?.length) {
logger.debug(
{ baseBranch, branch, err },
'isBranchConflicted: unknown error',
);
}
} finally {
try {
await git.merge(['--abort']);
if (origBranch !== baseBranch) {
await git.checkout(origBranch);
}
} catch (err) /* istanbul ignore next */ {
logger.debug(
{ baseBranch, branch, err },
'isBranchConflicted: cleanup error',
);
}
}
setCachedConflictResult(branch, result);
logger.debug(`branch.isConflicted(): ${result}`);
return result;
}
export async function deleteBranch(branchName: string): Promise<void> {
await syncGit();
try {
const deleteCommand = ['push', '--delete', 'origin', branchName];
if (getNoVerify().includes('push')) {
deleteCommand.push('--no-verify');
}
await gitRetry(() => git.raw(deleteCommand));
logger.debug(`Deleted remote branch: ${branchName}`);
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
logger.debug(`No remote branch to delete with name: ${branchName}`);
}
try {
await deleteLocalBranch(branchName);
// istanbul ignore next
logger.debug(`Deleted local branch: ${branchName}`);
} catch (err) {
const errChecked = checkForPlatformFailure(err);
// istanbul ignore if
if (errChecked) {
throw errChecked;
}
logger.debug(`No local branch to delete with name: ${branchName}`);
}
delete config.branchCommits[branchName];
}
export async function mergeToLocal(refSpecToMerge: string): Promise<void> {
let status: StatusResult | undefined;
try {
await syncGit();
await writeGitAuthor();
await git.reset(ResetMode.HARD);
await gitRetry(() =>
git.checkout([
'-B',
config.currentBranch,
'origin/' + config.currentBranch,
]),
);
status = await git.status();
await fetchRevSpec(refSpecToMerge);
await gitRetry(() => git.merge(['FETCH_HEAD']));
} catch (err) {
logger.debug(
{
baseBranch: config.currentBranch,
baseSha: config.currentBranchSha,
refSpecToMerge,
status,
err,
},
'mergeLocally error',
);
throw err;
}
}
export async function mergeBranch(branchName: string): Promise<void> {
let status: StatusResult | undefined;
try {
await syncGit();
await writeGitAuthor();
await git.reset(ResetMode.HARD);
await gitRetry(() =>
git.checkout(['-B', branchName, 'origin/' + branchName]),
);
await gitRetry(() =>
git.checkout([
'-B',
config.currentBranch,
'origin/' + config.currentBranch,
]),
);
status = await git.status();
await gitRetry(() => git.merge(['--ff-only', branchName]));
await gitRetry(() => git.push('origin', config.currentBranch));
incLimitedValue('Commits');
} catch (err) {
logger.debug(
{
baseBranch: config.currentBranch,
baseSha: config.currentBranchSha,
branchName,
branchSha: getBranchCommit(branchName),
status,
err,
},
'mergeBranch error',
);
throw err;
}
}
export async function getBranchLastCommitTime(
branchName: string,
): Promise<Date> {
await syncGit();
try {
const time = await git.show(['-s', '--format=%ai', 'origin/' + branchName]);
return new Date(Date.parse(time));
} catch (err) {
const errChecked = checkForPlatformFailure(err);
// istanbul ignore if
if (errChecked) {
throw errChecked;
}
return new Date();
}
}
export async function getBranchFiles(
branchName: string,
): Promise<string[] | null> {
await syncGit();
try {
const diff = await gitRetry(() =>
git.diffSummary([`origin/${branchName}`, `origin/${branchName}^`]),
);
return diff.files.map((file) => file.file);
} catch (err) /* istanbul ignore next */ {
logger.warn({ err }, 'getBranchFiles error');
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}
return null;
}
}
export async function getFile(
filePath: string,
branchName?: string,
): Promise<string | null> {
await syncGit();
try {
const content = await git.show([
'origin/' + (branchName ?? config.currentBranch) + ':' + filePath,
]);
return content;
} catch (err) {
const errChecked = checkForPlatformFailure(err);
// istanbul ignore if
if (errChecked) {
throw errChecked;
}
return null;
}
}
export async function getFiles(
fileNames: string[],
): Promise<Record<string, string | null>> {
const fileContentMap: Record<string, string | null> = {};
for (const fileName of fileNames) {
fileContentMap[fileName] = await getFile(fileName);
}
return fileContentMap;
}
export async function hasDiff(
sourceRef: string,
targetRef: string,
): Promise<boolean> {
await syncGit();
try {
return (
(await gitRetry(() => git.diff([sourceRef, targetRef, '--']))) !== ''
);
} catch (err) {
return true;
}
}
async function handleCommitAuth(localDir: string): Promise<void> {
if (!privateKeySet) {
await writePrivateKey();
privateKeySet = true;
}
await configSigningKey(localDir);
await writeGitAuthor();
}
/**
*
* Prepare local branch with commit
*
* 0. Hard reset
* 1. Creates local branch with `origin/` prefix
* 2. Perform `git add` (respecting mode) and `git remove` for each file
* 3. Perform commit
* 4. Check whether resulting commit is empty or not (due to .gitignore)
* 5. If not empty, return commit info for further processing
*
*/
export async function prepareCommit({
branchName,
files,
message,
force = false,
}: CommitFilesConfig): Promise<CommitResult | null> {
const localDir = GlobalConfig.get('localDir')!;
await syncGit();
logger.debug(`Preparing files for committing to branch ${branchName}`);
await handleCommitAuth(localDir);
try {
await git.reset(ResetMode.HARD);
await git.raw(['clean', '-fd']);
const parentCommitSha = config.currentBranchSha;
await gitRetry(() =>
git.checkout(['-B', branchName, 'origin/' + config.currentBranch]),
);
const deletedFiles: string[] = [];
const addedModifiedFiles: string[] = [];
const ignoredFiles: string[] = [];
for (const file of files) {
const fileName = file.path;
if (file.type === 'deletion') {
try {
await git.rm([fileName]);
deletedFiles.push(fileName);
} catch (err) /* istanbul ignore next */ {
const errChecked = checkForPlatformFailure(err);
if (errChecked) {
throw errChecked;
}