/
index.ts
955 lines (839 loc) · 26.3 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
import URL from 'url';
import { configFileNames } from '../../config/app-strings';
import { RenovateConfig } from '../../config/common';
import {
REPOSITORY_ACCESS_FORBIDDEN,
REPOSITORY_ARCHIVED,
REPOSITORY_BLOCKED,
REPOSITORY_CHANGED,
REPOSITORY_DISABLED,
REPOSITORY_EMPTY,
REPOSITORY_MIRRORED,
} from '../../constants/error-messages';
import { PLATFORM_TYPE_GITEA } from '../../constants/platforms';
import { PR_STATE_ALL, PR_STATE_OPEN } from '../../constants/pull-requests';
import { logger } from '../../logger';
import { BranchStatus } from '../../types';
import * as hostRules from '../../util/host-rules';
import { setBaseUrl } from '../../util/http/gitea';
import { sanitize } from '../../util/sanitize';
import { ensureTrailingSlash } from '../../util/url';
import {
BranchStatusConfig,
CommitFilesConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueConfig,
FindPRConfig,
Issue,
Platform,
PlatformConfig,
Pr,
RepoConfig,
RepoParams,
VulnerabilityAlert,
} from '../common';
import GitStorage, { StatusResult } from '../git/storage';
import { smartTruncate } from '../utils/pr-body';
import * as helper from './gitea-helper';
type GiteaRenovateConfig = {
endpoint: string;
token: string;
} & RenovateConfig;
interface GiteaRepoConfig {
storage: GitStorage;
repository: string;
localDir: string;
defaultBranch: string;
baseBranch: string;
mergeMethod: helper.PRMergeMethod;
prList: Promise<Pr[]> | null;
issueList: Promise<Issue[]> | null;
labelList: Promise<helper.Label[]> | null;
}
const defaults: any = {
hostType: PLATFORM_TYPE_GITEA,
endpoint: 'https://gitea.com/api/v1/',
};
const defaultConfigFile = configFileNames[0];
let config: GiteaRepoConfig = {} as any;
let botUserID: number;
function toRenovateIssue(data: helper.Issue): Issue {
return {
number: data.number,
state: data.state,
title: data.title,
body: data.body,
};
}
function toRenovatePR(data: helper.PR): Pr | null {
if (!data) {
return null;
}
if (
!data.base?.ref ||
!data.head?.label ||
!data.head?.sha ||
!data.head?.repo?.full_name
) {
logger.trace(
`Skipping Pull Request #${data.number} due to missing base and/or head branch`
);
return null;
}
return {
number: data.number,
displayNumber: `Pull Request #${data.number}`,
state: data.state,
title: data.title,
body: data.body,
sha: data.head.sha,
branchName: data.head.label,
targetBranch: data.base.ref,
sourceRepo: data.head.repo.full_name,
createdAt: data.created_at,
canMerge: data.mergeable,
isConflicted: !data.mergeable,
isStale: undefined,
isModified: undefined,
};
}
function matchesState(actual: string, expected: string): boolean {
if (expected === PR_STATE_ALL) {
return true;
}
if (expected.startsWith('!')) {
return actual !== expected.substring(1);
}
return actual === expected;
}
function findCommentByTopic(
comments: helper.Comment[],
topic: string
): helper.Comment | null {
return comments.find((c) => c.body.startsWith(`### ${topic}\n\n`));
}
function findCommentByContent(
comments: helper.Comment[],
content: string
): helper.Comment | null {
return comments.find((c) => c.body.trim() === content);
}
async function isPRModified(
repoPath: string,
branchName: string
): Promise<boolean> {
try {
const branch = await helper.getBranch(repoPath, branchName);
const branchCommitEmail = branch.commit.author.email;
const configEmail = global.gitAuthor.email;
if (branchCommitEmail === configEmail) {
return false;
}
logger.debug(
{ branchCommitEmail, configEmail },
'Last committer to branch does not match bot, PR cannot be rebased'
);
return true;
} catch (err) {
logger.warn({ err }, 'Error getting PR branch, marking as modified');
return true;
}
}
async function retrieveDefaultConfig(
repoPath: string,
branchName: string
): Promise<RenovateConfig> {
const contents = await helper.getRepoContents(
repoPath,
defaultConfigFile,
branchName
);
return JSON.parse(contents.contentString);
}
function getLabelList(): Promise<helper.Label[]> {
if (config.labelList === null) {
const repoLabels = helper
.getRepoLabels(config.repository, {
useCache: false,
})
.then((labels) => {
logger.debug(`Retrieved ${labels.length} repo labels`);
return labels;
});
const orgLabels = helper
.getOrgLabels(config.repository.split('/')[0], {
useCache: false,
})
.then((labels) => {
logger.debug(`Retrieved ${labels.length} org labels`);
return labels;
})
.catch((err) => {
// Will fail if owner of repo is not org or Gitea version < 1.12
logger.debug(`Unable to fetch organization labels`);
return [];
});
config.labelList = Promise.all([repoLabels, orgLabels]).then((labels) => {
return [].concat(...labels);
});
}
return config.labelList;
}
async function lookupLabelByName(name: string): Promise<number | null> {
logger.debug(`lookupLabelByName(${name})`);
const labelList = await getLabelList();
return labelList.find((l) => l.name === name)?.id;
}
const platform: Platform = {
async initPlatform({
endpoint,
token,
}: GiteaRenovateConfig): Promise<PlatformConfig> {
if (!token) {
throw new Error('Init: You must configure a Gitea personal access token');
}
if (endpoint) {
defaults.endpoint = ensureTrailingSlash(endpoint);
} else {
logger.debug('Using default Gitea endpoint: ' + defaults.endpoint);
}
setBaseUrl(defaults.endpoint);
let gitAuthor: string;
try {
const user = await helper.getCurrentUser({ token });
gitAuthor = `${user.full_name || user.username} <${user.email}>`;
botUserID = user.id;
} catch (err) {
logger.debug(
{ err },
'Error authenticating with Gitea. Check your token'
);
throw new Error('Init: Authentication failure');
}
return {
endpoint: defaults.endpoint,
gitAuthor,
};
},
async initRepo({
repository,
localDir,
optimizeForDisabled,
}: RepoParams): Promise<RepoConfig> {
let renovateConfig: RenovateConfig;
let repo: helper.Repo;
config = {} as any;
config.repository = repository;
config.localDir = localDir;
// Attempt to fetch information about repository
try {
repo = await helper.getRepo(repository);
} catch (err) {
logger.debug({ err }, 'Unknown Gitea initRepo error');
throw err;
}
// Ensure appropriate repository state and permissions
if (repo.archived) {
logger.debug(
'Repository is archived - throwing error to abort renovation'
);
throw new Error(REPOSITORY_ARCHIVED);
}
if (repo.mirror) {
logger.debug(
'Repository is a mirror - throwing error to abort renovation'
);
throw new Error(REPOSITORY_MIRRORED);
}
if (!repo.permissions.pull || !repo.permissions.push) {
logger.debug(
'Repository does not permit pull and push - throwing error to abort renovation'
);
throw new Error(REPOSITORY_ACCESS_FORBIDDEN);
}
if (repo.empty) {
logger.debug('Repository is empty - throwing error to abort renovation');
throw new Error(REPOSITORY_EMPTY);
}
if (repo.allow_rebase) {
config.mergeMethod = 'rebase';
} else if (repo.allow_rebase_explicit) {
config.mergeMethod = 'rebase-merge';
} else if (repo.allow_squash_merge) {
config.mergeMethod = 'squash';
} else if (repo.allow_merge_commits) {
config.mergeMethod = 'merge';
} else {
logger.debug(
'Repository has no allowed merge methods - throwing error to abort renovation'
);
throw new Error(REPOSITORY_BLOCKED);
}
// Determine author email and branches
config.defaultBranch = repo.default_branch;
config.baseBranch = config.defaultBranch;
logger.debug(`${repository} default branch = ${config.baseBranch}`);
// Optionally check if Renovate is disabled by attempting to fetch default configuration file
if (optimizeForDisabled) {
try {
renovateConfig = await retrieveDefaultConfig(
config.repository,
config.defaultBranch
);
} catch (err) {
// Do nothing
}
if (renovateConfig && renovateConfig.enabled === false) {
throw new Error(REPOSITORY_DISABLED);
}
}
// Find options for current host and determine Git endpoint
const opts = hostRules.find({
hostType: PLATFORM_TYPE_GITEA,
url: defaults.endpoint,
});
const gitEndpoint = URL.parse(repo.clone_url);
gitEndpoint.auth = opts.token;
// Initialize Git storage
config.storage = new GitStorage();
await config.storage.initRepo({
...config,
url: URL.format(gitEndpoint),
});
// Reset cached resources
config.prList = null;
config.issueList = null;
config.labelList = null;
return {
baseBranch: config.baseBranch,
isFork: !!repo.fork,
};
},
async getRepos(): Promise<string[]> {
logger.debug('Auto-discovering Gitea repositories');
try {
const repos = await helper.searchRepos({ uid: botUserID });
return repos.map((r) => r.full_name);
} catch (err) {
logger.error({ err }, 'Gitea getRepos() error');
throw err;
}
},
cleanRepo(): Promise<void> {
if (config.storage) {
config.storage.cleanRepo();
}
config = {} as any;
return Promise.resolve();
},
async setBranchStatus({
branchName,
context,
description,
state,
url: target_url,
}: BranchStatusConfig): Promise<void> {
try {
// Create new status for branch commit
const branchCommit = await config.storage.getBranchCommit(branchName);
await helper.createCommitStatus(config.repository, branchCommit, {
state: helper.renovateToGiteaStatusMapping[state] || 'pending',
context,
description,
...(target_url && { target_url }),
});
// Refresh caches by re-fetching commit status for branch
await helper.getCombinedCommitStatus(config.repository, branchName, {
useCache: false,
});
} catch (err) {
logger.warn({ err }, 'Failed to set branch status');
}
},
async getBranchStatus(
branchName: string,
requiredStatusChecks?: string[] | null
): Promise<BranchStatus> {
if (!requiredStatusChecks) {
return BranchStatus.green;
}
if (Array.isArray(requiredStatusChecks) && requiredStatusChecks.length) {
logger.warn({ requiredStatusChecks }, 'Unsupported requiredStatusChecks');
return BranchStatus.red;
}
let ccs: helper.CombinedCommitStatus;
try {
ccs = await helper.getCombinedCommitStatus(config.repository, branchName);
} catch (err) {
if (err.statusCode === 404) {
logger.debug(
'Received 404 when checking branch status, assuming branch deletion'
);
throw new Error(REPOSITORY_CHANGED);
}
logger.debug('Unknown error when checking branch status');
throw err;
}
logger.debug({ ccs }, 'Branch status check result');
return (
helper.giteaToRenovateStatusMapping[ccs.worstStatus] ||
BranchStatus.yellow
);
},
async getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus | null> {
const ccs = await helper.getCombinedCommitStatus(
config.repository,
branchName
);
const cs = ccs.statuses.find((s) => s.context === context);
if (!cs) {
return null;
} // no status check exists
const status = helper.giteaToRenovateStatusMapping[cs.status];
if (status) {
return status;
}
logger.warn(
{ check: cs },
'Could not map Gitea status value to Renovate status'
);
return BranchStatus.yellow;
},
async setBaseBranch(
baseBranch: string = config.defaultBranch
): Promise<string> {
config.baseBranch = baseBranch;
const baseBranchSha = await config.storage.setBaseBranch(baseBranch);
return baseBranchSha;
},
getPrList(): Promise<Pr[]> {
if (config.prList === null) {
config.prList = helper
.searchPRs(config.repository, {}, { useCache: false })
.then((prs) => {
const prList = prs.map(toRenovatePR).filter(Boolean);
logger.debug(`Retrieved ${prList.length} Pull Requests`);
return prList;
});
}
return config.prList;
},
/* istanbul ignore next */
async getPrFiles(pr: Pr): Promise<string[]> {
return config.storage.getBranchFiles(pr.branchName, pr.targetBranch);
},
async getPr(number: number): Promise<Pr | null> {
// Search for pull request in cached list or attempt to query directly
const prList = await platform.getPrList();
let pr = prList.find((p) => p.number === number);
if (pr) {
logger.debug('Returning from cached PRs');
} else {
logger.debug('PR not found in cached PRs - trying to fetch directly');
const gpr = await helper.getPR(config.repository, number);
pr = toRenovatePR(gpr);
// Add pull request to cache for further lookups / queries
if (config.prList !== null) {
(await config.prList).push(pr);
}
}
// Abort and return null if no match was found
if (!pr) {
return null;
}
// Enrich pull request with additional information which is more expensive to fetch
if (pr.state !== 'closed') {
if (pr.isStale === undefined) {
pr.isStale = await platform.isBranchStale(pr.branchName);
}
if (pr.isModified === undefined) {
pr.isModified = await isPRModified(config.repository, pr.branchName);
}
}
return pr;
},
async findPr({
branchName,
prTitle: title,
state = PR_STATE_ALL,
}: FindPRConfig): Promise<Pr> {
logger.debug(`findPr(${branchName}, ${title}, ${state})`);
const prList = await platform.getPrList();
const pr = prList.find(
(p) =>
p.sourceRepo === config.repository &&
p.branchName === branchName &&
matchesState(p.state, state) &&
(!title || p.title === title)
);
if (pr) {
logger.debug(`Found PR #${pr.number}`);
}
return pr ?? null;
},
async createPr({
branchName,
prTitle: title,
prBody: rawBody,
labels: labelNames,
useDefaultBranch,
}: CreatePRConfig): Promise<Pr> {
const base = useDefaultBranch ? config.defaultBranch : config.baseBranch;
const head = branchName;
const body = sanitize(rawBody);
logger.debug(`Creating pull request: ${title} (${head} => ${base})`);
try {
const labels = Array.isArray(labelNames)
? await Promise.all(labelNames.map(lookupLabelByName))
: [];
const gpr = await helper.createPR(config.repository, {
base,
head,
title,
body,
labels: labels.filter(Boolean),
});
const pr = toRenovatePR(gpr);
if (!pr) {
throw new Error('Can not parse newly created Pull Request');
}
if (config.prList !== null) {
(await config.prList).push(pr);
}
return pr;
} catch (err) {
// When the user manually deletes a branch from Renovate, the PR remains but is no longer linked to any branch. In
// the most recent versions of Gitea, the PR gets automatically closed when that happens, but older versions do
// not handle this properly and keep the PR open. As pushing a branch with the same name resurrects the PR, this
// would cause a HTTP 409 conflict error, which we hereby gracefully handle.
if (err.statusCode === 409) {
logger.warn(
`Attempting to gracefully recover from 409 Conflict response in createPr(${title}, ${branchName})`
);
// Refresh cached PR list and search for pull request with matching information
config.prList = null;
const pr = await platform.findPr({
branchName,
state: PR_STATE_OPEN,
});
// If a valid PR was found, return and gracefully recover from the error. Otherwise, abort and throw error.
if (pr) {
if (pr.title !== title || pr.body !== body) {
logger.debug(
`Recovered from 409 Conflict, but PR for ${branchName} is outdated. Updating...`
);
await platform.updatePr(pr.number, title, body);
pr.title = title;
pr.body = body;
} else {
logger.debug(
`Recovered from 409 Conflict and PR for ${branchName} is up-to-date`
);
}
return pr;
}
}
throw err;
}
},
async updatePr(number: number, title: string, body?: string): Promise<void> {
await helper.updatePR(config.repository, number, {
title,
...(body && { body }),
});
},
async mergePr(number: number, branchName: string): Promise<boolean> {
try {
await helper.mergePR(config.repository, number, config.mergeMethod);
return true;
} catch (err) {
logger.warn({ err, number }, 'Merging of PR failed');
return false;
}
},
getIssueList(): Promise<Issue[]> {
if (config.issueList === null) {
config.issueList = helper
.searchIssues(config.repository, {}, { useCache: false })
.then((issues) => {
const issueList = issues.map(toRenovateIssue);
logger.debug(`Retrieved ${issueList.length} Issues`);
return issueList;
});
}
return config.issueList;
},
async findIssue(title: string): Promise<Issue> {
const issueList = await platform.getIssueList();
const issue = issueList.find(
(i) => i.state === 'open' && i.title === title
);
if (issue) {
logger.debug(`Found Issue #${issue.number}`);
}
return issue ?? null;
},
async ensureIssue({
title,
body,
shouldReOpen,
once,
}: EnsureIssueConfig): Promise<'updated' | 'created' | null> {
logger.debug(`ensureIssue(${title})`);
try {
const issueList = await platform.getIssueList();
const issues = issueList.filter((i) => i.title === title);
// Update any matching issues which currently exist
if (issues.length) {
let activeIssue = issues.find((i) => i.state === 'open');
// If no active issue was found, decide if it shall be skipped, re-opened or updated without state change
if (!activeIssue) {
if (once) {
logger.debug('Issue already closed - skipping update');
return null;
}
if (shouldReOpen) {
logger.debug('Reopening previously closed Issue');
}
// Pick the last issue in the list as the active one
activeIssue = issues[issues.length - 1];
}
// Close any duplicate issues
for (const issue of issues) {
if (issue.state === 'open' && issue.number !== activeIssue.number) {
logger.warn(`Closing duplicate Issue #${issue.number}`);
await helper.closeIssue(config.repository, issue.number);
}
}
// Check if issue has already correct state
if (activeIssue.body === body && activeIssue.state === 'open') {
logger.debug(
`Issue #${activeIssue.number} is open and up to date - nothing to do`
);
return null;
}
// Update issue body and re-open if enabled
logger.debug(`Updating Issue #${activeIssue.number}`);
await helper.updateIssue(config.repository, activeIssue.number, {
body,
state: shouldReOpen
? 'open'
: (activeIssue.state as helper.IssueState),
});
return 'updated';
}
// Create new issue and reset cache
const issue = await helper.createIssue(config.repository, {
body,
title,
});
logger.debug(`Created new Issue #${issue.number}`);
config.issueList = null;
return 'created';
} catch (err) {
logger.warn({ err }, 'Could not ensure issue');
}
return null;
},
async ensureIssueClosing(title: string): Promise<void> {
logger.debug(`ensureIssueClosing(${title})`);
const issueList = await platform.getIssueList();
for (const issue of issueList) {
if (issue.state === 'open' && issue.title === title) {
logger.debug({ number: issue.number }, 'Closing issue');
await helper.closeIssue(config.repository, issue.number);
}
}
},
async deleteLabel(issue: number, labelName: string): Promise<void> {
logger.debug(`Deleting label ${labelName} from Issue #${issue}`);
const label = await lookupLabelByName(labelName);
if (label) {
await helper.unassignLabel(config.repository, issue, label);
} else {
logger.warn({ issue, labelName }, 'Failed to lookup label for deletion');
}
return null;
},
getRepoForceRebase(): Promise<boolean> {
return Promise.resolve(false);
},
async ensureComment({
number: issue,
topic,
content,
}: EnsureCommentConfig): Promise<boolean> {
try {
let body = sanitize(content);
const commentList = await helper.getComments(config.repository, issue);
// Search comment by either topic or exact body
let comment: helper.Comment = null;
if (topic) {
comment = findCommentByTopic(commentList, topic);
body = `### ${topic}\n\n${body}`;
} else {
comment = commentList.find((c) => c.body === body);
}
// Create a new comment if no match has been found, otherwise update if necessary
if (!comment) {
const c = await helper.createComment(config.repository, issue, body);
logger.info(
{ repository: config.repository, issue, comment: c.id },
'Comment added'
);
} else if (comment.body !== body) {
const c = await helper.updateComment(config.repository, issue, body);
logger.debug(
{ repository: config.repository, issue, comment: c.id },
'Comment updated'
);
} else {
logger.debug(`Comment #${comment.id} is already up-to-date`);
}
return true;
} catch (err) {
logger.warn({ err }, 'Error ensuring comment');
return false;
}
},
async ensureCommentRemoval({
number: issue,
topic,
content,
}: EnsureCommentRemovalConfig): Promise<void> {
logger.debug(
`Ensuring comment "${topic || content}" in #${issue} is removed`
);
const commentList = await helper.getComments(config.repository, issue);
let comment: helper.Comment | null = null;
if (topic) {
comment = findCommentByTopic(commentList, topic);
} else if (content) {
comment = findCommentByContent(commentList, content);
}
// Abort and do nothing if no matching comment was found
if (!comment) {
return;
}
// Attempt to delete comment
try {
await helper.deleteComment(config.repository, comment.id);
} catch (err) {
logger.warn({ err, issue, subject: topic }, 'Error deleting comment');
}
},
async getBranchPr(branchName: string): Promise<Pr | null> {
logger.debug(`getBranchPr(${branchName})`);
const pr = await platform.findPr({ branchName, state: PR_STATE_OPEN });
return pr ? platform.getPr(pr.number) : null;
},
async deleteBranch(branchName: string, closePr?: boolean): Promise<void> {
logger.debug(`deleteBranch(${branchName})`);
if (closePr) {
const pr = await platform.getBranchPr(branchName);
if (pr) {
await helper.closePR(config.repository, pr.number);
}
}
return config.storage.deleteBranch(branchName);
},
async addAssignees(number: number, assignees: string[]): Promise<void> {
logger.debug(`Updating assignees ${assignees} on Issue #${number}`);
await helper.updateIssue(config.repository, number, {
assignees,
});
},
addReviewers(number: number, reviewers: string[]): Promise<void> {
// Adding reviewers to a PR through API is not supported by Gitea as of today
// See tracking issue: https://github.com/go-gitea/gitea/issues/5733
logger.debug(`Updating reviewers ${reviewers} on Pull Request #${number}`);
logger.warn('Unimplemented in Gitea: Reviewers');
return Promise.resolve();
},
commitFiles(commitFilesConfig: CommitFilesConfig): Promise<string | null> {
return config.storage.commitFiles(commitFilesConfig);
},
getPrBody(prBody: string): string {
return smartTruncate(prBody, 1000000);
},
isBranchStale(branchName: string): Promise<boolean> {
return config.storage.isBranchStale(branchName);
},
setBranchPrefix(branchPrefix: string): Promise<void> {
return config.storage.setBranchPrefix(branchPrefix);
},
branchExists(branchName: string): Promise<boolean> {
return config.storage.branchExists(branchName);
},
mergeBranch(branchName: string): Promise<void> {
return config.storage.mergeBranch(branchName);
},
getBranchLastCommitTime(branchName: string): Promise<Date> {
return config.storage.getBranchLastCommitTime(branchName);
},
getFile(lockFileName: string, branchName?: string): Promise<string> {
return config.storage.getFile(lockFileName, branchName);
},
getRepoStatus(): Promise<StatusResult> {
return config.storage.getRepoStatus();
},
getFileList(): Promise<string[]> {
return config.storage.getFileList();
},
getAllRenovateBranches(branchPrefix: string): Promise<string[]> {
return config.storage.getAllRenovateBranches(branchPrefix);
},
getCommitMessages(): Promise<string[]> {
return config.storage.getCommitMessages();
},
getVulnerabilityAlerts(): Promise<VulnerabilityAlert[]> {
return Promise.resolve([]);
},
};
export const {
addAssignees,
addReviewers,
branchExists,
cleanRepo,
commitFiles,
createPr,
deleteBranch,
deleteLabel,
ensureComment,
ensureCommentRemoval,
ensureIssue,
ensureIssueClosing,
findIssue,
findPr,
getAllRenovateBranches,
getBranchLastCommitTime,
getBranchPr,
getBranchStatus,
getBranchStatusCheck,
getCommitMessages,
getFile,
getFileList,
getIssueList,
getPr,
getPrBody,
getPrList,
getPrFiles,
getRepoForceRebase,
getRepoStatus,
getRepos,
getVulnerabilityAlerts,
initPlatform,
initRepo,
isBranchStale,
mergeBranch,
mergePr,
setBaseBranch,
setBranchPrefix,
setBranchStatus,
updatePr,
} = platform;