forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.py
2170 lines (2008 loc) · 74.7 KB
/
github.py
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
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""GitHub source module responsible to fetch documents from GitHub Cloud and Server."""
import json
import time
from enum import Enum
from functools import cached_property, partial
import aiohttp
import fastjsonschema
from aiohttp.client_exceptions import ClientResponseError
from gidgethub import QueryError, RateLimitExceeded, sansio
from gidgethub.abc import (
BadGraphQLRequest,
GraphQLAuthorizationFailure,
)
from gidgethub.aiohttp import GitHubAPI
from gidgethub.apps import get_installation_access_token, get_jwt
from connectors.access_control import (
ACCESS_CONTROL,
es_access_control_query,
prefix_identity,
)
from connectors.filtering.validation import (
AdvancedRulesValidator,
SyncRuleValidationResult,
)
from connectors.logger import logger
from connectors.source import BaseDataSource, ConfigurableFieldValueError
from connectors.utils import (
CancellableSleeps,
RetryStrategy,
decode_base64_value,
nested_get_from_dict,
retryable,
ssl_context,
)
WILDCARD = "*"
BLOB = "blob"
GITHUB_CLOUD = "github_cloud"
GITHUB_SERVER = "github_server"
PERSONAL_ACCESS_TOKEN = "personal_access_token" # noqa: S105
GITHUB_APP = "github_app"
PULL_REQUEST_OBJECT = "pullRequest"
REPOSITORY_OBJECT = "repository"
RETRIES = 3
RETRY_INTERVAL = 2
FORBIDDEN = 403
UNAUTHORIZED = 401
NODE_SIZE = 100
REVIEWS_COUNT = 45
SUPPORTED_EXTENSION = [".markdown", ".md", ".rst"]
FILE_SCHEMA = {
"name": "name",
"size": "size",
"type": "type",
"path": "path",
"mode": "mode",
"extension": "extension",
"_timestamp": "_timestamp",
}
def _prefix_email(email):
return prefix_identity("email", email)
def _prefix_username(user):
return prefix_identity("username", user)
def _prefix_user_id(user_id):
return prefix_identity("user_id", user_id)
class GithubQuery(Enum):
USER_QUERY = """
query {
viewer {
login
}
}
"""
REPOS_QUERY = f"""
query ($login: String!, $cursor: String) {{
user(login: $login) {{
repositories(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
updatedAt
name
nameWithOwner
url
description
visibility
primaryLanguage {{
name
}}
defaultBranchRef {{
name
}}
isFork
stargazerCount
watchers {{
totalCount
}}
forkCount
createdAt
isArchived
}}
}}
}}
}}
"""
ORG_REPOS_QUERY = f"""
query ($orgName: String!, $cursor: String) {{
organization(login: $orgName) {{
repositories(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
updatedAt
name
nameWithOwner
url
description
visibility
primaryLanguage {{
name
}}
defaultBranchRef {{
name
}}
isFork
stargazerCount
watchers {{
totalCount
}}
forkCount
createdAt
isArchived
}}
}}
}}
}}
"""
REPO_QUERY = """
query ($owner: String!, $repositoryName: String!) {
repository(owner: $owner, name: $repositoryName) {
id
updatedAt
name
nameWithOwner
url
description
visibility
primaryLanguage {
name
}
defaultBranchRef {
name
}
isFork
stargazerCount
watchers {
totalCount
}
forkCount
createdAt
isArchived
}
}
"""
PULL_REQUEST_QUERY = f"""
query ($owner: String!, $name: String!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
pullRequests(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
updatedAt
number
url
createdAt
closedAt
title
body
state
mergedAt
author {{
login
}}
assignees(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
login
}}
}}
labels(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
description
}}
}}
reviewRequests(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
requestedReviewer {{
... on User {{
login
}}
}}
}}
}}
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
author {{
login
}}
body
}}
}}
reviews(first: {REVIEWS_COUNT}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
author {{
login
}}
state
body
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
body
}}
}}
}}
}}
}}
}}
}}
}}
"""
ISSUE_QUERY = f"""
query ($owner: String!, $name: String!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
issues(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
updatedAt
number
url
createdAt
closedAt
title
body
state
author {{
login
}}
assignees(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
login
}}
}}
labels(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
description
}}
}}
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
author {{
login
}}
body
}}
}}
}}
}}
}}
}}
"""
COMMENT_QUERY = """
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
{object_type}(number: $number) {{
comments(first: {node_size}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
author {{
login
}}
body
}}
}}
}}
}}
}}
"""
REVIEW_QUERY = f"""
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
pullRequest(number: $number) {{
reviews(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
author {{
login
}}
state
body
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
body
}}
}}
}}
}}
}}
}}
}}
"""
REVIEWERS_QUERY = f"""
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
pullRequest(number: $number) {{
reviewRequests(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
requestedReviewer {{
... on User {{
login
}}
}}
}}
}}
}}
}}
}}
"""
LABELS_QUERY = """
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
{object_type}(number: $number) {{
labels(first: {node_size}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
}}
}}
}}
}}
}}
"""
ASSIGNEES_QUERY = """
query ($owner: String!, $name: String!, $number: Int!, $cursor: String) {{
repository(owner: $owner, name: $name) {{
{object_type}(number: $number) {{
assignees(first: {node_size}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
login
}}
}}
}}
}}
}}
"""
SEARCH_QUERY = f"""
query ($filter_query: String!, $cursor: String) {{
search(query: $filter_query, type: ISSUE, first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
... on Issue {{
id
updatedAt
number
url
createdAt
closedAt
title
body
state
assignees(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
login
}}
}}
labels(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
description
}}
}}
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
author {{
login
}}
body
}}
}}
}}
... on PullRequest {{
id
updatedAt
number
url
createdAt
closedAt
title
body
state
mergedAt
assignees(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
login
}}
}}
labels(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
name
description
}}
}}
reviewRequests(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
requestedReviewer {{
... on User {{
login
}}
}}
}}
}}
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
author {{
login
}}
body
}}
}}
reviews(first: {REVIEWS_COUNT}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
id
author {{
login
}}
state
body
comments(first: {NODE_SIZE}) {{
pageInfo {{
hasNextPage
endCursor
}}
nodes {{
body
}}
}}
}}
}}
}}
}}
}}
}}
"""
ORG_MEMBERS_QUERY = f"""
query ($orgName: String!, $cursor: String) {{
organization(login: $orgName) {{
membersWithRole(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
edges {{
node {{
id
login
name
email
updatedAt
}}
}}
}}
}}
}}
"""
COLLABORATORS_QUERY = f"""
query ($orgName: String!, $repoName: String!, $cursor: String) {{
repository(owner: $orgName, name: $repoName) {{
collaborators(first: {NODE_SIZE}, after: $cursor) {{
pageInfo {{
hasNextPage
endCursor
}}
edges {{
node {{
id
login
email
}}
}}
}}
}}
}}
"""
class ObjectType(Enum):
REPOSITORY = "Repository"
ISSUE = "Issue"
PULL_REQUEST = "Pull request"
PR = "pr"
BRANCH = "branch"
class UnauthorizedException(Exception):
pass
class NoInstallationAccessTokenException(Exception):
pass
class ForbiddenException(Exception):
pass
class GitHubClient:
def __init__(
self, auth_method, base_url, app_id, private_key, token, ssl_enabled, ssl_ca
):
self._sleeps = CancellableSleeps()
self._logger = logger
self.auth_method = auth_method
self.base_url = base_url
self.app_id = app_id if self.auth_method == GITHUB_APP else None
self.private_key = private_key if self.auth_method == GITHUB_APP else None
self._personal_access_token = (
token if self.auth_method == PERSONAL_ACCESS_TOKEN else None
)
self._installation_access_token = None
if self.base_url == "https://api.github.com":
self.endpoints = {
"TREE": "/repos/{repo_name}/git/trees/{default_branch}?recursive=1",
"COMMITS": "/repos/{repo_name}/commits?path={path}",
}
else:
self.endpoints = {
"TREE": "/api/v3/repos/{repo_name}/git/trees/{default_branch}?recursive=1",
"COMMITS": "api/v3/repos/{repo_name}/commits?path={path}",
}
if ssl_enabled and ssl_ca:
self.ssl_ctx = ssl_context(certificate=ssl_ca)
else:
self.ssl_ctx = False
# a variable to hold the current installation id, used to refresh the access token
self._installation_id = None
def set_logger(self, logger_):
self._logger = logger_
def get_rate_limit_encountered(self, status_code, rate_limit_remaining):
return status_code == FORBIDDEN and not int(rate_limit_remaining)
async def _get_retry_after(self, resource_type):
current_time = time.time()
response = await self.get_github_item("/rate_limit")
reset = nested_get_from_dict(
response, ["resources", resource_type, "reset"], default=current_time
)
# Adding a 5 second delay to account for server delays
return (reset - current_time) + 5 # pyright: ignore
async def _put_to_sleep(self, resource_type):
retry_after = await self._get_retry_after(resource_type=resource_type)
self._logger.debug(
f"Connector will attempt to retry after {retry_after} seconds."
)
await self._sleeps.sleep(retry_after)
msg = "Rate limit exceeded."
raise Exception(msg)
def _access_token(self):
if self.auth_method == PERSONAL_ACCESS_TOKEN:
return self._personal_access_token
if not self._installation_access_token:
raise NoInstallationAccessTokenException
return self._installation_access_token
# update the current installation id and re-generate access token
async def update_installation_id(self, installation_id):
self._logger.debug(
f"Updating installation id - new ID: {installation_id}, original ID: {self._installation_id}"
)
self._installation_id = installation_id
await self._update_installation_access_token()
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
)
async def _update_installation_access_token(self):
try:
access_token_response = await get_installation_access_token(
gh=self._get_client,
installation_id=self._installation_id,
app_id=self.app_id,
private_key=self.private_key,
)
self._installation_access_token = access_token_response["token"]
except RateLimitExceeded:
await self._put_to_sleep("core")
except Exception:
self._logger.exception(
f"Failed to get access token for installation {self._installation_id}.",
exc_info=True,
)
raise
@cached_property
def _get_session(self):
connector = aiohttp.TCPConnector(ssl=self.ssl_ctx)
timeout = aiohttp.ClientTimeout(total=None)
return aiohttp.ClientSession(
timeout=timeout,
raise_for_status=True,
connector=connector,
)
@cached_property
def _get_client(self):
return GitHubAPI(
session=self._get_session,
requester="",
base_url=self.base_url,
)
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
skipped_exceptions=UnauthorizedException,
)
async def graphql(self, query, variables=None):
"""Invoke GraphQL request to fetch repositories, pull requests, and issues.
Args:
query: Dictionary comprising of query for the GraphQL request.
variables: Dictionary comprising of query for the GraphQL request.
Raises:
UnauthorizedException: Unauthorized exception
exception: An instance of an exception class.
Yields:
dictionary: Client response
"""
url = f"{self.base_url}/graphql"
self._logger.debug(
f"Sending POST to {url} with query: '{json.dumps(query)}' and variables: '{json.dumps(variables)}'"
)
try:
self._get_client.oauth_token = self._access_token()
return await self._get_client.graphql(
query=query, endpoint=url, **variables or {}
)
except GraphQLAuthorizationFailure as exception:
if self.auth_method == GITHUB_APP:
self._logger.debug(
f"The access token for installation #{self._installation_id} expired, Regenerating a new token."
)
await self._update_installation_access_token()
raise
msg = "Your Github token is either expired or revoked. Please check again."
raise UnauthorizedException(msg) from exception
except BadGraphQLRequest as exception:
if exception.status_code == FORBIDDEN:
msg = f"Provided GitHub token does not have the necessary permissions to perform the request for the URL: {url} and query: {query}."
raise ForbiddenException(msg) from exception
else:
raise
except QueryError as exception:
for error in exception.response.get("errors"):
if (
error.get("type").lower() == "rate_limited"
and "api rate limit exceeded" in error.get("message").lower()
):
await self._put_to_sleep(resource_type="graphql")
msg = f"Error while executing query. Exception: {exception.response.get('errors')}"
raise Exception(msg) from exception
except Exception:
raise
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
skipped_exceptions=UnauthorizedException,
)
async def get_github_item(self, resource):
"""Execute request using getitem method of GitHubAPI which is using REST API.
Using Rest API for fetching files and folder along with content.
Args:
resource (str): API to get the response
Returns:
dict/list: Response of the request
"""
self._logger.debug(f"Getting github item: {resource}")
try:
return await self._get_client.getitem(
url=resource, oauth_token=self._access_token()
)
except ClientResponseError as exception:
if exception.status == UNAUTHORIZED:
if self.auth_method == GITHUB_APP:
self._logger.debug(
f"The access token for installation #{self._installation_id} expired, Regenerating a new token."
)
await self._update_installation_access_token()
raise
msg = "Your Github token is either expired or revoked. Please check again."
raise UnauthorizedException(msg) from exception
elif self.get_rate_limit_encountered(
exception.status, exception.headers.get("X-RateLimit-Remaining")
):
await self._put_to_sleep(resource_type="core")
elif exception.status == FORBIDDEN:
msg = f"Provided GitHub token does not have the necessary permissions to perform the request for the URL: {resource}."
raise ForbiddenException(msg) from exception
else:
raise
except RateLimitExceeded:
await self._put_to_sleep("core")
except Exception:
raise
async def paginated_api_call(self, query, variables, keys):
"""Make a paginated API call for fetching GitHub objects.
Args:
query (string): Graphql Query
variables (dict): Variables for Graphql API
keys (list): List of fields to get pageInfo
Yields:
dict: dictionary containing response of GitHub.
"""
while True:
response = await self.graphql(query=query, variables=variables)
yield response
page_info = nested_get_from_dict(response, keys + ["pageInfo"], default={})
if not page_info.get("hasNextPage"):
break
variables["cursor"] = page_info["endCursor"] # pyright: ignore
def get_repo_details(self, repo_name):
return repo_name.split("/")
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
skipped_exceptions=UnauthorizedException,
)
async def get_personal_access_token_scopes(self):
try:
request_headers = sansio.create_headers(
self._get_client.requester,
accept=sansio.accept_format(),
oauth_token=self._access_token(),
)
url = f"{self.base_url}/graphql"
_, headers, _ = await self._get_client._request(
"HEAD", url, request_headers
)
scopes = headers.get("X-OAuth-Scopes")
if not scopes or not scopes.strip():
self._logger.warning(
f"Couldn't find 'X-OAuth-Scopes' in headers {headers}"
)
return set()
return {scope.strip() for scope in scopes.split(",")}
except ClientResponseError as exception:
if exception.status == FORBIDDEN:
if self.get_rate_limit_encountered(
exception.status, exception.headers.get("X-RateLimit-Remaining")
):
await self._put_to_sleep("graphql")
else:
msg = f"Provided GitHub token does not have the necessary permissions to perform the request for the URL: {self.base_url}."
raise ForbiddenException(msg) from exception
elif exception.status == UNAUTHORIZED:
msg = "Your Github token is either expired or revoked. Please check again."
raise UnauthorizedException(msg) from exception
else:
raise
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
)
async def _github_app_get(self, url):
self._logger.debug(f"Making a get request to GitHub: {url}")
try:
return await self._get_client._make_request(
"GET",
url,
{},
b"",
sansio.accept_format(),
get_jwt(app_id=self.app_id, private_key=self.private_key),
)
# we don't expect any 401 error as the jwt is freshly generated
except RateLimitExceeded:
await self._put_to_sleep("core")
except Exception:
raise
async def _github_app_paginated_get(self, url):
data, more = await self._github_app_get(url) # pyright: ignore
if data:
for item in data:
yield item
if more:
async for item in self._github_app_paginated_get(more): # pyright: ignore
yield item
async def get_installations(self):
async for installation in self._github_app_paginated_get(
url="/app/installations"
):
if installation["suspended_at"]:
self._logger.debug(
f"Skip installation '{installation['id']}' because it's suspended."
)
continue
yield installation
async def get_org_repos(self, org_name):
repo_variables = {
"orgName": org_name,
"cursor": None,
}
async for response in self.paginated_api_call(
query=GithubQuery.ORG_REPOS_QUERY.value,
variables=repo_variables,
keys=["organization", "repositories"],
):
for repo in nested_get_from_dict( # pyright: ignore
response, ["organization", "repositories", "nodes"], default=[]
):
yield repo
async def get_user_repos(self, user):
repo_variables = {
"login": user,
"cursor": None,
}
async for response in self.paginated_api_call(
query=GithubQuery.REPOS_QUERY.value,
variables=repo_variables,
keys=["user", "repositories"],
):
for repo in nested_get_from_dict( # pyright: ignore
response, ["user", "repositories", "nodes"], default=[]
):
yield repo
async def get_foreign_repo(self, repo_name):
owner, repo = self.get_repo_details(repo_name=repo_name)
repo_variables = {"owner": owner, "repositoryName": repo}
data = await self.graphql(
query=GithubQuery.REPO_QUERY.value, variables=repo_variables
)
return data.get(REPOSITORY_OBJECT)
async def _fetch_all_members(self, org_name):
org_variables = {
"orgName": org_name,
"cursor": None,