-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
1378 lines (1231 loc) · 29.8 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 (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/briandowns/spinner"
"github.com/cli/go-gh"
"github.com/cli/go-gh/pkg/api"
"github.com/fatih/color"
"github.com/pterm/pterm"
"github.com/shurcooL/graphql"
"github.com/spf13/cobra"
"golang.org/x/exp/slices"
)
var (
// flag vars
AutoConfirm = false
CreateIssues = false
CreateCSV = false
GithubSourceOrg string
GithubTargetOrg string
ApiUrl string
GithubSourcePat string
GithubTargetPat string
DefaultBranchRef = fmt.Sprint(
"Post-Migration Audit (PMA) Extension For GitHub CLI. Used to compare ",
"GitHub Enterprise (Server or Cloud) to GitHub Enterprise Cloud (includes ",
"Managed Users) migrations.",
)
// tool vars
AnsiRegex string
DefaultApiUrl string = "github.com"
DefaultIssueTitleTemplate string = "Post Migration Audit"
SourceRestClient api.RESTClient
TargetRestClient api.RESTClient
SourceGraphqlClient api.GQLClient
TargetGraphqlClient api.GQLClient
SourceRepositories []repository = []repository{}
TargetRepositories []repository = []repository{}
ToProcessRepositories []repository = []repository{}
LogFile *os.File
Threads int
ResultsTable pterm.TableData
WaitGroup sync.WaitGroup
// Create some colors and a spinner
Red = color.New(color.FgRed).SprintFunc()
Yellow = color.New(color.FgYellow).SprintFunc()
Cyan = color.New(color.FgCyan).SprintFunc()
Pink = color.New(color.FgHiMagenta).SprintFunc()
Spinner = spinner.New(spinner.CharSets[2], 100*time.Millisecond)
// Create the root cobra command
rootCmd = &cobra.Command{
Use: "gh pma",
Short: DefaultBranchRef,
Long: DefaultBranchRef,
Version: "1.0.0",
SilenceUsage: true,
SilenceErrors: true,
RunE: Process,
}
)
type repositoryQuery struct {
Organization struct {
Repos repoPage `graphql:"repositories(first: 100, after: $page)"`
} `graphql:"organization(login: $owner)"`
}
type rateResponse struct {
Limit int
Remaining int
Reset int
Used int
}
type apiResponse struct {
Resources struct {
Core rateResponse
Graphql rateResponse
}
Message string
Rate rateResponse
}
type file struct {
Content string
}
type environments struct {
Environments []environment
Total_Count int
}
type environment struct {
Name string
}
type issues struct {
Items []issue
Total_Count int
}
type issue struct {
Title string
ID int
Number int
State string
}
type repoPage struct {
PageInfo struct {
HasNextPage bool
EndCursor graphql.String
}
Nodes []repoNode
}
type branchRef struct {
Name string
}
type repoNode struct {
Name string
NameWithOwner string
Visibility string
Owner owner
DefaultBranchRef branchRef
}
type repository struct {
Name string
Owner string
NameWithOwner string
DefaultBranchRef branchRef
Visibility string
TargetVisibility string
ExistsInTarget bool
Secrets secrets
Variables variables
Environments environments
LFS file
}
type owner struct {
Login string
}
type secrets struct {
Secrets []secret
Total_Count int
}
type secret struct {
Name string
}
type variables struct {
Variables []variable
Total_Count int
}
type variable struct {
Name string
Value string
}
type user struct {
Login string
}
func init() {
rootCmd.PersistentFlags().StringVar(
&GithubSourceOrg,
"github-source-org",
"",
fmt.Sprint(
"Uses GH_SOURCE_PAT env variable or --github-source-pat option. Will ",
"fall back to GH_PAT or --github-target-pat if not set.",
),
)
rootCmd.PersistentFlags().StringVar(
&GithubTargetOrg,
"github-target-org",
"",
"Uses GH_PAT env variable or --github-target-pat option.",
)
rootCmd.PersistentFlags().StringVar(
&ApiUrl,
"ghes-api-url",
DefaultApiUrl,
fmt.Sprint(
"Required if migration source is GHES. The domain name for your GHES ",
"instance. For example: ghes.contoso.com",
),
)
rootCmd.PersistentFlags().StringVar(
&GithubSourcePat,
"github-source-pat",
"",
"",
)
rootCmd.PersistentFlags().StringVar(
&GithubTargetPat,
"github-target-pat",
"",
"",
)
rootCmd.PersistentFlags().IntVar(
&Threads,
"threads",
3,
fmt.Sprint(
"Number of threads to process concurrently. Maximum of 10 allowed. ",
"Increasing this number could get your PAT blocked due to API limiting.",
),
)
rootCmd.PersistentFlags().BoolVar(
&AutoConfirm,
"confirm",
false,
"Auto respond to visibility alignment confirmation prompt",
)
rootCmd.PersistentFlags().BoolVarP(
&CreateIssues,
"create-issues",
"i",
false,
"Whether to create issues in target org repositories or not.",
)
rootCmd.PersistentFlags().BoolVarP(
&CreateCSV,
"create-csv",
"c",
false,
"Whether to create a CSV file with the results.",
)
// make certain flags required
rootCmd.MarkPersistentFlagRequired("github-source-org")
rootCmd.MarkPersistentFlagRequired("github-target-org")
// update version template to show extension name
rootCmd.SetVersionTemplate(
fmt.Sprintf("PMA Extension for GitHub CLI, v%s\n", rootCmd.Version),
)
// add args here
rootCmd.Args = cobra.MaximumNArgs(0)
// set ANSI regex
AnsiRegex = "[\u001B\u009B]"
AnsiRegex += "[[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]"
AnsiRegex += "*(?:;[a-zA-Z\\d]*)*)?\u0007)"
AnsiRegex += "|(?:(?:\\d{1,4}(?:;\\d{0,4})*)"
AnsiRegex += "?[\\dA-PRZcf-ntqry=><~]))"
}
func main() {
if err := rootCmd.Execute(); err != nil {
ExitOnError(err)
}
}
func ExitOnError(err error) {
if err != nil {
rootCmd.PrintErrln(err.Error())
os.Exit(1)
}
}
func ExitManual(err error) {
Spinner.Stop()
fmt.Println(err.Error())
os.Exit(1)
}
func OutputFlags(key string, value string) {
sep := ": "
fmt.Println(fmt.Sprint(Pink(key), sep, value))
Log(fmt.Sprint(key, sep, value))
}
func OutputNotice(message string) {
Output(message, "default", false, false)
}
func OutputWarning(message string) {
Output(fmt.Sprint("[WARNING] ", message), "yellow", false, false)
}
func OutputError(message string, exit bool) {
Spinner.Stop()
Output(message, "red", true, exit)
}
func Output(message string, color string, isErr bool, exit bool) {
if isErr {
message = fmt.Sprint("[ERROR] ", message)
}
Log(StripAnsi(message))
switch {
case color == "red":
message = Red(message)
case color == "yellow":
message = Yellow(message)
}
fmt.Println(message)
if exit {
fmt.Println("")
os.Exit(1)
}
}
func AskForConfirmation(s string) (res bool, err error) {
// read the input
reader := bufio.NewReader(os.Stdin)
// loop until a response is valid
for {
fmt.Printf("%s [y/n]: ", s)
response, err := reader.ReadString('\n')
Debug(fmt.Sprint("User responded with: ", response))
if err != nil {
return false, err
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return true, err
} else if response == "n" || response == "no" {
return false, err
}
}
}
func DebugAndStatus(message string) string {
Spinner.Suffix = fmt.Sprint(
" ",
message,
)
return Debug(message)
}
func Debug(message string) string {
Log(message)
return message
}
func DisplayRateLeft() {
// validate we have API attempts left
rateLeft, _ := ValidateApiRate(SourceRestClient, "core")
rateMessage := Cyan("API Rate Limit Left:")
OutputNotice(fmt.Sprintf("%s %d", rateMessage, rateLeft))
LF()
}
func IsTargetProvided() bool {
if GithubTargetOrg != "" {
return true
}
return false
}
func GetOpts(hostname, token string) (options api.ClientOptions) {
// set options
opts := api.ClientOptions{
Host: hostname,
CacheTTL: time.Hour,
}
if token != "" {
opts.AuthToken = token
}
return opts
}
func LF() {
fmt.Println("")
}
func LFSExists(base64File string) (string, bool, error) {
decodedContents, err := base64.StdEncoding.DecodeString(base64File)
if err != nil {
return "", false, err
}
if strings.Contains(string(decodedContents), "filter=lfs") {
return string(decodedContents), true, err
}
return string(decodedContents), false, err
}
func Log(message string) {
if message != "" {
message = fmt.Sprint(
"[",
time.Now().Format("2006-01-02 15:04:05"),
"] ",
message,
)
}
_, err := LogFile.WriteString(
fmt.Sprintln(message),
)
if err != nil {
fmt.Println(Red("Unable to write to log file."))
fmt.Println(Red(err))
os.Exit(1)
}
}
func Truncate(str string, limit int) string {
lastSpaceIx := -1
len := 0
for i, r := range str {
if unicode.IsSpace(r) {
lastSpaceIx = i
}
len++
if len >= limit {
if lastSpaceIx != -1 {
return fmt.Sprint(str[:lastSpaceIx], "...")
} else {
return fmt.Sprint(str[:limit], "...")
}
}
}
return str
}
func StripAnsi(str string) string {
regex := regexp.MustCompile(AnsiRegex)
return regex.ReplaceAllString(str, "")
}
func SleepIfLongerThan(thisTime time.Time) {
// delay if write was fast
elapsed := time.Since(thisTime)
if elapsed.Seconds() < 1 {
wait := 1000 - elapsed.Milliseconds()
DebugAndStatus(
fmt.Sprintf(
"Execution time was %v. Waiting for %vms to avoid rate limiting.",
elapsed.Seconds(),
wait,
),
)
time.Sleep(time.Duration(wait) * time.Millisecond)
}
}
func Process(cmd *cobra.Command, args []string) (err error) {
// Create log file
LogFile, err = os.Create(
fmt.Sprint(
time.Now().Format("20060102150401"),
".pma.log",
),
)
if err != nil {
return err
}
defer LogFile.Close()
Debug("---- VALIDATING FLAGS & ENV VARS ----")
if GithubSourcePat == "" {
GithubSourcePatEnv, isSet := os.LookupEnv("GH_SOURCE_PAT")
if isSet {
GithubSourcePat = GithubSourcePatEnv
Debug("Source PAT set from Environment Variable GH_SOURCE_PAT")
} else {
OutputError(
fmt.Sprint(
"A source PAT was not provided via --github-source-pat or ",
"environment variable GH_SOURCE_PAT",
),
true,
)
}
}
if GithubTargetPat == "" {
GithubTargetPatEnv, isSet := os.LookupEnv("GH_PAT")
if isSet {
GithubTargetPat = GithubTargetPatEnv
Debug("Target PAT set from Environment Variable GH_PAT")
} else {
OutputError(
fmt.Sprint(
"A target PAT was not provided via --github-target-pat or ",
"environment variable GH_PAT",
),
true,
)
}
}
// validate API URL
r, _ := regexp.Compile("^http(s|):(//|)")
if r.MatchString(ApiUrl) {
OutputError(
"--ghes-api-url should NOT contain http(s).",
true,
)
}
if Threads > 10 {
OutputError("Number of concurrent threads cannot be higher than 10.", true)
} else if Threads > 3 {
OutputWarning(
fmt.Sprint(
"Number of concurrent threads is higher than 3. This could result in ",
"extreme load on your server.",
),
)
}
LF()
// output flags for reference
OutputFlags("GitHub Source Org", GithubSourceOrg)
if ApiUrl != DefaultApiUrl {
OutputFlags("GHES Source URL", ApiUrl)
}
if IsTargetProvided() {
OutputFlags("GitHub Target Org", GithubTargetOrg)
}
OutputFlags("Read Threads", fmt.Sprintf("%d", Threads))
LF()
Debug("---- SETTING UP API CLIENTS ----")
// set up clients
opts := GetOpts(ApiUrl, GithubSourcePat)
SourceRestClient, err = gh.RESTClient(&opts)
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed to set up source REST client.", true)
}
SourceGraphqlClient, err = gh.GQLClient(&opts)
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed set set up source GraphQL client.", true)
}
opts = GetOpts(DefaultApiUrl, GithubTargetPat)
TargetRestClient, err = gh.RESTClient(&opts)
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed to set up target REST client.", true)
}
TargetGraphqlClient, err = gh.GQLClient(&opts)
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed set set up target GraphQL client.", true)
}
Debug("---- LOOKING UP REPOSITORIES IN ORGS ----")
Spinner.Start()
// thread getting repos
WaitGroup.Add(2)
go GetSourceRepositories()
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed to get source repositories.", true)
}
go GetTargetRepositories()
if err != nil {
Debug(fmt.Sprint("Error object: ", err))
OutputError("Failed to get target repositories.", true)
}
WaitGroup.Wait()
Debug(fmt.Sprintf("Found %d repositories", len(SourceRepositories)))
Debug("---- GETTING REPOSITORY DATA ----")
// set up table header for displaying of data
Debug("Creating table data for display...")
ResultsTable = pterm.TableData{
{
"Repository",
"Exists In Target",
"Default Branch",
"Visibility",
"Secrets",
"Variables",
"Environments",
},
}
// set a temp var that we can batch through without effecting the original
repositoriesToProcess := SourceRepositories
batchThreads := Threads
batchNum := 1
for len(repositoriesToProcess) > 0 {
repositoriesLeft := len(repositoriesToProcess)
if repositoriesLeft < Threads {
batchThreads = repositoriesLeft
Debug(
fmt.Sprint(
"Setting number of threads to",
fmt.Sprintf(
" %d because there are only %d repositories left.",
repositoriesLeft,
repositoriesLeft,
),
),
)
}
DebugAndStatus(
fmt.Sprintf(
"Running repository analysis batch #%d (%d threads)...",
batchNum,
batchThreads,
),
)
// get the next batch into new array and remove from processing array
batch := repositoriesToProcess[:batchThreads]
repositoriesToProcess = repositoriesToProcess[len(batch):]
// add the number of wait groups needed
WaitGroup.Add(len(batch))
// process threads
for i := 0; i < len(batch); i++ {
Debug(
fmt.Sprintf(
"Running thread %d of %d on repository '%s'",
i+1,
len(batch),
batch[i].NameWithOwner,
),
)
go GetRepositoryStatistics(SourceRestClient, batch[i])
}
// wait for threads to finish
WaitGroup.Wait()
batchNum++
}
Spinner.Stop()
// output table
if len(SourceRepositories) > 0 {
pterm.DefaultTable.WithHasHeader().
WithHeaderRowSeparator("-").
WithData(ResultsTable).Render()
} else {
OutputNotice("No repositories found.")
return err
}
// Create output file
if CreateCSV {
outputFile, err := os.Create(
fmt.Sprint(
time.Now().Format("20060102150401"),
".",
GithubSourceOrg,
".csv",
),
)
if err != nil {
return err
}
defer outputFile.Close()
// write header
_, err = outputFile.WriteString(
fmt.Sprintln(
"repository,",
"exists_in_target,",
"default_branch,",
"visibility,",
"secrets,",
"variables,",
"environments",
"lfs",
),
)
if err != nil {
OutputError("Error writing to output file.", true)
}
// write body
for _, repository := range SourceRepositories {
line := fmt.Sprintf("%s", repository.NameWithOwner)
if !IsTargetProvided() {
line = fmt.Sprintf("%s,%s", line, "Unknown")
} else {
line = fmt.Sprintf("%s,%t", line, repository.ExistsInTarget)
}
_, foundLFS, _ := LFSExists(repository.LFS.Content)
lfsString := "No"
if foundLFS {
lfsString = "Potentially"
}
line = fmt.Sprintf(
"%s,%s,%s|%s,%d,%d,%d,%s\n",
line,
repository.DefaultBranchRef.Name,
repository.Visibility,
repository.TargetVisibility,
repository.Secrets.Total_Count,
repository.Variables.Total_Count,
repository.Environments.Total_Count,
lfsString,
)
_, err = outputFile.WriteString(line)
if err != nil {
OutputError("Error writing to output file.", true)
}
}
}
// create issues if we need to
if CreateIssues {
Spinner.Start()
DebugAndStatus("Attempting to create issues for repositories...")
err = ProcessIssues(SourceRestClient, GithubTargetOrg, SourceRepositories)
Spinner.Stop()
if err != nil {
return err
}
}
// prompt for fixing
if len(ToProcessRepositories) > 0 {
// find out if we need to process visibility
repoWord := "repository"
if len(ToProcessRepositories) > 1 {
repoWord = "repositories"
}
proceedMessage := Debug(fmt.Sprintf(
"Do you want to align visibility for %d %s?",
len(ToProcessRepositories),
repoWord,
))
// auto confirm
c := true
if !AutoConfirm {
c, err = AskForConfirmation(Yellow(proceedMessage))
}
if err != nil {
OutputError(err.Error(), true)
} else if !c {
// warn when manually abandoned
LF()
OutputWarning("Alignment process abandoned.")
LF()
DisplayRateLeft()
return err
}
// process if code gets to here
Spinner.Start()
err = ProcessRepositoryVisibilities(
TargetRestClient,
GithubTargetOrg,
ToProcessRepositories,
)
Spinner.Stop()
// on successful processing
if err == nil {
LF()
OutputNotice(
fmt.Sprintf(
"Successfully processed %d repositories.",
len(ToProcessRepositories),
),
)
LF()
}
}
DisplayRateLeft()
// always return
return err
}
func ValidateApiRate(
client api.RESTClient,
requestType string,
) (left int, err error) {
apiResponse := apiResponse{}
attempts := 0
rateRemaining := 0
for {
// after 240 attempts (1 hour), end the scrip.
if attempts >= 240 {
return 0, errors.New(
fmt.Sprint(
"After an hour of retrying, the API rate limit has not ",
"refreshed. Aborting.",
),
)
}
// get the current rate liit left or error out if request fails
err = client.Get("rate_limit", &apiResponse)
if err != nil {
Debug("Failed to get rate limit from GitHub server.")
return 0, err
}
// if rate limiting is disabled, do not proceed
if apiResponse.Message == "Rate limiting is not enabled." {
Debug("Rate limit is not enabled.")
return 0, err
}
// choose which response to validate
switch {
default:
return 0, errors.New(
fmt.Sprintf(
"Invalid API request type provided: '%s'",
requestType,
),
)
case requestType == "core":
rateRemaining = apiResponse.Resources.Core.Remaining
case requestType == "graphql":
rateRemaining = apiResponse.Resources.Graphql.Remaining
}
// validate there is rate left
if rateRemaining <= 0 {
attempts++
DebugAndStatus(
fmt.Sprint(
"API rate limit ",
fmt.Sprintf(
"(%s) has none remaining. Sleeping for 15 seconds (attempt #%d)",
requestType,
attempts,
),
),
)
time.Sleep(15 * time.Second)
} else {
break
}
}
return rateRemaining, err
}
func GetRepositoryStatistics(client api.RESTClient, repoToProcess repository) {
// validate we have API attempts left
_, timeoutErr := ValidateApiRate(client, "core")
if timeoutErr != nil {
OutputError(timeoutErr.Error(), true)
}
// start timer
start := time.Now()
// get number of secrets
var secretsResponse secrets
secretsErr := client.Get(
fmt.Sprintf(
"repos/%s/actions/secrets",
repoToProcess.NameWithOwner,
),
&secretsResponse,
)
Debug(fmt.Sprintf(
"Secrets from %s: %+v",
repoToProcess.NameWithOwner,
secretsResponse,
))
if secretsErr != nil {
ExitManual(secretsErr)
} else {
repoToProcess.Secrets = secretsResponse
}
// validate we have API attempts left
_, timeoutErr = ValidateApiRate(client, "core")
if timeoutErr != nil {
OutputError(timeoutErr.Error(), true)
}
// get number of variables
var variablesResponse variables
variablesErr := client.Get(
fmt.Sprintf(
"repos/%s/actions/variables",
repoToProcess.NameWithOwner,
),
&variablesResponse,
)
Debug(fmt.Sprintf(
"Variables from %s: %+v",
repoToProcess.NameWithOwner,
variablesResponse,
))
if variablesErr != nil {
ExitManual(variablesErr)
} else {
repoToProcess.Variables = variablesResponse
}
// validate we have API attempts left
_, timeoutErr = ValidateApiRate(client, "core")
if timeoutErr != nil {
OutputError(timeoutErr.Error(), true)
}
// get number of variables
var envResponse environments
envsErr := client.Get(
fmt.Sprintf(
"repos/%s/environments",
repoToProcess.NameWithOwner,
),
&envResponse,
)
Debug(fmt.Sprintf(
"Environments from %s: %+v",
repoToProcess.NameWithOwner,
envResponse,
))
if envsErr != nil {
ExitManual(envsErr)
} else {
repoToProcess.Environments = envResponse
}
// get LFS definition file
var fileResponse file
_ = client.Get(
fmt.Sprintf(
"repos/%s/contents/.gitattributes",
repoToProcess.NameWithOwner,
),
&fileResponse,
)
Debug(fmt.Sprintf(
"Contents of .gitattributes from %s: %+v",
repoToProcess.NameWithOwner,
fileResponse,
))
repoToProcess.LFS = fileResponse
// find if repo exists in target
tIdx := slices.IndexFunc(TargetRepositories, func(r repository) bool {
return r.Name == repoToProcess.Name
})
if tIdx < 0 {
repoToProcess.ExistsInTarget = false
repoToProcess.TargetVisibility = fmt.Sprintf("UNKNOWN")
} else {
repoToProcess.ExistsInTarget = true
repoToProcess.TargetVisibility = TargetRepositories[tIdx].Visibility
// add this repo to array of processing if visibilties don't match
if repoToProcess.Visibility != TargetRepositories[tIdx].Visibility {
ToProcessRepositories = append(ToProcessRepositories, repoToProcess)
}
}
// find index of repo in original list and overwite it
idx := slices.IndexFunc(SourceRepositories, func(r repository) bool {
return r.NameWithOwner == repoToProcess.NameWithOwner
})
if idx < 0 {
OutputError(
fmt.Sprintf(
"Error finding batch repository in original list: %s",
repoToProcess.NameWithOwner,
),
false,
)
} else {
SourceRepositories[idx] = repoToProcess
}
// write to table for output
visiblity := fmt.Sprintf(
"%s",
repoToProcess.Visibility,
)
existsInTarget := strconv.FormatBool(repoToProcess.ExistsInTarget)