forked from piceaTech/node-gitlab-2-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithubHelper.ts
More file actions
1468 lines (1267 loc) · 45.8 KB
/
githubHelper.ts
File metadata and controls
1468 lines (1267 loc) · 45.8 KB
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 settings from '../settings';
import { GithubSettings } from './settings';
import * as utils from './utils';
import { Octokit as GitHubApi, RestEndpointMethodTypes } from '@octokit/rest';
import { Endpoints } from '@octokit/types';
import {
GitlabHelper,
GitLabIssue,
GitLabMergeRequest,
GitLabNote,
GitLabUser,
} from './gitlabHelper';
type IssuesListForRepoResponseData =
Endpoints['GET /repos/{owner}/{repo}/issues']['response']['data'];
type PullsListResponseData =
Endpoints['GET /repos/{owner}/{repo}/pulls']['response']['data'];
type GitHubIssue = IssuesListForRepoResponseData[0];
type GitHubPullRequest = PullsListResponseData[0];
const gitHubLocation = 'https://github.com';
// Source for regex: https://stackoverflow.com/a/30281147
const usernameRegex = new RegExp('\\B@([a-z0-9](?:-(?=[a-z0-9])|[a-z0-9]){0,38}(?<=[a-z0-9]))', 'gi')
interface CommentImport {
created_at?: string;
body: string;
}
interface IssueImport {
title: string;
body: string;
closed: boolean;
assignee?: string;
created_at?: string;
updated_at?: string;
milestone?: number;
labels?: string[];
}
export interface MilestoneImport {
id: number; // GitHub internal identifier
iid: number; // GitLab external number
title: string;
description: string;
state: string;
due_date?: string;
}
export interface SimpleLabel {
name: string;
color: string;
description: string;
}
export interface SimpleMilestone {
number: number;
title: string;
}
export class GithubHelper {
githubApi: GitHubApi;
githubUrl: string;
githubOwner: string;
githubOwnerIsOrg: boolean;
githubToken: string;
githubTokenOwner: string;
githubRepo: string;
githubTimeout?: number;
gitlabHelper: GitlabHelper;
repoId?: number;
delayInMs: number;
useIssuesForAllMergeRequests: boolean;
milestoneMap?: Map<number, SimpleMilestone>;
users: Set<string>;
constructor(
githubApi: GitHubApi,
githubSettings: GithubSettings,
gitlabHelper: GitlabHelper,
useIssuesForAllMergeRequests: boolean
) {
this.githubApi = githubApi;
this.githubUrl = githubSettings.baseUrl
? githubSettings.baseUrl
: gitHubLocation;
this.githubOwner = githubSettings.owner;
this.githubOwnerIsOrg = githubSettings.ownerIsOrg ?? false;
this.githubToken = githubSettings.token;
this.githubTokenOwner = githubSettings.token_owner;
this.githubRepo = githubSettings.repo;
this.githubTimeout = githubSettings.timeout;
this.gitlabHelper = gitlabHelper;
this.delayInMs = 2000;
this.useIssuesForAllMergeRequests = useIssuesForAllMergeRequests;
this.users = new Set<string>();
}
/*
******************************************************************************
******************************** GET METHODS *********************************
******************************************************************************
*/
/**
* Store the new repo id
*/
async registerRepoId() {
try {
await utils.sleep(this.delayInMs);
let result = await this.githubApi.repos.get({
owner: this.githubOwner,
repo: this.githubRepo,
});
this.repoId = result.data.id;
} catch (err) {
console.error('Could not access GitHub repo');
console.error(err);
process.exit(1);
}
}
// ----------------------------------------------------------------------------
/**
* Get a list of all GitHub milestones currently in new repo
*/
async getAllGithubMilestones(): Promise<SimpleMilestone[]> {
try {
await utils.sleep(this.delayInMs);
// get an array of GitHub milestones for the new repo
let result = await this.githubApi.issues.listMilestones({
owner: this.githubOwner,
repo: this.githubRepo,
state: 'all',
});
return result.data.map(x => ({ number: x.number, title: x.title }));
} catch (err) {
console.error('Could not access all GitHub milestones');
console.error(err);
process.exit(1);
}
}
// ----------------------------------------------------------------------------
/**
* Get a list of all the current GitHub issues.
* This uses a while loop to make sure that each page of issues is received.
*/
async getAllGithubIssues() {
let allIssues: IssuesListForRepoResponseData = [];
let page = 1;
const perPage = 100;
while (true) {
await utils.sleep(this.delayInMs);
// get a paginated list of issues
const issues = await this.githubApi.issues.listForRepo({
owner: this.githubOwner,
repo: this.githubRepo,
state: 'all',
labels: 'gitlab merge request',
per_page: perPage,
page: page,
});
// if this page has zero issues then we are done!
if (issues.data.length === 0) break;
// join this list of issues with the master list
allIssues = allIssues.concat(issues.data);
// if there are strictly less issues on this page than the maximum number per page
// then we can be sure that this is all the issues. No use querying again.
if (issues.data.length < perPage) break;
// query for the next page of issues next iteration
page++;
}
return allIssues;
}
// ----------------------------------------------------------------------------
/**
* Get a list of all GitHub label names currently in new repo
*/
async getAllGithubLabelNames() {
try {
await utils.sleep(this.delayInMs);
// get an array of GitHub labels for the new repo
let result = await this.githubApi.issues.listLabelsForRepo({
owner: this.githubOwner,
repo: this.githubRepo,
});
// extract the label name and put into a new array
let labels = result.data.map(x => x.name);
return labels;
} catch (err) {
console.error('Could not access all GitHub label names');
console.error(err);
process.exit(1);
}
}
// ----------------------------------------------------------------------------
/**
* Gets a release by tag name
* @param tag {string} - the tag name to search a release for
* @returns
*/
async getReleaseByTag(tag: string) {
try {
await utils.sleep(this.delayInMs);
// get an existing release by tag name in github
let result = await this.githubApi.repos.getReleaseByTag({
owner: this.githubOwner,
repo: this.githubRepo,
tag: tag,
});
return result;
} catch (err) {
console.error('No existing release for this tag on github');
return null;
}
}
// ----------------------------------------------------------------------------
/**
* Creates a new release on github
* @param tag_name {string} - the tag name
* @param name {string} - title of the release
* @param body {string} - description for the release
*/
async createRelease(tag_name: string, name: string, body: string) {
try {
await utils.sleep(this.delayInMs);
// get an array of GitHub labels for the new repo
let result = await this.githubApi.repos.createRelease({
owner: this.githubOwner,
repo: this.githubRepo,
tag_name,
name,
body,
});
return result;
} catch (err) {
console.error('Could not create release on github');
console.error(err);
return null;
}
}
// ----------------------------------------------------------------------------
/**
* Get a list of all the current GitHub pull requests.
* This uses a while loop to make sure that each page of issues is received.
*/
async getAllGithubPullRequests() {
let allPullRequests: PullsListResponseData = [];
let page = 1;
const perPage = 100;
while (true) {
await utils.sleep(this.delayInMs);
// get a paginated list of pull requests
const pullRequests = await this.githubApi.pulls.list({
owner: this.githubOwner,
repo: this.githubRepo,
state: 'all',
per_page: perPage,
page: page,
});
// if this page has zero PRs then we are done!
if (pullRequests.data.length === 0) break;
// join this list of PRs with the master list
allPullRequests = allPullRequests.concat(pullRequests.data);
// if there are strictly less PRs on this page than the maximum number per page
// then we can be sure that this is all the PRs. No use querying again.
if (pullRequests.data.length < perPage) break;
// query for the next page of PRs next iteration
page++;
}
return allPullRequests;
}
// ----------------------------------------------------------------------------
/*
******************************************************************************
******************************** POST METHODS ********************************
******************************************************************************
*/
userIsCreator(author: GitLabUser) {
this.users.add(author.username as string);
return (
author &&
((settings.usermap &&
settings.usermap[author.username as string] ===
settings.github.token_owner) ||
author.username === settings.github.token_owner)
);
}
/**
* Update the description of the repository on GitHub.
* Replaces newlines and tabs with spaces. No attempt is made to remove e.g. Markdown
* links or other special formatting.
*/
async updateRepositoryDescription(description: string) {
let props: RestEndpointMethodTypes['repos']['update']['parameters'] = {
owner: this.githubOwner,
repo: this.githubRepo,
description: description?.replace(/\s+/g, ' ') || '',
};
return this.githubApi.repos.update(props);
}
/**
* TODO description
* @param milestones All GitHub milestones
* @param issue The GitLab issue object
*/
async createIssue(issue: GitLabIssue) {
let bodyConverted = await this.convertIssuesAndComments(
issue.description ?? '',
issue,
!this.userIsCreator(issue.author) || !issue.description
);
let props: RestEndpointMethodTypes['issues']['create']['parameters'] = {
owner: this.githubOwner,
repo: this.githubRepo,
title: issue.title ? issue.title.trim() : '',
body: bodyConverted,
};
props.assignees = this.convertAssignees(issue);
props.milestone = this.convertMilestone(issue);
props.labels = this.convertLabels(issue);
await utils.sleep(this.delayInMs);
if (settings.dryRun) return Promise.resolve({ data: issue });
return this.githubApi.issues.create(props);
}
/**
* Converts GitLab assignees to GitHub usernames, using settings.usermap
*/
convertAssignees(item: GitLabIssue | GitLabMergeRequest): string[] {
if (!item.assignees) return [];
let assignees: string[] = [];
for (let assignee of item.assignees) {
let username: string = assignee.username as string;
this.users.add(username);
if (username === settings.github.username) {
assignees.push(settings.github.username);
} else if (settings.usermap && settings.usermap[username]) {
assignees.push(settings.usermap[username]);
}
}
return assignees;
}
/**
* Returns the GitHub milestone id for a milestone GitLab property of an issue or MR
*
* Note that this requires milestoneMap to be built, either during migration
* or read from GitHub using registerMilestoneMap()
*/
convertMilestone(item: GitLabIssue | GitLabMergeRequest): number | undefined {
if (!this.milestoneMap) throw Error('this.milestoneMap not initialised');
if (!item.milestone) return undefined;
for (let m of this.milestoneMap.values())
if (m.title == item.milestone.title) return m.number;
return undefined;
}
/**
* Converts GitLab labels to GitHub labels.
*
* This also adds "has attachment" if the issue links to data.
*/
convertLabels(item: GitLabIssue | GitLabMergeRequest): string[] {
let labels: string[] = [];
if (item.labels) {
labels = item.labels.filter(l => {
if (item.state !== 'closed') return true;
let lower = l.toLowerCase();
// ignore any labels that should have been removed when the issue was closed
return lower !== 'doing' && lower !== 'to do';
});
if (settings.conversion.useLowerCaseLabels) {
labels = labels.map((el: string) => el.toLowerCase());
}
}
// If the item's description contains a url that contains "/uploads/",
// it is likely to have an attachment
if (
item.description &&
item.description.indexOf('/uploads/') > -1 &&
!settings.s3
) {
labels.push('has attachment');
}
labels.push('gitlab merge request');
if (item.state === 'merged') {
labels.push('merged');
}
return labels;
}
/**
* Uses the preview issue import API to set creation date on issues and comments.
* Also it does not notify assignees.
*
* See https://gist.github.com/jonmagic/5282384165e0f86ef105
* @param milestones All GitHub milestones
* @param issue The GitLab issue object
*/
async importIssueAndComments(issue: GitLabIssue) {
let bodyConverted = issue.isPlaceholder
? issue.description ?? ''
: await this.convertIssuesAndComments(
issue.description ?? '',
issue,
!this.userIsCreator(issue.author) || !issue.description
);
let props: IssueImport = {
title: issue.title ? issue.title.trim() : '',
body: bodyConverted,
created_at: issue.created_at,
updated_at: issue.updated_at,
closed: issue.state === 'closed',
};
let assignees = this.convertAssignees(issue);
props.assignee = assignees.length == 1 ? assignees[0] : undefined;
props.milestone = this.convertMilestone(issue);
props.labels = this.convertLabels(issue);
if (settings.dryRun) return Promise.resolve({ data: issue });
//
// Issue comments
//
console.log('\tMigrating issue comments...');
let comments: CommentImport[] = [];
if (issue.isPlaceholder) {
console.log(
'\t...this is a placeholder issue, no comments are migrated.'
);
} else {
let notes = await this.gitlabHelper.getIssueNotes(issue.iid);
comments = await this.processNotesIntoComments(notes);
}
const issue_number = await this.requestImportIssue(props, comments);
if (assignees.length > 1 && issue_number) {
if (assignees.length > 10) {
console.error(
`Cannot add more than 10 assignees to GitHub issue #${issue_number}.`
);
} else {
console.log(
`Importing ${assignees.length} assignees for GitHub issue #${issue_number}`
);
}
this.githubApi.issues.addAssignees({
owner: this.githubOwner,
repo: this.githubRepo,
issue_number: issue_number,
assignees: assignees,
});
}
}
/**
*
* @param notes
* @returns Comments ready for requestImportIssue()
*/
async processNotesIntoComments(
notes: GitLabNote[]
): Promise<CommentImport[]> {
if (!notes || !notes.length) {
console.log(`\t...no comments available, nothing to migrate.`);
return [];
}
let comments: CommentImport[] = [];
// sort notes in ascending order of when they were created (by id)
notes = notes.sort((a, b) => a.id - b.id);
let nrOfMigratedNotes = 0;
for (let note of notes) {
if (this.checkIfNoteCanBeSkipped(note.body)) continue;
this.users.add(note.author.username);
let userIsPoster =
(settings.usermap &&
settings.usermap[note.author.username] ===
settings.github.token_owner) ||
note.author.username === settings.github.token_owner;
comments.push({
created_at: note.created_at,
body: await this.convertIssuesAndComments(
note.body,
note,
!userIsPoster || !note.body
),
});
nrOfMigratedNotes++;
}
console.log(
`\t...Done creating comments (migrated ${nrOfMigratedNotes} comments, skipped ${
notes.length - nrOfMigratedNotes
} comments)`
);
return comments;
}
/**
* Calls the preview API for issue importing
*
* @param issue Props for the issue
* @param comments Comments
* @returns GitHub issue number or null if import failed
*/
async requestImportIssue(
issue: IssueImport,
comments: CommentImport[]
): Promise<number | null> {
// see: https://github.com/orgs/community/discussions/27190
if (issue.body.length > 65536) {
throw `${issue.title} has a body longer than 65536 characters. Please shorten it.`;
}
// create the GitHub issue from the GitLab issue
let pending = await this.githubApi.request(
`POST /repos/${settings.github.owner}/${settings.github.repo}/import/issues`,
{
issue: issue,
comments: comments,
}
);
let result = null;
while (true) {
await utils.sleep(this.delayInMs);
result = await this.githubApi.request(
`GET /repos/${settings.github.owner}/${settings.github.repo}/import/issues/${pending.data.id}`
);
if (
result.data.status === 'imported' ||
result.data.status === 'failed'
) {
break;
}
}
if (result.data.status === 'failed') {
console.log('\tFAILED: ');
console.log(result);
console.log('\tERRORS:');
console.log(result.data.errors);
return null;
}
let issue_number = result.data.issue_url.split('/').splice(-1)[0];
return issue_number;
}
// ----------------------------------------------------------------------------
/**
* TODO description
*/
async createIssueComments(githubIssue: GitHubIssue, issue: GitLabIssue) {
console.log('\tMigrating issue comments...');
// retrieve any notes/comments associated with this issue
if (issue.isPlaceholder) {
console.log(
'\t...this is a placeholder issue, no comments are migrated.'
);
return;
}
let notes = await this.gitlabHelper.getIssueNotes(issue.iid);
// if there are no notes, then there is nothing to do!
if (notes.length === 0) {
console.log(`\t...no issue comments available, nothing to migrate.`);
return;
}
// sort notes in ascending order of when they were created (by id)
notes = notes.sort((a, b) => a.id - b.id);
let nrOfMigratedNotes = 0;
for (let note of notes) {
const gotMigrated = await this.processNote(note, githubIssue);
if (gotMigrated) nrOfMigratedNotes++;
}
console.log(
`\t...Done creating issue comments (migrated ${nrOfMigratedNotes} comments, skipped ${
notes.length - nrOfMigratedNotes
} comments)`
);
}
// ----------------------------------------------------------------------------
/**
* This function checks if a note needs to be processed or if it can be skipped.
* A note can be skipped if it contains predefined terms (like 'Status changed to...')
* or if it contains any value from settings.skipMatchingComments ->
* Note that this is case insensitive!
*
*/
checkIfNoteCanBeSkipped(noteBody: string) {
const stateChange =
(/Status changed to .*/i.test(noteBody) &&
!/Status changed to closed by commit.*/i.test(noteBody)) ||
/^changed milestone to .*/i.test(noteBody) ||
/^Milestone changed to .*/i.test(noteBody) ||
/^(Re)*assigned to /i.test(noteBody) ||
/^added .* labels/i.test(noteBody) ||
/^Added ~.* label/i.test(noteBody) ||
/^removed ~.* label/i.test(noteBody) ||
/^mentioned in issue #\d+.*/i.test(noteBody) ||
// /^marked this issue as related to #\d+/i.test(noteBody) ||
/^mentioned in merge request !\d+/i.test(noteBody) ||
/^changed the description.*/i.test(noteBody) ||
/^changed title from.*to.*/i.test(noteBody);
const matchingComment = settings.skipMatchingComments.reduce(
(a, b) => a || new RegExp(b, 'i').test(noteBody),
false
);
return stateChange || matchingComment;
}
// ----------------------------------------------------------------------------
/*
* Processes the current note.
* This means, it either creates a comment in the github issue, or it gets skipped.
* Return false when it got skipped, otherwise true.
*/
async processNote(
note: GitLabNote,
githubIssue: Pick<GitHubIssue | GitHubPullRequest, 'number'>
) {
if (this.checkIfNoteCanBeSkipped(note.body)) return false;
let bodyConverted = await this.convertIssuesAndComments(note.body, note);
await utils.sleep(this.delayInMs);
if (settings.dryRun) return true;
await this.githubApi.issues
.createComment({
owner: this.githubOwner,
repo: this.githubRepo,
issue_number: githubIssue.number,
body: bodyConverted,
})
.catch(x => {
console.error('could not create GitHub issue comment!');
console.error(x);
process.exit(1);
});
return true;
}
// ----------------------------------------------------------------------------
/**
* Update the issue state (i.e., closed or open).
*/
async updateIssueState(githubIssue: GitHubIssue, issue: GitLabIssue) {
// default state is open so we don't have to update if the issue is closed.
if (issue.state !== 'closed' || githubIssue.state === 'closed') return;
let props: RestEndpointMethodTypes['issues']['update']['parameters'] = {
owner: this.githubOwner,
repo: this.githubRepo,
issue_number: githubIssue.number,
state: issue.state,
};
await utils.sleep(this.delayInMs);
if (settings.dryRun) return Promise.resolve();
return await this.githubApi.issues.update(props);
}
// ----------------------------------------------------------------------------
/**
* Create a GitHub milestone from a GitLab milestone
* @param milestone GitLab milestone data
* @return Created milestone data (or void if debugging => nothing created)
*/
async createMilestone(milestone: MilestoneImport): Promise<SimpleMilestone> {
// convert from GitLab to GitHub
let bodyConverted = await this.convertIssuesAndComments(
milestone.description,
milestone,
false
);
let githubMilestone: RestEndpointMethodTypes['issues']['createMilestone']['parameters'] =
{
owner: this.githubOwner,
repo: this.githubRepo,
title: milestone.title,
description: bodyConverted,
state: milestone.state === 'active' ? 'open' : 'closed',
};
if (milestone.due_date) {
githubMilestone.due_on = milestone.due_date + 'T00:00:00Z';
}
await utils.sleep(this.delayInMs);
if (settings.dryRun) return Promise.resolve({ number: -1, title: 'DEBUG' });
const created = await this.githubApi.issues.createMilestone(
githubMilestone
);
return { number: created.data.number, title: created.data.title };
}
// ----------------------------------------------------------------------------
/**
* Create a GitHub label from a GitLab label
*/
async createLabel(label: SimpleLabel) {
// convert from GitLab to GitHub
let githubLabel = {
owner: this.githubOwner,
repo: this.githubRepo,
name: label.name,
color: label.color.substring(1), // remove leading "#" because gitlab returns it but github wants the color without it
description: label.description,
};
await utils.sleep(this.delayInMs);
if (settings.dryRun) return Promise.resolve();
// create the GitHub label
return await this.githubApi.issues.createLabel(githubLabel);
}
// ----------------------------------------------------------------------------
/**
* Create a pull request, set its data, and set its comments
* @param mergeRequest the GitLab merge request that we want to migrate
*/
async createPullRequestAndComments(
mergeRequest: GitLabMergeRequest
): Promise<void> {
let pullRequestData = await this.createPullRequest(mergeRequest);
// createPullRequest() returns an issue number if a PR could not be created and
// an issue was created instead, and settings.useIssueImportAPI is true. In that
// case comments were already added and the state is already properly set
if (typeof pullRequestData === 'number' || !pullRequestData) return;
let pullRequest = pullRequestData.data;
// data is set to null if one of the branches does not exist and the pull request cannot be created
if (pullRequest) {
// Add milestones, labels, and other attributes from the Issues API
await this.updatePullRequestData(pullRequest, mergeRequest);
// add any comments/nodes associated with this pull request
await this.createPullRequestComments(pullRequest, mergeRequest);
// Make sure to close the GitHub pull request if it is closed or merged in GitLab
await this.updatePullRequestState(pullRequest, mergeRequest);
}
}
// ----------------------------------------------------------------------------
/**
* Create a pull request. A pull request can only be created if both the target and source branches exist on the GitHub
* repository. In many cases, the source branch is deleted when the merge occurs, and the merge request may not be able
* to be migrated. In this case, an issue is created instead with a 'gitlab merge request' label.
* @param mergeRequest the GitLab merge request object that we want to duplicate
* @returns {Promise<Promise<{data: null}>|Promise<Github.Response<Github.PullsCreateResponse>>|Promise<{data: *}>>}
*/
async createPullRequest(mergeRequest: GitLabMergeRequest) {
let canCreate = !this.useIssuesForAllMergeRequests;
if (canCreate) {
// Check to see if the target branch exists in GitHub - if it does not exist, we cannot create a pull request
try {
await this.githubApi.repos.getBranch({
owner: this.githubOwner,
repo: this.githubRepo,
branch: mergeRequest.target_branch,
});
} catch (err) {
let gitlabBranches = await this.gitlabHelper.getAllBranches();
if (gitlabBranches.find(m => m.name === mergeRequest.target_branch)) {
// Need to move that branch over to GitHub!
console.error(
`The '${mergeRequest.target_branch}' branch exists on GitLab but has not been migrated to GitHub. Please migrate the branch before migrating pull request #${mergeRequest.iid}.`
);
return Promise.resolve({ data: null });
} else {
console.error(
`Merge request ${mergeRequest.iid} (target branch '${mergeRequest.target_branch}' does not exist => cannot migrate pull request, creating an issue instead.`
);
canCreate = false;
}
}
}
if (canCreate) {
// Check to see if the source branch exists in GitHub - if it does not exist, we cannot create a pull request
try {
await this.githubApi.repos.getBranch({
owner: this.githubOwner,
repo: this.githubRepo,
branch: mergeRequest.source_branch,
});
} catch (err) {
let gitlabBranches = await this.gitlabHelper.getAllBranches();
if (gitlabBranches.find(m => m.name === mergeRequest.source_branch)) {
// Need to move that branch over to GitHub!
console.error(
`The '${mergeRequest.source_branch}' branch exists on GitLab but has not been migrated to GitHub. Please migrate the branch before migrating pull request #${mergeRequest.iid}.`
);
return Promise.resolve({ data: null });
} else {
console.error(
`Pull request #${mergeRequest.iid} (source branch '${mergeRequest.source_branch}' does not exist => cannot migrate pull request, creating an issue instead.`
);
canCreate = false;
}
}
}
if (settings.dryRun) return Promise.resolve({ data: mergeRequest });
if (canCreate) {
let bodyConverted = await this.convertIssuesAndComments(
mergeRequest.description,
mergeRequest
);
// GitHub API Documentation to create a pull request: https://developer.github.com/v3/pulls/#create-a-pull-request
let props = {
owner: this.githubOwner,
repo: this.githubRepo,
title: mergeRequest.title.trim(),
body: bodyConverted,
head: mergeRequest.source_branch,
base: mergeRequest.target_branch,
};
await utils.sleep(this.delayInMs);
try {
// try to create the GitHub pull request from the GitLab issue
const response = await this.githubApi.pulls.create(props);
return Promise.resolve(response);
} catch (err) {
if (err.status === 422) {
console.error(
`Pull request #${mergeRequest.iid} - attempt to create has failed, assume '${mergeRequest.source_branch}' has already been merged => cannot migrate pull request, creating an issue instead.`
);
// fall through to next section
} else {
throw err;
}
}
}
// Failing all else, create an issue with a descriptive title
let mergeStr =
'_Merges ' +
mergeRequest.source_branch +
' -> ' +
mergeRequest.target_branch +
'_\n\n';
let bodyConverted = await this.convertIssuesAndComments(
mergeStr + mergeRequest.description,
mergeRequest,
!this.userIsCreator(mergeRequest.author) || !settings.useIssueImportAPI
);
if (settings.useIssueImportAPI) {
let assignees = this.convertAssignees(mergeRequest);
let props: IssueImport = {
title: mergeRequest.title.trim() + ' - [' + mergeRequest.state + ']',
body: bodyConverted,
assignee: assignees.length > 0 ? assignees[0] : undefined,
created_at: mergeRequest.created_at,
updated_at: mergeRequest.updated_at,
closed:
mergeRequest.state === 'merged' || mergeRequest.state === 'closed',
labels: ['gitlab merge request'],
};
console.log('\tMigrating pull request comments...');
let comments: CommentImport[] = [];
if (!mergeRequest.iid) {
console.log(
'\t...this is a placeholder for a deleted GitLab merge request, no comments are created.'
);
} else {
let notes = await this.gitlabHelper.getAllMergeRequestNotes(
mergeRequest.iid
);
comments = await this.processNotesIntoComments(notes);
}
return this.requestImportIssue(props, comments);
} else {
let props = {
owner: this.githubOwner,
repo: this.githubRepo,
assignees: this.convertAssignees(mergeRequest),
title: mergeRequest.title.trim() + ' - [' + mergeRequest.state + ']',
body: bodyConverted,
};
// Add a label to indicate the issue is a merge request
if (!mergeRequest.labels) mergeRequest.labels = [];
mergeRequest.labels.push('gitlab merge request');
return this.githubApi.issues.create(props);
}
}
// ----------------------------------------------------------------------------
/**
* Create comments for the pull request
* @param pullRequest the GitHub pull request object
* @param mergeRequest the GitLab merge request object
*/
async createPullRequestComments(
pullRequest: Pick<GitHubPullRequest, 'number'>,
mergeRequest: GitLabMergeRequest
): Promise<void> {
console.log('\tMigrating pull request comments...');
if (!mergeRequest.iid) {