/
index.ts
1039 lines (979 loc) · 29.1 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, { URLSearchParams } from 'url';
import is from '@sindresorhus/is';
import delay from 'delay';
import { configFileNames } from '../../config/app-strings';
import { RenovateConfig } from '../../config/common';
import {
PLATFORM_AUTHENTICATION_ERROR,
REPOSITORY_ACCESS_FORBIDDEN,
REPOSITORY_ARCHIVED,
REPOSITORY_CHANGED,
REPOSITORY_DISABLED,
REPOSITORY_EMPTY,
REPOSITORY_MIRRORED,
REPOSITORY_NOT_FOUND,
} from '../../constants/error-messages';
import { PLATFORM_TYPE_GITLAB } from '../../constants/platforms';
import { PR_STATE_ALL, PR_STATE_OPEN } from '../../constants/pull-requests';
import { logger } from '../../logger';
import { BranchStatus } from '../../types';
import * as git from '../../util/git';
import * as hostRules from '../../util/host-rules';
import { HttpResponse } from '../../util/http';
import { GitlabHttp, setBaseUrl } from '../../util/http/gitlab';
import { sanitize } from '../../util/sanitize';
import { ensureTrailingSlash } from '../../util/url';
import {
BranchStatusConfig,
CreatePRConfig,
EnsureCommentConfig,
EnsureCommentRemovalConfig,
EnsureIssueConfig,
FindPRConfig,
Issue,
PlatformConfig,
Pr,
RepoConfig,
RepoParams,
VulnerabilityAlert,
} from '../common';
import { smartTruncate } from '../utils/pr-body';
const gitlabApi = new GitlabHttp();
type MergeMethod = 'merge' | 'rebase_merge' | 'ff';
type RepoResponse = {
archived: boolean;
mirror: boolean;
default_branch: string;
empty_repo: boolean;
http_url_to_repo: string;
forked_from_project: boolean;
repository_access_level: 'disabled' | 'private' | 'enabled';
merge_requests_access_level: 'disabled' | 'private' | 'enabled';
merge_method: MergeMethod;
path_with_namespace: string;
};
const defaultConfigFile = configFileNames[0];
let config: {
repository: string;
localDir: string;
defaultBranch: string;
baseBranch: string;
email: string;
prList: any[];
issueList: any[];
optimizeForDisabled: boolean;
mergeMethod: MergeMethod;
} = {} as any;
const defaults = {
hostType: PLATFORM_TYPE_GITLAB,
endpoint: 'https://gitlab.com/api/v4/',
};
let authorId: number;
export async function initPlatform({
endpoint,
token,
}: {
token: string;
endpoint: string;
}): Promise<PlatformConfig> {
if (!token) {
throw new Error('Init: You must configure a GitLab personal access token');
}
if (endpoint) {
defaults.endpoint = ensureTrailingSlash(endpoint);
setBaseUrl(defaults.endpoint);
} else {
logger.debug('Using default GitLab endpoint: ' + defaults.endpoint);
}
let gitAuthor: string;
try {
const user = (
await gitlabApi.getJson<{ email: string; name: string; id: number }>(
`user`,
{ token }
)
).body;
gitAuthor = `${user.name} <${user.email}>`;
authorId = user.id;
} catch (err) {
logger.debug(
{ err },
'Error authenticating with GitLab. Check that your token includes "user" permissions'
);
throw new Error('Init: Authentication failure');
}
const platformConfig: PlatformConfig = {
endpoint: defaults.endpoint,
gitAuthor,
};
return platformConfig;
}
// Get all repositories that the user has access to
export async function getRepos(): Promise<string[]> {
logger.debug('Autodiscovering GitLab repositories');
try {
const url = `projects?membership=true&per_page=100&with_merge_requests_enabled=true&min_access_level=30`;
const res = await gitlabApi.getJson<RepoResponse[]>(url, {
paginate: true,
});
logger.debug(`Discovered ${res.body.length} project(s)`);
return res.body
.filter((repo) => !repo.mirror && !repo.archived)
.map((repo) => repo.path_with_namespace);
} catch (err) {
logger.error({ err }, `GitLab getRepos error`);
throw err;
}
}
function urlEscape(str: string): string {
return str ? str.replace(/\//g, '%2F') : str;
}
// Initialize GitLab by getting base branch
export async function initRepo({
repository,
localDir,
optimizeForDisabled,
}: RepoParams): Promise<RepoConfig> {
config = {} as any;
config.repository = urlEscape(repository);
config.localDir = localDir;
let res: HttpResponse<RepoResponse>;
try {
res = await gitlabApi.getJson<RepoResponse>(
`projects/${config.repository}`
);
if (res.body.archived) {
logger.debug(
'Repository is archived - throwing error to abort renovation'
);
throw new Error(REPOSITORY_ARCHIVED);
}
if (res.body.mirror) {
logger.debug(
'Repository is a mirror - throwing error to abort renovation'
);
throw new Error(REPOSITORY_MIRRORED);
}
if (res.body.repository_access_level === 'disabled') {
logger.debug(
'Repository portion of project is disabled - throwing error to abort renovation'
);
throw new Error(REPOSITORY_DISABLED);
}
if (res.body.merge_requests_access_level === 'disabled') {
logger.debug(
'MRs are disabled for the project - throwing error to abort renovation'
);
throw new Error(REPOSITORY_DISABLED);
}
if (res.body.default_branch === null || res.body.empty_repo) {
throw new Error(REPOSITORY_EMPTY);
}
if (optimizeForDisabled) {
let renovateConfig: RenovateConfig;
try {
renovateConfig = JSON.parse(
Buffer.from(
(
await gitlabApi.getJson<{ content: string }>(
`projects/${config.repository}/repository/files/${defaultConfigFile}?ref=${res.body.default_branch}`
)
).body.content,
'base64'
).toString()
);
} catch (err) {
// Do nothing
}
if (renovateConfig && renovateConfig.enabled === false) {
throw new Error(REPOSITORY_DISABLED);
}
}
config.defaultBranch = res.body.default_branch;
config.baseBranch = config.defaultBranch;
config.mergeMethod = res.body.merge_method || 'merge';
logger.debug(`${repository} default branch = ${config.baseBranch}`);
delete config.prList;
logger.debug('Enabling Git FS');
const opts = hostRules.find({
hostType: defaults.hostType,
url: defaults.endpoint,
});
let url: string;
if (
process.env.GITLAB_IGNORE_REPO_URL ||
res.body.http_url_to_repo === null
) {
logger.debug('no http_url_to_repo found. Falling back to old behaviour.');
const { host, protocol } = URL.parse(defaults.endpoint);
url = git.getUrl({
protocol: protocol.slice(0, -1) as any,
auth: 'oauth2:' + opts.token,
host,
repository,
});
} else {
logger.debug(`${repository} http URL = ${res.body.http_url_to_repo}`);
const repoUrl = URL.parse(`${res.body.http_url_to_repo}`);
repoUrl.auth = 'oauth2:' + opts.token;
url = URL.format(repoUrl);
}
await git.initRepo({
...config,
url,
gitAuthorName: global.gitAuthor?.name,
gitAuthorEmail: global.gitAuthor?.email,
});
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Caught initRepo error');
if (err.message.includes('HEAD is not a symbolic ref')) {
throw new Error(REPOSITORY_EMPTY);
}
if ([REPOSITORY_ARCHIVED, REPOSITORY_EMPTY].includes(err.message)) {
throw err;
}
if (err.statusCode === 403) {
throw new Error(REPOSITORY_ACCESS_FORBIDDEN);
}
if (err.statusCode === 404) {
throw new Error(REPOSITORY_NOT_FOUND);
}
if (err.message === REPOSITORY_DISABLED) {
throw err;
}
logger.debug({ err }, 'Unknown GitLab initRepo error');
throw err;
}
const repoConfig: RepoConfig = {
baseBranch: config.baseBranch,
isFork: !!res.body.forked_from_project,
};
return repoConfig;
}
export function getRepoForceRebase(): Promise<boolean> {
return Promise.resolve(config?.mergeMethod !== 'merge');
}
export async function setBaseBranch(
branchName = config.baseBranch
): Promise<string> {
logger.debug(`Setting baseBranch to ${branchName}`);
config.baseBranch = branchName;
const baseBranchSha = await git.setBaseBranch(branchName);
return baseBranchSha;
}
type BranchState = 'pending' | 'running' | 'success' | 'failed' | 'canceled';
interface GitlabBranchStatus {
status: BranchState;
name: string;
allow_failure?: boolean;
}
async function getStatus(
branchName: string,
useCache = true
): Promise<GitlabBranchStatus[]> {
const branchSha = await git.getBranchCommit(branchName);
const url = `projects/${config.repository}/repository/commits/${branchSha}/statuses`;
return (
await gitlabApi.getJson<GitlabBranchStatus[]>(url, {
paginate: true,
useCache,
})
).body;
}
const gitlabToRenovateStatusMapping: Record<string, BranchStatus> = {
pending: BranchStatus.yellow,
created: BranchStatus.yellow,
manual: BranchStatus.yellow,
running: BranchStatus.yellow,
success: BranchStatus.green,
failed: BranchStatus.red,
canceled: BranchStatus.red,
skipped: BranchStatus.red,
};
// Returns the combined status for a branch.
export async function getBranchStatus(
branchName: string,
requiredStatusChecks?: string[] | null
): Promise<BranchStatus> {
logger.debug(`getBranchStatus(${branchName})`);
if (!requiredStatusChecks) {
// null means disable status checks, so it always succeeds
return BranchStatus.green;
}
if (Array.isArray(requiredStatusChecks) && requiredStatusChecks.length) {
// This is Unsupported
logger.warn({ requiredStatusChecks }, `Unsupported requiredStatusChecks`);
return BranchStatus.red;
}
if (!(await git.branchExists(branchName))) {
throw new Error(REPOSITORY_CHANGED);
}
const res = await getStatus(branchName);
logger.debug(`Got res with ${res.length} results`);
if (res.length === 0) {
// Return 'pending' if we have no status checks
return BranchStatus.yellow;
}
let status: BranchStatus = BranchStatus.green; // default to green
res
.filter((check) => !check.allow_failure)
.forEach((check) => {
if (status !== BranchStatus.red) {
// if red, stay red
let mappedStatus: BranchStatus =
gitlabToRenovateStatusMapping[check.status];
if (!mappedStatus) {
logger.warn(
{ check },
'Could not map GitLab check.status to Renovate status'
);
mappedStatus = BranchStatus.yellow;
}
if (mappedStatus !== BranchStatus.green) {
logger.trace({ check }, 'Found non-green check');
status = mappedStatus;
}
}
});
return status;
}
// Pull Request
export async function createPr({
branchName,
prTitle: title,
prBody: rawDescription,
labels,
useDefaultBranch,
platformOptions,
}: CreatePRConfig): Promise<Pr> {
const description = sanitize(rawDescription);
const targetBranch = useDefaultBranch
? config.defaultBranch
: config.baseBranch;
logger.debug(`Creating Merge Request: ${title}`);
const res = await gitlabApi.postJson<Pr & { iid: number }>(
`projects/${config.repository}/merge_requests`,
{
body: {
source_branch: branchName,
target_branch: targetBranch,
remove_source_branch: true,
title,
description,
labels: is.array(labels) ? labels.join(',') : null,
},
}
);
const pr = res.body;
pr.number = pr.iid;
pr.branchName = branchName;
pr.displayNumber = `Merge Request #${pr.iid}`;
pr.isModified = false;
// istanbul ignore if
if (config.prList) {
config.prList.push(pr);
}
if (platformOptions && platformOptions.gitLabAutomerge) {
try {
const desiredStatus = 'can_be_merged';
const retryTimes = 5;
// Check for correct merge request status before setting `merge_when_pipeline_succeeds` to `true`.
for (let attempt = 1; attempt <= retryTimes; attempt += 1) {
const { body } = await gitlabApi.getJson<{
merge_status: string;
pipeline: string;
}>(`projects/${config.repository}/merge_requests/${pr.iid}`);
// Only continue if the merge request can be merged and has a pipeline.
if (body.merge_status === desiredStatus && body.pipeline !== null) {
break;
}
await delay(500 * attempt);
}
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${pr.iid}/merge`,
{
body: {
should_remove_source_branch: true,
merge_when_pipeline_succeeds: true,
},
}
);
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Automerge on PR creation failed');
}
}
return pr;
}
export async function getPr(iid: number): Promise<Pr> {
logger.debug(`getPr(${iid})`);
const url = `projects/${config.repository}/merge_requests/${iid}?include_diverged_commits_count=1`;
const pr = (
await gitlabApi.getJson<
Pr & {
iid: number;
source_branch: string;
target_branch: string;
description: string;
diverged_commits_count: number;
merge_status: string;
}
>(url)
).body;
// Harmonize fields with GitHub
pr.branchName = pr.source_branch;
pr.targetBranch = pr.target_branch;
pr.number = pr.iid;
pr.displayNumber = `Merge Request #${pr.iid}`;
pr.body = pr.description;
pr.isStale = pr.diverged_commits_count > 0;
pr.state = pr.state === 'opened' ? PR_STATE_OPEN : pr.state;
pr.isModified = true;
if (pr.merge_status === 'cannot_be_merged') {
logger.debug('pr cannot be merged');
pr.canMerge = false;
pr.isConflicted = true;
} else if (pr.state === PR_STATE_OPEN) {
const branchStatus = await getBranchStatus(pr.branchName, []);
if (branchStatus === BranchStatus.green) {
pr.canMerge = true;
}
}
// Check if the most recent branch commit is by us
// If not then we don't allow it to be rebased, in case someone's changes would be lost
const branchUrl = `projects/${
config.repository
}/repository/branches/${urlEscape(pr.source_branch)}`;
try {
const branch = (
await gitlabApi.getJson<{ commit: { author_email: string } }>(branchUrl)
).body;
const branchCommitEmail =
branch && branch.commit ? branch.commit.author_email : null;
if (branchCommitEmail === global.gitAuthor.email) {
pr.isModified = false;
} else {
logger.debug(
{ branchCommitEmail, configEmail: global.gitAuthor.email, iid: pr.iid },
'Last committer to branch does not match bot email, so PR cannot be rebased.'
);
pr.isModified = true;
}
} catch (err) {
logger.debug({ err }, 'Error getting PR branch');
if (pr.state === PR_STATE_OPEN || err.statusCode !== 404) {
logger.warn({ err }, 'Error getting PR branch');
pr.isConflicted = true;
}
}
return pr;
}
// istanbul ignore next
async function closePr(iid: number): Promise<void> {
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${iid}`,
{
body: {
state_event: 'close',
},
}
);
}
export async function updatePr(
iid: number,
title: string,
description: string
): Promise<void> {
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${iid}`,
{
body: {
title,
description: sanitize(description),
},
}
);
}
export async function mergePr(iid: number): Promise<boolean> {
try {
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${iid}/merge`,
{
body: {
should_remove_source_branch: true,
},
}
);
return true;
} catch (err) /* istanbul ignore next */ {
if (err.statusCode === 401) {
logger.debug('No permissions to merge PR');
return false;
}
if (err.statusCode === 406) {
logger.debug({ err }, 'PR not acceptable for merging');
return false;
}
logger.debug({ err }, 'merge PR error');
logger.debug('PR merge failed');
return false;
}
}
export function getPrBody(input: string): string {
return smartTruncate(
input
.replace(/Pull Request/g, 'Merge Request')
.replace(/PR/g, 'MR')
.replace(/\]\(\.\.\/pull\//g, '](!'),
50000
);
}
// Branch
// Returns the Pull Request for a branch. Null if not exists.
export async function getBranchPr(branchName: string): Promise<Pr> {
logger.debug(`getBranchPr(${branchName})`);
// istanbul ignore if
if (!(await git.branchExists(branchName))) {
return null;
}
const query = new URLSearchParams({
per_page: '100',
state: 'opened',
source_branch: branchName,
}).toString();
const urlString = `projects/${config.repository}/merge_requests?${query}`;
const res = await gitlabApi.getJson<{ source_branch: string }[]>(urlString, {
paginate: true,
});
logger.debug(`Got res with ${res.body.length} results`);
let pr: any = null;
res.body.forEach((result) => {
if (result.source_branch === branchName) {
pr = result;
}
});
if (!pr) {
return null;
}
return getPr(pr.iid);
}
export async function deleteBranch(
branchName: string,
shouldClosePr = false
): Promise<void> {
if (shouldClosePr) {
logger.debug('Closing PR');
const pr = await getBranchPr(branchName);
// istanbul ignore if
if (pr) {
await closePr(pr.number);
}
}
return git.deleteBranch(branchName);
}
export async function getBranchStatusCheck(
branchName: string,
context: string
): Promise<BranchStatus | null> {
// cache-bust in case we have rebased
const res = await getStatus(branchName, false);
logger.debug(`Got res with ${res.length} results`);
for (const check of res) {
if (check.name === context) {
return gitlabToRenovateStatusMapping[check.status] || BranchStatus.yellow;
}
}
return null;
}
export async function setBranchStatus({
branchName,
context,
description,
state: renovateState,
url: targetUrl,
}: BranchStatusConfig): Promise<void> {
// First, get the branch commit SHA
const branchSha = await git.getBranchCommit(branchName);
// Now, check the statuses for that commit
const url = `projects/${config.repository}/statuses/${branchSha}`;
let state = 'success';
if (renovateState === BranchStatus.yellow) {
state = 'pending';
} else if (renovateState === BranchStatus.red) {
state = 'failed';
}
const options: any = {
state,
description,
context,
};
if (targetUrl) {
options.target_url = targetUrl;
}
try {
await gitlabApi.postJson(url, { body: options });
// update status cache
await getStatus(branchName, false);
} catch (err) /* istanbul ignore next */ {
if (
err.body &&
err.body.message &&
err.body.message.startsWith(
'Cannot transition status via :enqueue from :pending'
)
) {
// https://gitlab.com/gitlab-org/gitlab-foss/issues/25807
logger.debug('Ignoring status transition error');
} else {
logger.debug({ err });
logger.warn('Failed to set branch status');
}
}
}
// Issue
export async function getIssueList(): Promise<any[]> {
if (!config.issueList) {
const query = new URLSearchParams({
per_page: '100',
author_id: `${authorId}`,
state: 'opened',
}).toString();
const res = await gitlabApi.getJson<{ iid: number; title: string }[]>(
`projects/${config.repository}/issues?${query}`,
{
useCache: false,
paginate: true,
}
);
// istanbul ignore if
if (!is.array(res.body)) {
logger.warn({ responseBody: res.body }, 'Could not retrieve issue list');
return [];
}
config.issueList = res.body.map((i) => ({
iid: i.iid,
title: i.title,
}));
}
return config.issueList;
}
export async function findIssue(title: string): Promise<Issue | null> {
logger.debug(`findIssue(${title})`);
try {
const issueList = await getIssueList();
const issue = issueList.find((i: { title: string }) => i.title === title);
if (!issue) {
return null;
}
const issueBody = (
await gitlabApi.getJson<{ description: string }>(
`projects/${config.repository}/issues/${issue.iid}`
)
).body.description;
return {
number: issue.iid,
body: issueBody,
};
} catch (err) /* istanbul ignore next */ {
logger.warn('Error finding issue');
return null;
}
}
export async function ensureIssue({
title,
body,
}: EnsureIssueConfig): Promise<'updated' | 'created' | null> {
logger.debug(`ensureIssue()`);
const description = getPrBody(sanitize(body));
try {
const issueList = await getIssueList();
const issue = issueList.find((i: { title: string }) => i.title === title);
if (issue) {
const existingDescription = (
await gitlabApi.getJson<{ description: string }>(
`projects/${config.repository}/issues/${issue.iid}`
)
).body.description;
if (existingDescription !== description) {
logger.debug('Updating issue body');
await gitlabApi.putJson(
`projects/${config.repository}/issues/${issue.iid}`,
{
body: { description },
}
);
return 'updated';
}
} else {
await gitlabApi.postJson(`projects/${config.repository}/issues`, {
body: {
title,
description,
},
});
logger.info('Issue created');
// delete issueList so that it will be refetched as necessary
delete config.issueList;
return 'created';
}
} catch (err) /* istanbul ignore next */ {
if (err.message.startsWith('Issues are disabled for this repo')) {
logger.debug(`Could not create issue: ${err.message}`);
} else {
logger.warn({ err }, 'Could not ensure issue');
}
}
return null;
}
export async function ensureIssueClosing(title: string): Promise<void> {
logger.debug(`ensureIssueClosing()`);
const issueList = await getIssueList();
for (const issue of issueList) {
if (issue.title === title) {
logger.debug({ issue }, 'Closing issue');
await gitlabApi.putJson(
`projects/${config.repository}/issues/${issue.iid}`,
{
body: { state_event: 'close' },
}
);
}
}
}
export async function addAssignees(
iid: number,
assignees: string[]
): Promise<void> {
logger.debug(`Adding assignees ${assignees} to #${iid}`);
try {
let assigneeId = (
await gitlabApi.getJson<{ id: number }[]>(
`users?username=${assignees[0]}`
)
).body[0].id;
let url = `projects/${config.repository}/merge_requests/${iid}?assignee_id=${assigneeId}`;
await gitlabApi.putJson(url);
try {
if (assignees.length > 1) {
url = `projects/${config.repository}/merge_requests/${iid}?assignee_ids[]=${assigneeId}`;
for (let i = 1; i < assignees.length; i += 1) {
assigneeId = (
await gitlabApi.getJson<{ id: number }[]>(
`users?username=${assignees[i]}`
)
).body[0].id;
url += `&assignee_ids[]=${assigneeId}`;
}
await gitlabApi.putJson(url);
}
} catch (error) {
logger.error({ iid, assignees }, 'Failed to add multiple assignees');
}
} catch (err) {
logger.debug({ err }, 'addAssignees error');
logger.warn({ iid, assignees }, 'Failed to add assignees');
}
}
export function addReviewers(iid: number, reviewers: string[]): Promise<void> {
logger.debug(`addReviewers('${iid}, '${reviewers})`);
logger.warn('Unimplemented in GitLab: approvals');
return Promise.resolve();
}
export async function deleteLabel(
issueNo: number,
label: string
): Promise<void> {
logger.debug(`Deleting label ${label} from #${issueNo}`);
try {
const pr = await getPr(issueNo);
const labels = (pr.labels || []).filter((l: string) => l !== label).join();
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${issueNo}`,
{
body: { labels },
}
);
} catch (err) /* istanbul ignore next */ {
logger.warn({ err, issueNo, label }, 'Failed to delete label');
}
}
async function getComments(issueNo: number): Promise<GitlabComment[]> {
// GET projects/:owner/:repo/merge_requests/:number/notes
logger.debug(`Getting comments for #${issueNo}`);
const url = `projects/${config.repository}/merge_requests/${issueNo}/notes`;
const comments = (
await gitlabApi.getJson<GitlabComment[]>(url, { paginate: true })
).body;
logger.debug(`Found ${comments.length} comments`);
return comments;
}
async function addComment(issueNo: number, body: string): Promise<void> {
// POST projects/:owner/:repo/merge_requests/:number/notes
await gitlabApi.postJson(
`projects/${config.repository}/merge_requests/${issueNo}/notes`,
{
body: { body },
}
);
}
async function editComment(
issueNo: number,
commentId: number,
body: string
): Promise<void> {
// PUT projects/:owner/:repo/merge_requests/:number/notes/:id
await gitlabApi.putJson(
`projects/${config.repository}/merge_requests/${issueNo}/notes/${commentId}`,
{
body: { body },
}
);
}
async function deleteComment(
issueNo: number,
commentId: number
): Promise<void> {
// DELETE projects/:owner/:repo/merge_requests/:number/notes/:id
await gitlabApi.deleteJson(
`projects/${config.repository}/merge_requests/${issueNo}/notes/${commentId}`
);
}
export async function ensureComment({
number,
topic,
content,
}: EnsureCommentConfig): Promise<boolean> {
const sanitizedContent = sanitize(content);
const massagedTopic = topic
? topic.replace(/Pull Request/g, 'Merge Request').replace(/PR/g, 'MR')
: topic;
const comments = await getComments(number);
let body: string;
let commentId: number;
let commentNeedsUpdating: boolean;
if (topic) {
logger.debug(`Ensuring comment "${massagedTopic}" in #${number}`);
body = `### ${topic}\n\n${sanitizedContent}`;
body = body.replace(/Pull Request/g, 'Merge Request').replace(/PR/g, 'MR');
comments.forEach((comment: { body: string; id: number }) => {
if (comment.body.startsWith(`### ${massagedTopic}\n\n`)) {
commentId = comment.id;
commentNeedsUpdating = comment.body !== body;
}
});
} else {
logger.debug(`Ensuring content-only comment in #${number}`);
body = `${sanitizedContent}`;
comments.forEach((comment: { body: string; id: number }) => {
if (comment.body === body) {
commentId = comment.id;
commentNeedsUpdating = false;
}
});
}
if (!commentId) {
await addComment(number, body);
logger.debug(
{ repository: config.repository, issueNo: number },
'Added comment'
);
} else if (commentNeedsUpdating) {
await editComment(number, commentId, body);
logger.debug(
{ repository: config.repository, issueNo: number },
'Updated comment'
);
} else {
logger.debug('Comment is already update-to-date');
}
return true;
}
type GitlabComment = {
body: string;
id: number;
};
export async function ensureCommentRemoval({
number: issueNo,
topic,
content,
}: EnsureCommentRemovalConfig): Promise<void> {
logger.debug(
`Ensuring comment "${topic || content}" in #${issueNo} is removed`
);
const comments = await getComments(issueNo);
let commentId: number | null = null;
const byTopic = (comment: GitlabComment): boolean =>
comment.body.startsWith(`### ${topic}\n\n`);
const byContent = (comment: GitlabComment): boolean =>
comment.body.trim() === content;
if (topic) {
commentId = comments.find(byTopic)?.id;
} else if (content) {
commentId = comments.find(byContent)?.id;
}
if (commentId) {
await deleteComment(issueNo, commentId);
}
}
async function fetchPrList(): Promise<Pr[]> {
const query = new URLSearchParams({
per_page: '100',
author_id: `${authorId}`,
}).toString();
const urlString = `projects/${config.repository}/merge_requests?${query}`;
try {
const res = await gitlabApi.getJson<
{
iid: number;
source_branch: string;
title: string;
state: string;
created_at: string;
}[]
>(urlString, { paginate: true });
return res.body.map((pr) => ({
number: pr.iid,
branchName: pr.source_branch,
title: pr.title,
state: pr.state === 'opened' ? PR_STATE_OPEN : pr.state,
createdAt: pr.created_at,
}));
} catch (err) /* istanbul ignore next */ {
logger.debug({ err }, 'Error fetching PR list');
if (err.statusCode === 403) {
throw new Error(PLATFORM_AUTHENTICATION_ERROR);
}