-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
1138 lines (959 loc) · 38 KB
/
main.go
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
package main
import (
"bytes"
"context"
"encoding/csv"
"errors"
"flag"
"fmt"
"math"
"net/http"
"net/url"
"os"
"os/signal"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory"
"github.com/gofri/go-github-pagination/githubpagination"
"github.com/google/go-github/v67/github"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-retryablehttp"
"github.com/xanzy/go-gitlab"
)
const (
dateFormat = "Mon, 2 Jan 2006"
defaultGithubDomain = "github.com"
defaultGitlabDomain = "gitlab.com"
)
var loop, report bool
var deleteExistingRepos, enablePullRequests, renameMasterToMain bool
var githubDomain, githubRepo, githubToken, githubUser, gitlabDomain, gitlabProject, gitlabToken, projectsCsvPath string
var (
cache *objectCache
errCount int
logger hclog.Logger
gh *github.Client
gl *gitlab.Client
maxConcurrency int
)
type Project = []string
type Report struct {
GroupName string
ProjectName string
MergeRequestsCount int
}
func sendErr(err error) {
errCount++
logger.Error(err.Error())
}
func main() {
var err error
// Bypass pre-emptive rate limit checks in the GitHub client, as we will handle these via go-retryablehttp
valueCtx := context.WithValue(context.Background(), github.BypassRateLimitCheck, true)
// Assign a Done channel so we can abort on Ctrl-c
ctx, cancel := context.WithCancel(valueCtx)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
defer func() {
signal.Stop(c)
cancel()
}()
go func() {
select {
case <-c:
cancel()
case <-ctx.Done():
}
}()
logger = hclog.New(&hclog.LoggerOptions{
Name: "gitlab-migrator",
Level: hclog.LevelFromString(os.Getenv("LOG_LEVEL")),
})
cache = newObjectCache()
githubToken = os.Getenv("GITHUB_TOKEN")
if githubToken == "" {
logger.Error("missing environment variable", "name", "GITHUB_TOKEN")
os.Exit(1)
}
gitlabToken = os.Getenv("GITLAB_TOKEN")
if gitlabToken == "" {
logger.Error("missing environment variable", "name", "GITLAB_TOKEN")
os.Exit(1)
}
flag.BoolVar(&loop, "loop", false, "continue migrating until canceled")
flag.BoolVar(&report, "report", false, "report on primitives to be migrated instead of beginning migration")
flag.BoolVar(&deleteExistingRepos, "delete-existing-repos", false, "whether existing repositories should be deleted before migrating")
flag.BoolVar(&enablePullRequests, "migrate-pull-requests", false, "whether pull requests should be migrated")
flag.BoolVar(&renameMasterToMain, "rename-master-to-main", false, "rename master branch to main and update pull requests")
flag.StringVar(&githubDomain, "github-domain", defaultGithubDomain, "specifies the GitHub domain to use")
flag.StringVar(&githubRepo, "github-repo", "", "the GitHub repository to migrate to")
flag.StringVar(&githubUser, "github-user", "", "specifies the GitHub user to use, who will author any migrated PRs (required)")
flag.StringVar(&gitlabDomain, "gitlab-domain", defaultGitlabDomain, "specifies the GitLab domain to use")
flag.StringVar(&gitlabProject, "gitlab-project", "", "the GitLab project to migrate")
flag.StringVar(&projectsCsvPath, "projects-csv", "", "specifies the path to a CSV file describing projects to migrate (incompatible with -gitlab-project and -github-repo)")
flag.IntVar(&maxConcurrency, "max-concurrency", 4, "how many projects to migrate in parallel")
flag.Parse()
if githubUser == "" {
logger.Error("must specify GitHub user")
os.Exit(1)
}
repoSpecifiedInline := githubRepo != "" && gitlabProject != ""
if repoSpecifiedInline && projectsCsvPath != "" {
logger.Error("cannot specify -projects-csv and either -github-repo or -gitlab-project at the same time")
os.Exit(1)
}
if !repoSpecifiedInline && projectsCsvPath == "" {
logger.Error("must specify either -projects-csv or both of -github-repo and -gitlab-project")
os.Exit(1)
}
retryClient := &retryablehttp.Client{
HTTPClient: cleanhttp.DefaultPooledClient(),
Logger: nil,
RetryMax: 16,
RetryWaitMin: 30 * time.Second,
RetryWaitMax: 300 * time.Second,
}
retryClient.Backoff = func(min, max time.Duration, attemptNum int, resp *http.Response) (sleep time.Duration) {
requestMethod := "unknown"
requestUrl := "unknown"
if req := resp.Request; req != nil {
requestMethod = req.Method
if req.URL != nil {
requestUrl = req.URL.String()
}
}
defer func() {
logger.Trace("waiting before retrying failed API request", "method", requestMethod, "url", requestUrl, "status", resp.StatusCode, "sleep", sleep, "attempt", attemptNum, "max_attempts", retryClient.RetryMax)
}()
if resp != nil {
// Check the Retry-After header
if s, ok := resp.Header["Retry-After"]; ok {
if retryAfter, err := strconv.ParseInt(s[0], 10, 64); err == nil {
sleep = time.Second * time.Duration(retryAfter)
return
}
}
// Reference:
// - https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28
// - https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api?apiVersion=2022-11-28
if v, ok := resp.Header["X-Ratelimit-Remaining"]; ok {
if remaining, err := strconv.ParseInt(v[0], 10, 64); err == nil && remaining == 0 {
// If x-ratelimit-reset is present, this indicates the UTC timestamp when we can retry
if w, ok := resp.Header["X-Ratelimit-Reset"]; ok {
if recoveryEpoch, err := strconv.ParseInt(w[0], 10, 64); err == nil {
// Add 30 seconds to recovery timestamp for clock differences
sleep = roundDuration(time.Until(time.Unix(recoveryEpoch+30, 0)), time.Second)
return
}
}
// Otherwise, wait for 60 seconds
sleep = 60 * time.Second
return
}
}
}
// Exponential backoff
mult := math.Pow(2, float64(attemptNum)) * float64(min)
wait := time.Duration(mult)
if float64(wait) != mult || wait > max {
wait = max
}
sleep = wait
return
}
retryClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
if err != nil {
return false, err
}
// Potential connection reset
if resp == nil {
return true, nil
}
retryableStatuses := []int{
http.StatusTooManyRequests, // rate-limiting
http.StatusForbidden, // rate-limiting
http.StatusRequestTimeout,
http.StatusFailedDependency,
http.StatusInternalServerError,
http.StatusBadGateway,
http.StatusServiceUnavailable,
http.StatusGatewayTimeout,
}
requestMethod := "unknown"
requestUrl := "unknown"
if req := resp.Request; req != nil {
requestMethod = req.Method
if req.URL != nil {
requestUrl = req.URL.String()
}
}
for _, status := range retryableStatuses {
if resp.StatusCode == status {
logger.Trace("retrying failed API request", "method", requestMethod, "url", requestUrl, "status", resp.StatusCode)
return true, nil
}
}
return false, nil
}
client := githubpagination.NewClient(&retryablehttp.RoundTripper{Client: retryClient}, githubpagination.WithPerPage(100))
if githubDomain == defaultGithubDomain {
gh = github.NewClient(client).WithAuthToken(githubToken)
} else {
githubUrl := fmt.Sprintf("https://%s", githubDomain)
if gh, err = github.NewClient(client).WithAuthToken(githubToken).WithEnterpriseURLs(githubUrl, githubUrl); err != nil {
sendErr(err)
os.Exit(1)
}
}
gitlabOpts := make([]gitlab.ClientOptionFunc, 0)
if gitlabDomain != defaultGitlabDomain {
gitlabUrl := fmt.Sprintf("https://%s", gitlabDomain)
gitlabOpts = append(gitlabOpts, gitlab.WithBaseURL(gitlabUrl))
}
if gl, err = gitlab.NewClient(gitlabToken, gitlabOpts...); err != nil {
sendErr(err)
os.Exit(1)
}
projects := make([]Project, 0)
if projectsCsvPath != "" {
data, err := os.ReadFile(projectsCsvPath)
if err != nil {
sendErr(err)
os.Exit(1)
}
// Trim a UTF-8 BOM, if present
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
if projects, err = csv.NewReader(bytes.NewBuffer(data)).ReadAll(); err != nil {
sendErr(err)
os.Exit(1)
}
} else {
projects = []Project{{gitlabProject, githubRepo}}
}
if report {
printReport(ctx, projects)
} else {
if err = performMigration(ctx, projects); err != nil {
sendErr(err)
os.Exit(1)
} else if errCount > 0 {
logger.Warn(fmt.Sprintf("encountered %d errors during migration, review log output for details", errCount))
}
}
}
func printReport(ctx context.Context, projects []Project) {
logger.Debug("building report")
results := make([]Report, 0)
for _, proj := range projects {
if err := ctx.Err(); err != nil {
return
}
result, err := reportProject(ctx, proj)
if err != nil {
errCount++
sendErr(err)
}
if result != nil {
results = append(results, *result)
}
}
fmt.Println()
totalMergeRequests := 0
for _, result := range results {
totalMergeRequests += result.MergeRequestsCount
fmt.Printf("%#v\n", result)
}
fmt.Println()
fmt.Printf("Total merge requests: %d\n", totalMergeRequests)
fmt.Println()
}
func reportProject(ctx context.Context, proj []string) (*Report, error) {
gitlabPath := strings.Split(proj[0], "/")
//githubPath := strings.Split(proj[1], "/")
logger.Debug("searching for GitLab project", "name", gitlabPath[1], "group", gitlabPath[0])
searchTerm := gitlabPath[1]
projectResult, _, err := gl.Projects.ListProjects(&gitlab.ListProjectsOptions{Search: &searchTerm})
if err != nil {
return nil, fmt.Errorf("listing projects: %v", err)
}
var project *gitlab.Project
for _, item := range projectResult {
if item == nil {
continue
}
if item.PathWithNamespace == proj[0] {
logger.Debug("found GitLab project", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", item.ID)
project = item
}
}
if project == nil {
return nil, fmt.Errorf("no matching GitLab project found: %s", proj[0])
}
var mergeRequests []*gitlab.MergeRequest
opts := &gitlab.ListProjectMergeRequestsOptions{
OrderBy: pointer("created_at"),
Sort: pointer("asc"),
}
logger.Debug("retrieving GitLab merge requests", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID)
for {
result, resp, err := gl.MergeRequests.ListProjectMergeRequests(project.ID, opts)
if err != nil {
return nil, fmt.Errorf("retrieving gitlab merge requests: %v", err)
}
mergeRequests = append(mergeRequests, result...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
return &Report{
GroupName: gitlabPath[0],
ProjectName: gitlabPath[1],
MergeRequestsCount: len(mergeRequests),
}, nil
}
func performMigration(ctx context.Context, projects []Project) error {
concurrency := maxConcurrency
if len(projects) < maxConcurrency {
concurrency = len(projects)
}
logger.Info(fmt.Sprintf("processing %d project(s) with %d workers", len(projects), concurrency))
var wg sync.WaitGroup
queue := make(chan Project, concurrency*2)
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for proj := range queue {
if err := ctx.Err(); err != nil {
break
}
if err := migrateProject(ctx, proj); err != nil {
errCount++
sendErr(err)
}
}
}()
}
queueProjects := func() {
for _, proj := range projects {
if err := ctx.Err(); err != nil {
break
}
queue <- proj
}
}
if loop {
logger.Info(fmt.Sprintf("looping migration until canceled"))
for {
if err := ctx.Err(); err != nil {
break
}
queueProjects()
}
} else {
queueProjects()
close(queue)
}
wg.Wait()
return nil
}
func migrateProject(ctx context.Context, proj []string) error {
gitlabPath := strings.Split(proj[0], "/")
githubPath := strings.Split(proj[1], "/")
logger.Info("searching for GitLab project", "name", gitlabPath[1], "group", gitlabPath[0])
searchTerm := gitlabPath[1]
projectResult, _, err := gl.Projects.ListProjects(&gitlab.ListProjectsOptions{Search: &searchTerm})
if err != nil {
return fmt.Errorf("listing projects: %v", err)
}
var project *gitlab.Project
for _, item := range projectResult {
if item == nil {
continue
}
if item.PathWithNamespace == proj[0] {
logger.Debug("found GitLab project", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", item.ID)
project = item
}
}
if project == nil {
return fmt.Errorf("no matching GitLab project found: %s", proj[0])
}
cloneUrl, err := url.Parse(project.HTTPURLToRepo)
if err != nil {
return fmt.Errorf("parsing clone URL: %v", err)
}
logger.Info("mirroring repository from GitLab to GitHub", "name", gitlabPath[1], "group", gitlabPath[0], "github_org", githubPath[0], "github_repo", githubPath[1])
user, err := getGithubUser(ctx, githubPath[0])
if err != nil {
return fmt.Errorf("retrieving github user: %v", err)
}
var org string
if strings.EqualFold(*user.Type, "organization") {
org = githubPath[0]
} else if !strings.EqualFold(*user.Type, "user") || !strings.EqualFold(*user.Login, githubPath[0]) {
return fmt.Errorf("configured owner is neither an organization nor the current user: %s", githubPath[0])
}
logger.Debug("checking for existing repository on GitHub", "owner", githubPath[0], "repo", githubPath[1])
_, _, err = gh.Repositories.Get(ctx, githubPath[0], githubPath[1])
var githubError *github.ErrorResponse
if err != nil && (!errors.As(err, &githubError) || githubError == nil || githubError.Response == nil || githubError.Response.StatusCode != http.StatusNotFound) {
return fmt.Errorf("retrieving github repo: %v", err)
}
var createRepo, repoDeleted bool
if err != nil {
createRepo = true
} else if deleteExistingRepos {
logger.Warn("existing repository was found on GitHub, proceeding to delete", "owner", githubPath[0], "repo", githubPath[1])
if _, err = gh.Repositories.Delete(ctx, githubPath[0], githubPath[1]); err != nil {
return fmt.Errorf("deleting existing github repo: %v", err)
}
createRepo = true
repoDeleted = true
}
defaultBranch := "main"
if !renameMasterToMain && project.DefaultBranch != "" {
defaultBranch = project.DefaultBranch
}
homepage := fmt.Sprintf("https://%s/%s/%s", gitlabDomain, gitlabPath[0], gitlabPath[1])
if createRepo {
if repoDeleted {
logger.Warn("recreating GitHub repository", "owner", githubPath[0], "repo", githubPath[1])
} else {
logger.Debug("repository not found on GitHub, proceeding to create", "owner", githubPath[0], "repo", githubPath[1])
}
newRepo := github.Repository{
Name: pointer(githubPath[1]),
Description: &project.Description,
Homepage: &homepage,
DefaultBranch: &defaultBranch,
Private: pointer(true),
HasIssues: pointer(true),
HasProjects: pointer(true),
HasWiki: pointer(true),
}
if _, _, err = gh.Repositories.Create(ctx, org, &newRepo); err != nil {
return fmt.Errorf("creating github repo: %v", err)
}
}
logger.Debug("updating repository settings", "owner", githubPath[0], "repo", githubPath[1])
updateRepo := github.Repository{
Name: pointer(githubPath[1]),
Description: &project.Description,
Homepage: &homepage,
AllowAutoMerge: pointer(true),
AllowMergeCommit: pointer(true),
AllowRebaseMerge: pointer(true),
AllowSquashMerge: pointer(true),
AllowUpdateBranch: pointer(true),
}
if _, _, err = gh.Repositories.Edit(ctx, githubPath[0], githubPath[1], &updateRepo); err != nil {
return fmt.Errorf("updating github repo: %v", err)
}
cloneUrl.User = url.UserPassword("oauth2", gitlabToken)
cloneUrlWithCredentials := cloneUrl.String()
// In-memory filesystem for worktree operations
fs := memfs.New()
logger.Debug("cloning repository", "name", gitlabPath[1], "group", gitlabPath[0], "url", project.HTTPURLToRepo)
repo, err := git.CloneContext(ctx, memory.NewStorage(), fs, &git.CloneOptions{
URL: cloneUrlWithCredentials,
Auth: nil,
RemoteName: "gitlab",
Mirror: true,
})
if err != nil {
return fmt.Errorf("cloning gitlab repo: %v", err)
}
if renameMasterToMain {
if masterBranch, err := repo.Reference(plumbing.NewBranchReferenceName("master"), false); err == nil {
logger.Info("renaming master branch to main prior to push", "name", gitlabPath[1], "group", gitlabPath[0], "sha", masterBranch.Hash())
logger.Debug("creating main branch", "name", gitlabPath[1], "group", gitlabPath[0], "sha", masterBranch.Hash())
mainBranch := plumbing.NewHashReference(plumbing.NewBranchReferenceName("main"), masterBranch.Hash())
if err = repo.Storer.SetReference(mainBranch); err != nil {
return fmt.Errorf("creating main branch: %v", err)
}
logger.Debug("deleting master branch", "name", gitlabPath[1], "group", gitlabPath[0], "sha", masterBranch.Hash())
if err = repo.Storer.RemoveReference(masterBranch.Name()); err != nil {
return fmt.Errorf("deleting master branch: %v", err)
}
}
}
githubUrl := fmt.Sprintf("https://%s/%s/%s", githubDomain, githubPath[0], githubPath[1])
githubUrlWithCredentials := fmt.Sprintf("https://%s:%s@%s/%s/%s", githubUser, githubToken, githubDomain, githubPath[0], githubPath[1])
logger.Debug("adding remote for GitHub repository", "name", gitlabPath[1], "group", gitlabPath[0], "url", githubUrl)
if _, err = repo.CreateRemote(&config.RemoteConfig{
Name: "github",
URLs: []string{githubUrlWithCredentials},
Mirror: true,
}); err != nil {
return fmt.Errorf("adding github remote: %v", err)
}
logger.Debug("force-pushing to GitHub repository", "name", gitlabPath[1], "group", gitlabPath[0], "url", githubUrl)
if err = repo.PushContext(ctx, &git.PushOptions{
RemoteName: "github",
Force: true,
//Prune: true, // causes error, attempts to delete main branch
}); err != nil {
upToDateError := errors.New("already up-to-date")
if errors.As(err, &upToDateError) {
logger.Debug("repository already up-to-date on GitHub", "name", gitlabPath[1], "group", gitlabPath[0], "url", githubUrl)
} else {
return fmt.Errorf("pushing to github repo: %v", err)
}
}
logger.Debug("setting default repository branch", "owner", githubPath[0], "repo", githubPath[1], "branch_name", defaultBranch)
updateRepo = github.Repository{
DefaultBranch: &defaultBranch,
}
if _, _, err = gh.Repositories.Edit(ctx, githubPath[0], githubPath[1], &updateRepo); err != nil {
return fmt.Errorf("setting default branch: %v", err)
}
if enablePullRequests {
migratePullRequests(ctx, githubPath, gitlabPath, project, repo)
}
return nil
}
func migratePullRequests(ctx context.Context, githubPath, gitlabPath []string, project *gitlab.Project, repo *git.Repository) {
var mergeRequests []*gitlab.MergeRequest
opts := &gitlab.ListProjectMergeRequestsOptions{
OrderBy: pointer("created_at"),
Sort: pointer("asc"),
}
logger.Debug("retrieving GitLab merge requests", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID)
for {
result, resp, err := gl.MergeRequests.ListProjectMergeRequests(project.ID, opts)
if err != nil {
sendErr(fmt.Errorf("retrieving gitlab merge requests: %v", err))
return
}
mergeRequests = append(mergeRequests, result...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
var successCount, failureCount int
totalCount := len(mergeRequests)
logger.Info("migrating merge requests from GitLab to GitHub", "name", gitlabPath[1], "group", gitlabPath[0], "count", totalCount)
for _, mergeRequest := range mergeRequests {
if mergeRequest == nil {
continue
}
// Check for context cancellation
if err := ctx.Err(); err != nil {
sendErr(fmt.Errorf("preparing to list pull requests: %v", err))
break
}
var cleanUpBranch bool
var pullRequest *github.PullRequest
logger.Debug("searching for any existing pull request", "owner", githubPath[0], "repo", githubPath[1], "merge_request_id", mergeRequest.IID)
//query := fmt.Sprintf("repo:%s/%s is:pr head:%s", githubPath[0], githubPath[1], mergeRequest.SourceBranch)
query := fmt.Sprintf("repo:%s/%s is:pr", githubPath[0], githubPath[1])
searchResult, err := getGithubSearchResults(ctx, query)
if err != nil {
sendErr(fmt.Errorf("listing pull requests: %v", err))
continue
}
// Look for an existing GitHub pull request
skip := false
for _, issue := range searchResult.Issues {
if issue == nil {
continue
}
// Check for context cancellation
if err := ctx.Err(); err != nil {
sendErr(fmt.Errorf("preparing to retrieve pull request: %v", err))
break
}
if issue.IsPullRequest() {
// Extract the PR number from the URL
prUrl, err := url.Parse(*issue.PullRequestLinks.URL)
if err != nil {
sendErr(fmt.Errorf("parsing pull request url: %v", err))
skip = true
break
}
if m := regexp.MustCompile(".+/([0-9]+)$").FindStringSubmatch(prUrl.Path); len(m) == 2 {
prNumber, _ := strconv.Atoi(m[1])
pr, err := getGithubPullRequest(ctx, githubPath[0], githubPath[1], prNumber)
if err != nil {
sendErr(fmt.Errorf("retrieving pull request: %v", err))
skip = true
break
}
if strings.Contains(pr.GetBody(), fmt.Sprintf("**GitLab MR Number** | %d", mergeRequest.IID)) ||
strings.Contains(pr.GetBody(), fmt.Sprintf("**GitLab MR Number** | [%d]", mergeRequest.IID)) {
logger.Debug("found existing pull request", "owner", githubPath[0], "repo", githubPath[1], "pr_number", pr.GetNumber())
pullRequest = pr
}
}
}
}
if skip {
continue
}
// Proceed to create temporary branches when migrating a merged/closed merge request that doesn't yet have a counterpart PR in GitHub (can't create one without a branch)
if pullRequest == nil && !strings.EqualFold(mergeRequest.State, "opened") {
logger.Trace("searching for existing branch for closed/merged merge request", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID, "source_branch", mergeRequest.SourceBranch)
// Only create temporary branches if the source branch has been deleted
if _, err = repo.Reference(plumbing.ReferenceName(mergeRequest.SourceBranch), false); err != nil {
// Create a worktree
worktree, err := repo.Worktree()
if err != nil {
sendErr(fmt.Errorf("creating worktree: %v", err))
failureCount++
continue
}
// Generate temporary branch names
mergeRequest.SourceBranch = fmt.Sprintf("migration-source-%d/%s", mergeRequest.IID, mergeRequest.SourceBranch)
mergeRequest.TargetBranch = fmt.Sprintf("migration-target-%d/%s", mergeRequest.IID, mergeRequest.TargetBranch)
logger.Trace("retrieving commits for merge request", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID)
mergeRequestCommits, _, err := gl.MergeRequests.GetMergeRequestCommits(project.ID, mergeRequest.IID, &gitlab.GetMergeRequestCommitsOptions{OrderBy: "created_at", Sort: "asc"})
if err != nil {
sendErr(fmt.Errorf("retrieving merge request commits: %v", err))
failureCount++
continue
}
// Some merge requests have no commits, disregard these
if len(mergeRequestCommits) == 0 {
continue
}
// API is buggy, ordering is not respected, so we'll reorder by commit datestamp
sort.Slice(mergeRequestCommits, func(i, j int) bool {
return mergeRequestCommits[i].CommittedDate.Before(*mergeRequestCommits[j].CommittedDate)
})
if mergeRequestCommits[0] == nil {
sendErr(fmt.Errorf("start commit for merge request %d is nil", mergeRequest.IID))
failureCount++
continue
}
if mergeRequestCommits[len(mergeRequestCommits)-1] == nil {
sendErr(fmt.Errorf("end commit for merge request %d is nil", mergeRequest.IID))
failureCount++
continue
}
logger.Trace("inspecting start commit", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID, "sha", mergeRequestCommits[0].ShortID)
startCommit, err := object.GetCommit(repo.Storer, plumbing.NewHash(mergeRequestCommits[0].ID))
if err != nil {
sendErr(fmt.Errorf("loading start commit: %v", err))
failureCount++
continue
}
// Starting with a merge commit is _probably_ wrong
if startCommit.NumParents() > 1 {
sendErr(fmt.Errorf("start commit %s for merge request %d has %d parents", mergeRequestCommits[0].ShortID, mergeRequest.IID, startCommit.NumParents()))
failureCount++
continue
}
if startCommit.NumParents() == 0 {
// Orphaned commit, start with an empty branch
// TODO: this isn't working as hoped, try to figure this out. in the meantime, we'll skip MRs from orphaned branches
//if err = repo.Storer.SetReference(plumbing.NewSymbolicReference("HEAD", plumbing.ReferenceName(fmt.Sprintf("refs/heads/%s", mergeRequest.TargetBranch)))); err != nil {
// return fmt.Errorf("creating empty branch: %s", err)
//}
continue
} else {
// Branch out from parent commit
logger.Trace("inspecting start commit parent", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID, "sha", mergeRequestCommits[0].ShortID)
startCommitParent, err := startCommit.Parent(0)
if err != nil {
sendErr(fmt.Errorf("loading parent commit: %s", err))
failureCount++
continue
}
logger.Trace("creating target branch for merged/closed merge request", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID, "branch", mergeRequest.TargetBranch, "sha", startCommitParent.Hash)
if err = worktree.Checkout(&git.CheckoutOptions{
Create: true,
Force: true,
Branch: plumbing.NewBranchReferenceName(mergeRequest.TargetBranch),
Hash: startCommitParent.Hash,
}); err != nil {
sendErr(fmt.Errorf("checking out temporary target branch: %v", err))
failureCount++
continue
}
}
endHash := plumbing.NewHash(mergeRequestCommits[len(mergeRequestCommits)-1].ID)
logger.Trace("creating source branch for merged/closed merge request", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID, "branch", mergeRequest.SourceBranch, "sha", endHash)
if err = worktree.Checkout(&git.CheckoutOptions{
Create: true,
Force: true,
Branch: plumbing.NewBranchReferenceName(mergeRequest.SourceBranch),
Hash: endHash,
}); err != nil {
sendErr(fmt.Errorf("checking out temporary source branch: %v", err))
failureCount++
continue
}
logger.Debug("pushing branches for merged/closed merge request", "owner", githubPath[0], "repo", githubPath[1], "source_branch", mergeRequest.SourceBranch, "target_branch", mergeRequest.TargetBranch)
if err = repo.PushContext(ctx, &git.PushOptions{
RemoteName: "github",
RefSpecs: []config.RefSpec{
config.RefSpec(fmt.Sprintf("refs/heads/%[1]s:refs/heads/%[1]s", mergeRequest.SourceBranch)),
config.RefSpec(fmt.Sprintf("refs/heads/%[1]s:refs/heads/%[1]s", mergeRequest.TargetBranch)),
},
Force: true,
}); err != nil {
upToDateError := errors.New("already up-to-date")
if errors.As(err, &upToDateError) {
logger.Trace("branch already exists and is up-to-date on GitHub", "owner", githubPath[0], "repo", githubPath[1], "source_branch", mergeRequest.SourceBranch, "target_branch", mergeRequest.TargetBranch)
} else {
sendErr(fmt.Errorf("pushing temporary branches to github: %v", err))
failureCount++
continue
}
}
// We will clean up these temporary branches after configuring and closing the pull request
cleanUpBranch = true
}
}
if renameMasterToMain && mergeRequest.TargetBranch == "master" {
logger.Trace("changing target branch from master to main", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID)
mergeRequest.TargetBranch = "main"
}
githubAuthorName := mergeRequest.Author.Name
author, err := getGitlabUser(mergeRequest.Author.Username)
if err != nil {
sendErr(fmt.Errorf("retrieving gitlab user: %v", err))
failureCount++
continue
}
if author.WebsiteURL != "" {
githubAuthorName = "@" + strings.TrimPrefix(strings.ToLower(author.WebsiteURL), "https://github.com/")
}
originalState := ""
if !strings.EqualFold(mergeRequest.State, "opened") {
originalState = fmt.Sprintf("> This merge request was originally **%s** on GitLab", mergeRequest.State)
}
logger.Debug("determining merge request approvers", "name", gitlabPath[1], "group", gitlabPath[0], "project_id", project.ID, "merge_request_id", mergeRequest.IID)
approvers := make([]string, 0)
awards, _, err := gl.AwardEmoji.ListMergeRequestAwardEmoji(project.ID, mergeRequest.IID, &gitlab.ListAwardEmojiOptions{PerPage: 100})
if err != nil {
sendErr(fmt.Errorf("listing merge request awards: %v", err))
} else {
for _, award := range awards {
if award.Name == "thumbsup" {
approver := award.User.Name
approverUser, err := getGitlabUser(award.User.Username)
if err != nil {
sendErr(fmt.Errorf("retrieving gitlab user: %v", err))
continue
}
if approverUser.WebsiteURL != "" {
approver = "@" + strings.TrimPrefix(strings.ToLower(approverUser.WebsiteURL), "https://github.com/")
}
approvers = append(approvers, approver)
}
}
}
description := mergeRequest.Description
if strings.TrimSpace(description) == "" {
description = "_No description_"
}
slices.Sort(approvers)
approval := strings.Join(approvers, ", ")
if approval == "" {
approval = "_No approvers_"
}
closeDate := ""
if mergeRequest.State == "closed" && mergeRequest.ClosedAt != nil {
closeDate = fmt.Sprintf("\n> | **Date Originally Closed** | %s |", mergeRequest.ClosedAt.Format(dateFormat))
} else if mergeRequest.State == "merged" && mergeRequest.MergedAt != nil {
closeDate = fmt.Sprintf("\n> | **Date Originally Merged** | %s |", mergeRequest.MergedAt.Format(dateFormat))
}
mergeRequestTitle := mergeRequest.Title
if len(mergeRequestTitle) > 40 {
mergeRequestTitle = mergeRequestTitle[:40] + "..."
}
body := fmt.Sprintf(`> [!NOTE]
> This pull request was migrated from GitLab
>
> | | |
> | ---- | ---- |
> | **Original Author** | %[1]s |
> | **GitLab Project** | [%[4]s/%[5]s](https://%[10]s/%[4]s/%[5]s) |
> | **GitLab Merge Request** | [%[11]s](https://%[10]s/%[4]s/%[5]s/merge_requests/%[2]d) |
> | **GitLab MR Number** | [%[2]d](https://%[10]s/%[4]s/%[5]s/merge_requests/%[2]d) |
> | **Date Originally Opened** | %[6]s |%[7]s
> | **Approved on GitLab by** | %[8]s |
> | | |
>
%[9]s
## Original Description
%[3]s`, githubAuthorName, mergeRequest.IID, description, gitlabPath[0], gitlabPath[1], mergeRequest.CreatedAt.Format(dateFormat), closeDate, approval, originalState, gitlabDomain, mergeRequestTitle)
if pullRequest == nil {
logger.Info("creating pull request", "owner", githubPath[0], "repo", githubPath[1], "source_branch", mergeRequest.SourceBranch, "target_branch", mergeRequest.TargetBranch)
newPullRequest := github.NewPullRequest{
Title: &mergeRequest.Title,
Head: &mergeRequest.SourceBranch,
Base: &mergeRequest.TargetBranch,
Body: &body,
MaintainerCanModify: pointer(true),
Draft: &mergeRequest.Draft,
}
if pullRequest, _, err = gh.PullRequests.Create(ctx, githubPath[0], githubPath[1], &newPullRequest); err != nil {
sendErr(fmt.Errorf("creating pull request: %v", err))
failureCount++
continue
}
if mergeRequest.State == "closed" || mergeRequest.State == "merged" {
logger.Debug("closing pull request", "owner", githubPath[0], "repo", githubPath[1], "pr_number", pullRequest.GetNumber())
pullRequest.State = pointer("closed")
if pullRequest, _, err = gh.PullRequests.Edit(ctx, githubPath[0], githubPath[1], pullRequest.GetNumber(), pullRequest); err != nil {
sendErr(fmt.Errorf("updating pull request: %v", err))
failureCount++
continue
}
}
} else {
var newState *string
switch mergeRequest.State {
case "opened":
newState = pointer("open")
case "closed", "merged":
newState = pointer("closed")
}
if (newState != nil && (pullRequest.State == nil || *pullRequest.State != *newState)) ||
(pullRequest.Title == nil || *pullRequest.Title != mergeRequest.Title) ||
(pullRequest.Body == nil || *pullRequest.Body != body) ||
(pullRequest.Draft == nil || *pullRequest.Draft != mergeRequest.Draft) {
logger.Info("updating pull request", "owner", githubPath[0], "repo", githubPath[1], "pr_number", pullRequest.GetNumber())
pullRequest.Title = &mergeRequest.Title
pullRequest.Body = &body
pullRequest.Draft = &mergeRequest.Draft
pullRequest.State = newState
if pullRequest, _, err = gh.PullRequests.Edit(ctx, githubPath[0], githubPath[1], pullRequest.GetNumber(), pullRequest); err != nil {
sendErr(fmt.Errorf("updating pull request: %v", err))
failureCount++
continue
}