-
Notifications
You must be signed in to change notification settings - Fork 88
/
GithubApi.cs
1220 lines (1037 loc) · 44 KB
/
GithubApi.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Octoshift.Models;
using OctoshiftCLI.Extensions;
using OctoshiftCLI.Models;
namespace OctoshiftCLI.Services;
public class GithubApi
{
private readonly GithubClient _client;
private readonly string _apiUrl;
private readonly RetryPolicy _retryPolicy;
private readonly ArchiveUploader _multipartUploader;
public GithubApi(GithubClient client, string apiUrl, RetryPolicy retryPolicy, ArchiveUploader multipartUploader)
{
_client = client;
_apiUrl = apiUrl;
_retryPolicy = retryPolicy;
_multipartUploader = multipartUploader;
}
public virtual async Task AddAutoLink(string org, string repo, string keyPrefix, string urlTemplate)
{
if (string.IsNullOrWhiteSpace(keyPrefix))
{
throw new ArgumentException($"Invalid value for {nameof(keyPrefix)}");
}
if (string.IsNullOrWhiteSpace(urlTemplate))
{
throw new ArgumentException($"Invalid value for {nameof(urlTemplate)}");
}
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/autolinks";
var payload = new
{
key_prefix = keyPrefix,
url_template = urlTemplate
};
await _client.PostAsync(url, payload);
}
public virtual async Task<List<(int Id, string KeyPrefix, string UrlTemplate)>> GetAutoLinks(string org, string repo)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/autolinks";
return await _client.GetAllAsync(url)
.Select(al => ((int)al["id"], (string)al["key_prefix"], (string)al["url_template"]))
.ToListAsync();
}
public virtual async Task DeleteAutoLink(string org, string repo, int autoLinkId)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/autolinks/{autoLinkId}";
await _client.DeleteAsync(url);
}
public virtual async Task<(string Id, string Slug)> CreateTeam(string org, string teamName)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams";
var payload = new { name = teamName, privacy = "closed" };
var response = await _client.PostAsync(url, payload);
var data = JObject.Parse(response);
return ((string)data["id"], (string)data["slug"]);
}
public virtual async Task<IEnumerable<(string Name, string Slug)>> GetTeams(string org)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams";
return await _client.GetAllAsync(url)
.Select(t => ((string)t["name"], (string)t["slug"]))
.ToListAsync();
}
public virtual async Task<IEnumerable<string>> GetTeamMembers(string org, string teamSlug)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams/{teamSlug.EscapeDataString()}/members?per_page=100";
return await _retryPolicy.HttpRetry(async () => await _client.GetAllAsync(url).Select(x => (string)x["login"]).ToListAsync(),
ex => ex.StatusCode == HttpStatusCode.NotFound);
}
public virtual async Task<IEnumerable<(string Name, string Visibility)>> GetRepos(string org)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/repos?per_page=100";
return await _client.GetAllAsync(url).Select(x => ((string)x["name"], (string)x["visibility"])).ToListAsync();
}
public virtual async Task RemoveTeamMember(string org, string teamSlug, string member)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams/{teamSlug.EscapeDataString()}/memberships/{member.EscapeDataString()}";
await _retryPolicy.Retry(() => _client.DeleteAsync(url));
}
public virtual async Task<string> GetLoginName()
{
var url = $"{_apiUrl}/graphql";
var payload = new
{
query = "query{viewer{login}}"
};
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["viewer"]["login"];
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to lookup the login for current user", ex);
}
}
public virtual async Task<string> GetOrgMembershipForUser(string org, string member)
{
var url = $"{_apiUrl}/orgs/{org}/memberships/{member}";
try
{
var response = await _client.GetAsync(url);
var data = JObject.Parse(response);
return (string)data["role"];
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) // Not a member
{
return null;
}
}
public virtual async Task<bool> DoesRepoExist(string org, string repo)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}";
try
{
await _client.GetNonSuccessAsync(url, HttpStatusCode.NotFound);
return false;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.OK)
{
return true;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.MovedPermanently)
{
return false;
}
}
public virtual async Task<bool> DoesOrgExist(string org)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}";
try
{
await _client.GetAsync(url);
return true;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
}
public virtual async Task AddTeamSync(string org, string teamName, string groupId, string groupName, string groupDesc)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams/{teamName.EscapeDataString()}/team-sync/group-mappings";
var payload = new
{
groups = new[]
{
new { group_id = groupId, group_name = groupName, group_description = groupDesc }
}
};
await _client.PatchAsync(url, payload);
}
public virtual async Task AddTeamToRepo(string org, string repo, string teamSlug, string role)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams/{teamSlug.EscapeDataString()}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}";
var payload = new { permission = role };
await _client.PutAsync(url, payload);
}
public virtual async Task<string> GetOrganizationId(string org)
{
var url = $"{_apiUrl}/graphql";
var payload = new
{
query = "query($login: String!) {organization(login: $login) { login, id, name } }",
variables = new { login = org }
};
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["organization"]["id"];
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to lookup the Organization ID for organization '{org}'", ex);
}
}
public virtual async Task<string> GetOrganizationDatabaseId(string org)
{
var url = $"{_apiUrl}/graphql";
var payload = new
{
query = "query($login: String!) {organization(login: $login) { login, databaseId, name } }",
variables = new { login = org }
};
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["organization"]["databaseId"];
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to lookup the Organization database ID for organization '{org}'", ex);
}
}
public virtual async Task<string> GetEnterpriseId(string enterpriseName)
{
var url = $"{_apiUrl}/graphql";
var payload = new
{
query = "query($slug: String!) {enterprise (slug: $slug) { slug, id } }",
variables = new { slug = enterpriseName }
};
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["enterprise"]["id"];
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to lookup the Enterprise ID for enterprise '{enterpriseName}'", ex);
}
}
public virtual async Task<string> CreateAdoMigrationSource(string orgId, string adoServerUrl)
{
var url = $"{_apiUrl}/graphql";
var query = "mutation createMigrationSource($name: String!, $url: String!, $ownerId: ID!, $type: MigrationSourceType!)";
var gql = "createMigrationSource(input: {name: $name, url: $url, ownerId: $ownerId, type: $type}) { migrationSource { id, name, url, type } }";
adoServerUrl = adoServerUrl.HasValue() ? adoServerUrl : "https://dev.azure.com";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new
{
name = "Azure DevOps Source",
url = adoServerUrl,
ownerId = orgId,
type = "AZURE_DEVOPS"
},
operationName = "createMigrationSource"
};
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["createMigrationSource"]["migrationSource"]["id"];
}
public virtual async Task<string> CreateBbsMigrationSource(string orgId)
{
var url = $"{_apiUrl}/graphql";
var query = "mutation createMigrationSource($name: String!, $url: String!, $ownerId: ID!, $type: MigrationSourceType!)";
var gql = "createMigrationSource(input: {name: $name, url: $url, ownerId: $ownerId, type: $type}) { migrationSource { id, name, url, type } }";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new
{
name = "Bitbucket Server Source",
url = "https://not-used",
ownerId = orgId,
type = "BITBUCKET_SERVER"
},
operationName = "createMigrationSource"
};
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["createMigrationSource"]["migrationSource"]["id"];
}
public virtual async Task<string> CreateGhecMigrationSource(string orgId)
{
var url = $"{_apiUrl}/graphql";
var query = "mutation createMigrationSource($name: String!, $url: String!, $ownerId: ID!, $type: MigrationSourceType!)";
var gql = "createMigrationSource(input: {name: $name, url: $url, ownerId: $ownerId, type: $type}) { migrationSource { id, name, url, type } }";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new
{
name = "GHEC Source",
url = "https://github.com",
ownerId = orgId,
type = "GITHUB_ARCHIVE"
},
operationName = "createMigrationSource"
};
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["createMigrationSource"]["migrationSource"]["id"];
}
public virtual async Task<string> StartMigration(string migrationSourceId, string sourceRepoUrl, string orgId, string repo, string sourceToken, string targetToken, string gitArchiveUrl = null, string metadataArchiveUrl = null, bool skipReleases = false, string targetRepoVisibility = null, bool lockSource = false)
{
var url = $"{_apiUrl}/graphql";
var query = @"
mutation startRepositoryMigration(
$sourceId: ID!,
$ownerId: ID!,
$sourceRepositoryUrl: URI!,
$repositoryName: String!,
$continueOnError: Boolean!,
$gitArchiveUrl: String,
$metadataArchiveUrl: String,
$accessToken: String!,
$githubPat: String,
$skipReleases: Boolean,
$targetRepoVisibility: String,
$lockSource: Boolean)";
var gql = @"
startRepositoryMigration(
input: {
sourceId: $sourceId,
ownerId: $ownerId,
sourceRepositoryUrl: $sourceRepositoryUrl,
repositoryName: $repositoryName,
continueOnError: $continueOnError,
gitArchiveUrl: $gitArchiveUrl,
metadataArchiveUrl: $metadataArchiveUrl,
accessToken: $accessToken,
githubPat: $githubPat,
skipReleases: $skipReleases,
targetRepoVisibility: $targetRepoVisibility,
lockSource: $lockSource
}
) {
repositoryMigration {
id,
databaseId,
migrationSource {
id,
name,
type
},
sourceUrl,
state,
failureReason
}
}";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new
{
sourceId = migrationSourceId,
ownerId = orgId,
sourceRepositoryUrl = sourceRepoUrl,
repositoryName = repo,
continueOnError = true,
gitArchiveUrl,
metadataArchiveUrl,
accessToken = sourceToken,
githubPat = targetToken,
skipReleases,
targetRepoVisibility,
lockSource
},
operationName = "startRepositoryMigration"
};
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["startRepositoryMigration"]["repositoryMigration"]["id"];
}
public virtual async Task<string> StartOrganizationMigration(string sourceOrgUrl, string targetOrgName, string targetEnterpriseId, string sourceAccessToken)
{
var url = $"{_apiUrl}/graphql";
var query = @"
mutation startOrganizationMigration (
$sourceOrgUrl: URI!,
$targetOrgName: String!,
$targetEnterpriseId: ID!,
$sourceAccessToken: String!)";
var gql = @"
startOrganizationMigration(
input: {
sourceOrgUrl: $sourceOrgUrl,
targetOrgName: $targetOrgName,
targetEnterpriseId: $targetEnterpriseId,
sourceAccessToken: $sourceAccessToken
}) {
orgMigration {
id,
databaseId
}
}";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new
{
sourceOrgUrl,
targetOrgName,
targetEnterpriseId,
sourceAccessToken
},
operationName = "startOrganizationMigration"
};
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["startOrganizationMigration"]["orgMigration"]["id"];
}
public virtual async Task<(string State, string SourceOrgUrl, string TargetOrgName, string FailureReason, int? RemainingRepositoriesCount, int? TotalRepositoriesCount)> GetOrganizationMigration(string migrationId)
{
var url = $"{_apiUrl}/graphql";
var query = "query($id: ID!)";
var gql = "node(id: $id) { ... on OrganizationMigration { state, sourceOrgUrl, targetOrgName, failureReason, remainingRepositoriesCount, totalRepositoriesCount } }";
var payload = new { query = $"{query} {{ {gql} }}", variables = new { id = migrationId } };
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (
State: (string)data["data"]["node"]["state"],
SourceOrgUrl: (string)data["data"]["node"]["sourceOrgUrl"],
TargetOrgName: (string)data["data"]["node"]["targetOrgName"],
FailureReason: (string)data["data"]["node"]["failureReason"],
RemainingRepositoriesCount: (int?)data["data"]["node"]["remainingRepositoriesCount"],
TotalRepositoriesCount: (int?)data["data"]["node"]["totalRepositoriesCount"]);
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to get migration state for migration {migrationId}", ex);
}
}
public virtual async Task<string> StartBbsMigration(string migrationSourceId, string bbsRepoUrl, string orgId, string repo, string targetToken, string archiveUrl, string targetRepoVisibility = null)
{
return await StartMigration(
migrationSourceId,
bbsRepoUrl, // source repository URL
orgId,
repo,
"not-used", // source access token
targetToken,
archiveUrl,
"https://not-used", // metadata archive URL
false, // skip releases
targetRepoVisibility,
false // lock source
);
}
public virtual async Task<(string State, string RepositoryName, int WarningsCount, string FailureReason, string MigrationLogUrl)> GetMigration(string migrationId)
{
var url = $"{_apiUrl}/graphql";
var query = "query($id: ID!)";
var gql = @"
node(id: $id) {
... on Migration {
id,
sourceUrl,
migrationLogUrl,
migrationSource {
name
},
state,
warningsCount,
failureReason,
repositoryName
}
}";
var payload = new { query = $"{query} {{ {gql} }}", variables = new { id = migrationId } };
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return (
State: (string)data["data"]["node"]["state"],
RepositoryName: (string)data["data"]["node"]["repositoryName"],
WarningsCount: (int)data["data"]["node"]["warningsCount"],
FailureReason: (string)data["data"]["node"]["failureReason"],
MigrationLogUrl: (string)data["data"]["node"]["migrationLogUrl"]);
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to get migration state for migration {migrationId}", ex);
}
}
public virtual async Task<(string MigrationLogUrl, string MigrationId)?> GetMigrationLogUrl(string org, string repo)
{
var url = $"{_apiUrl}/graphql";
var query = "query ($org: String!, $repo: String!)";
var gql = @"
organization(login: $org) {
repositoryMigrations(last: 1, repositoryName: $repo) {
nodes {
id
migrationLogUrl
}
}
}
";
var payload = new { query = $"{query} {{ {gql} }}", variables = new { org, repo } };
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
var nodes = (JArray)data["data"]["organization"]["repositoryMigrations"]["nodes"];
return nodes.Count == 0
// No matching migration was found
? ((string MigrationLogUrl, string MigrationId)?)null
// A matching migration was found, which may or may not have a migration log URL. If there is no migration log, it's an empty string.
: (MigrationLogUrl: (string)nodes[0]["migrationLogUrl"], MigrationId: (string)nodes[0]["id"]);
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to get migration log URL.", ex);
}
}
public virtual async Task<int> GetIdpGroupId(string org, string groupName)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/external-groups";
var group = await _client.GetAllAsync(url, data => (JArray)data["groups"])
.SingleAsync(x => string.Equals((string)x["group_name"], groupName, StringComparison.OrdinalIgnoreCase));
return (int)group["group_id"];
}
public virtual async Task<string> GetTeamSlug(string org, string teamName)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams";
var response = await _client.GetAllAsync(url)
.SingleAsync(x => ((string)x["name"]).ToUpper() == teamName.ToUpper());
return (string)response["slug"];
}
public virtual async Task AddEmuGroupToTeam(string org, string teamSlug, int groupId)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/teams/{teamSlug.EscapeDataString()}/external-groups";
var payload = new { group_id = groupId };
await _retryPolicy.HttpRetry(async () => await _client.PatchAsync(url, payload),
ex => ex.StatusCode == HttpStatusCode.BadRequest);
}
public virtual async Task<bool> GrantMigratorRole(string org, string actor, string actorType)
{
var url = $"{_apiUrl}/graphql";
var query = "mutation grantMigratorRole ( $organizationId: ID!, $actor: String!, $actor_type: ActorType! )";
var gql = "grantMigratorRole( input: {organizationId: $organizationId, actor: $actor, actorType: $actor_type }) { success }";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new { organizationId = org, actor, actor_type = actorType },
operationName = "grantMigratorRole"
};
try
{
var data = await _client.PostGraphQLAsync(url, payload);
return (bool)data["data"]["grantMigratorRole"]["success"];
}
catch (HttpRequestException)
{
return false;
}
}
public virtual async Task<bool> RevokeMigratorRole(string org, string actor, string actorType)
{
var url = $"{_apiUrl}/graphql";
var query = "mutation revokeMigratorRole ( $organizationId: ID!, $actor: String!, $actor_type: ActorType! )";
var gql = "revokeMigratorRole( input: {organizationId: $organizationId, actor: $actor, actorType: $actor_type }) { success }";
var payload = new
{
query = $"{query} {{ {gql} }}",
variables = new { organizationId = org, actor, actor_type = actorType },
operationName = "revokeMigratorRole"
};
try
{
var data = await _client.PostGraphQLAsync(url, payload);
return (bool)data["data"]["revokeMigratorRole"]["success"];
}
catch (HttpRequestException)
{
return false;
}
}
public virtual async Task DeleteRepo(string org, string repo)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}";
await _client.DeleteAsync(url);
}
public virtual async Task<int> StartGitArchiveGeneration(string org, string repo)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/migrations";
var options = new
{
repositories = new[] { repo },
exclude_metadata = true
};
try
{
var response = await _client.PostAsync(url, options);
var data = JObject.Parse(response);
return (int)data["id"];
}
catch (HttpRequestException ex) when (ex.Message.Contains("configure blob storage"))
{
throw new OctoshiftCliException(ex.Message, ex);
}
}
public virtual async Task<int> StartMetadataArchiveGeneration(string org, string repo, bool skipReleases, bool lockSource)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/migrations";
var options = new
{
repositories = new[] { repo },
exclude_git_data = true,
exclude_releases = skipReleases,
lock_repositories = lockSource,
exclude_owner_projects = true
};
var response = await _client.PostAsync(url, options);
var data = JObject.Parse(response);
return (int)data["id"];
}
public virtual async Task<string> GetArchiveMigrationStatus(string org, int archiveId)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/migrations/{archiveId}";
var response = await _client.GetAsync(url);
var data = JObject.Parse(response);
return (string)data["state"];
}
public virtual async Task<string> GetArchiveMigrationUrl(string org, int archiveId)
{
var url = $"{_apiUrl}/orgs/{org.EscapeDataString()}/migrations/{archiveId}/archive";
var response = await _client.GetNonSuccessAsync(url, HttpStatusCode.Found);
return response;
}
public virtual async Task<IEnumerable<Mannequin>> GetMannequins(string orgId)
{
var url = $"{_apiUrl}/graphql";
var payload = GetMannequinsPayload(orgId);
try
{
return await _retryPolicy.Retry(async () =>
{
return await _client.PostGraphQLWithPaginationAsync(
url,
payload,
data => (JArray)data["data"]["node"]["mannequins"]["nodes"],
data => (JObject)data["data"]["node"]["mannequins"]["pageInfo"])
.Select(mannequin => BuildMannequin(mannequin))
.ToListAsync();
});
}
catch (Exception ex)
{
throw new OctoshiftCliException($"Failed to retrieve the list of mannequins", ex);
}
}
public virtual async Task<IEnumerable<Mannequin>> GetMannequinsByLogin(string orgId, string login)
{
var url = $"{_apiUrl}/graphql";
var payload = GetMannequinsByLoginPayload(orgId, login);
return await _retryPolicy.Retry(async () =>
{
return await _client.PostGraphQLWithPaginationAsync(
url,
payload,
data => (JArray)data["data"]["node"]["mannequins"]["nodes"],
data => (JObject)data["data"]["node"]["mannequins"]["pageInfo"])
.Select(mannequin => BuildMannequin(mannequin))
.ToListAsync();
});
}
public virtual async Task<string> GetUserId(string login)
{
var url = $"{_apiUrl}/graphql";
var payload = new
{
query = "query($login: String!) {user(login: $login) { id, name } }",
variables = new { login }
};
// TODO: Add retry logic here, but need to inspect the actual error message and differentiate between transient failure vs user doesn't exist (only retry on failure)
var data = await _client.PostGraphQLAsync(url, payload);
return (string)data["data"]["user"]["id"];
}
public virtual async Task<CreateAttributionInvitationResult> CreateAttributionInvitation(string orgId, string mannequinId, string targetUserId)
{
var url = $"{_apiUrl}/graphql";
var mutation = "mutation($orgId: ID!,$sourceId: ID!,$targetId: ID!)";
var gql = @"
createAttributionInvitation(
input: { ownerId: $orgId, sourceId: $sourceId, targetId: $targetId }
) {
source {
... on Mannequin {
id
login
}
}
target {
... on User {
id
login
}
}
}";
var payload = new
{
query = $"{mutation} {{ {gql} }}",
variables = new { orgId, sourceId = mannequinId, targetId = targetUserId }
};
var response = await _client.PostAsync(url, payload);
var data = JObject.Parse(response);
return data.ToObject<CreateAttributionInvitationResult>();
}
public virtual async Task<ReattributeMannequinToUserResult> ReclaimMannequinSkipInvitation(string orgId, string mannequinId, string targetUserId)
{
var url = $"{_apiUrl}/graphql";
var mutation = "mutation($orgId: ID!,$sourceId: ID!,$targetId: ID!)";
var gql = @"
reattributeMannequinToUser(
input: { ownerId: $orgId, sourceId: $sourceId, targetId: $targetId }
) {
source {
... on Mannequin {
id
login
}
}
target {
... on User {
id
login
}
}
}";
var payload = new
{
query = $"{mutation} {{ {gql} }}",
variables = new { orgId, sourceId = mannequinId, targetId = targetUserId }
};
try
{
return await _retryPolicy.Retry(async () =>
{
var data = await _client.PostGraphQLAsync(url, payload);
return data.ToObject<ReattributeMannequinToUserResult>();
});
}
catch (OctoshiftCliException ex) when (ex.Message.Contains("Field 'reattributeMannequinToUser' doesn't exist on type 'Mutation'"))
{
throw new OctoshiftCliException($"Reclaiming mannequins with the--skip - invitation flag is not enabled for your GitHub organization.For more details, contact GitHub Support.", ex);
}
}
public virtual async Task<IEnumerable<GithubSecretScanningAlert>> GetSecretScanningAlertsForRepository(string org, string repo)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/secret-scanning/alerts?per_page=100";
return await _client.GetAllAsync(url)
.Select(secretAlert => BuildSecretScanningAlert(secretAlert))
.ToListAsync();
}
public virtual async Task<IEnumerable<GithubSecretScanningAlertLocation>> GetSecretScanningAlertsLocations(string org, string repo, int alertNumber)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/secret-scanning/alerts/{alertNumber}/locations?per_page=100";
return await _client.GetAllAsync(url)
.Select(alertLocation => BuildSecretScanningAlertLocation(alertLocation))
.ToListAsync();
}
public virtual async Task UpdateSecretScanningAlert(string org, string repo, int alertNumber, string state, string resolution = null)
{
if (!SecretScanningAlert.IsOpenOrResolved(state))
{
throw new ArgumentException($"Invalid value for {nameof(state)}");
}
if (SecretScanningAlert.IsResolved(state) && !SecretScanningAlert.IsValidDismissedReason(resolution))
{
throw new ArgumentException($"Invalid value for {nameof(resolution)}");
}
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/secret-scanning/alerts/{alertNumber}";
object payload = state == SecretScanningAlert.AlertStateOpen ? new { state } : new { state, resolution };
await _client.PatchAsync(url, payload);
}
public virtual async Task<IEnumerable<CodeScanningAnalysis>> GetCodeScanningAnalysisForRepository(string org, string repo, string branch = null)
{
var queryString = "per_page=100&sort=created&direction=asc";
if (branch.HasValue())
{
queryString += $"&ref={branch.EscapeDataString()}";
}
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/code-scanning/analyses?{queryString}";
try
{
return await _client.GetAllAsync(url)
.Select(BuildCodeScanningAnalysis)
.ToListAsync();
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound && ex.Message.Contains("no analysis found"))
{
return Enumerable.Empty<CodeScanningAnalysis>();
}
}
public virtual async Task UpdateCodeScanningAlert(string org, string repo, int alertNumber, string state, string dismissedReason = null, string dismissedComment = null)
{
if (!CodeScanningAlertState.IsOpenOrDismissed(state))
{
throw new ArgumentException($"Invalid value for {nameof(state)}");
}
if (CodeScanningAlertState.IsDismissed(state) && !CodeScanningAlertState.IsValidDismissedReason(dismissedReason))
{
throw new ArgumentException($"Invalid value for {nameof(dismissedReason)}");
}
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/code-scanning/alerts/{alertNumber}";
var payload = state == "open"
? (new { state })
: (object)(new
{
state,
dismissed_reason = dismissedReason,
dismissed_comment = dismissedComment ?? string.Empty
});
await _client.PatchAsync(url, payload);
}
public virtual async Task<string> GetSarifReport(string org, string repo, int analysisId)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/code-scanning/analyses/{analysisId}";
// Need change the Accept header to application/sarif+json otherwise it will just be the analysis record
var headers = new Dictionary<string, string>() { { "accept", "application/sarif+json" } };
return await _client.GetAsync(url, headers);
}
public virtual async Task<string> UploadSarifReport(string org, string repo, string sarifReport, string commitSha, string sarifRef)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/code-scanning/sarifs";
var payload = new
{
commit_sha = commitSha,
sarif = StringCompressor.GZipAndBase64String(sarifReport),
@ref = sarifRef
};
var response = await _retryPolicy.HttpRetry(async () => await _client.PostAsync(url, payload),
ex => ex.StatusCode == HttpStatusCode.BadGateway);
var data = JObject.Parse(response);
return (string)data["id"];
}
public virtual async Task<SarifProcessingStatus> GetSarifProcessingStatus(string org, string repo, string sarifId)
{
var url = $"{_apiUrl}/repos/{org.EscapeDataString()}/{repo.EscapeDataString()}/code-scanning/sarifs/{sarifId.EscapeDataString()}";
var response = await _client.GetAsync(url);
var data = JObject.Parse(response);
var errors = data["errors"]?.ToObject<string[]>() ?? Array.Empty<string>();
return new() { Status = (string)data["processing_status"], Errors = errors };
}
public virtual async Task<string> GetDefaultBranch(string org, string repo)