forked from FORCOLAB-UofT/GitHubAPI-Crawler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub_api.py
1301 lines (1111 loc) · 45.7 KB
/
github_api.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
import time
from datetime import datetime
import json
from typing import Iterable
from random import randint
import os.path
from util import language_tool
import fetch_raw_diff
import logging
import os.path
import init
from fetch_raw_diff import *
from util import localfile
# try:
# import settings
# except ImportError:
# settings = object()
# _tokens = getattr(settings, "SCRAPER_GITHUB_API_TOKENS", [])
with open(init.currentDIR+"/data/token.txt", 'r') as file:
_tokens = [line.rstrip('\n') for line in file]
logger = logging.getLogger('ghd.scraper')
LOCAL_DATA_PATH = init.LOCAL_DATA_PATH
file_list_cache = {}
logger = logging.getLogger('INTRUDE.scraper')
# nonCodeFileExtensionList = [line.rstrip('\n') for line in open('./data/NonCodeFile.txt')]
nonCodeFileExtensionList = [line.rstrip('\n') for line in open(init.currentDIR+'/data/NonCodeFile.txt')]
class RepoDoesNotExist(requests.HTTPError):
pass
class TokenNotReady(requests.HTTPError):
pass
def parse_commit(commit):
github_author = commit['author'] or {}
commit_author = commit['commit'].get('author') or {}
return {
'sha': commit['sha'],
'author': github_author.get('login'),
'author_name': commit_author.get('name'),
'author_email': commit_author.get('email'),
'authored_date': commit_author.get('date'),
'message': commit['commit']['message'].replace("\n", ","),
'committed_date': commit['commit']['committer']['date'],
'parents': "\n".join(p['sha'] for p in commit['parents']),
'verified': commit.get('verification', {}).get('verified')
}
class GitHubAPIToken(object):
api_url = "https://api.github.com/"
token = None
timeout = None
_user = None
_headers = None
limit = None # see __init__ for more details
def __init__(self, token=None, timeout=None):
if token is not None:
self.token = token
self._headers = {
"Authorization": "token " + token,
# "Accept": "application/vnd.github.v3+json",
"Accept": "application/vnd.github.mockingbird-preview"
# "User-Agent": "request"
}
self.limit = {}
for api_class in ('core', 'search'):
self.limit[api_class] = {
'limit': None,
'remaining': None,
'reset_time': None
}
self.timeout = timeout
super(GitHubAPIToken, self).__init__()
@property
def user(self):
if self._user is None:
try:
r = self.request('user')
except TokenNotReady:
pass
else:
self._user = r.json().get('login', '')
return self._user
def _check_limits(self):
# regular limits will be updaated automatically upon request
# we only need to take care about search limit
try:
s = self.request('rate_limit').json()['resources']['search']
except TokenNotReady:
# self.request updated core limits already; search limits unknown
s = {'remaining': None, 'reset': None, 'limit': None}
self.limit['search'] = {
'remaining': s['remaining'],
'reset_time': s['reset'],
'limit': s['limit']
}
@staticmethod
def api_class(url):
return 'search' if url.startswith('search') else 'core'
def ready(self, url):
t = self.when(url)
return not t or t <= time.time()
def legit(self):
if self.limit['core']['limit'] is None:
self._check_limits()
return self.limit['core']['limit'] < 100
def when(self, url):
key = self.api_class(url)
if self.limit[key]['remaining'] != 0:
return 0
return self.limit[key]['reset_time']
def request(self, url, method='get', data=None, **params):
# TODO: use coroutines, perhaps Tornado (as PY2/3 compatible)
if not self.ready(url):
raise TokenNotReady
# Exact API version can be specified by Accept header:
# "Accept": "application/vnd.github.v3+json"}
# might throw a timeout
r = requests.request(
method, self.api_url + url, params=params, data=data,
headers=self._headers, timeout=self.timeout)
if 'X-RateLimit-Remaining' in r.headers:
remaining = int(r.headers['X-RateLimit-Remaining'])
self.limit[self.api_class(url)] = {
'remaining': remaining,
'reset_time': int(r.headers['X-RateLimit-Reset']),
'limit': int(r.headers['X-RateLimit-Limit'])
}
if r.status_code == 403 and remaining == 0:
raise TokenNotReady
if r.status_code == 443:
print('443 error')
raise TokenNotReady
return r
class GitHubAPI(object):
""" This is a convenience class to pool GitHub API keys and update their
limits after every request. Actual work is done by outside classes, such
as _IssueIterator and _CommitIterator
"""
_instance = None # instance of API() for Singleton pattern implementation
tokens = None
def __new__(cls, *args, **kwargs): # Singleton
if not isinstance(cls._instance, cls):
cls._instance = super(GitHubAPI, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, tokens=_tokens, timeout=30):
if not tokens:
raise EnvironmentError(
"No GitHub API tokens found in settings.py. Please add some.")
self.tokens = [GitHubAPIToken(t, timeout=timeout) for t in tokens]
def requestPR(self, url, method='get', page=1, data=None, **params):
# type: (str, str, bool, str) -> dict
""" Generic, API version agnostic request method """
timeout_counter = 0
params['page'] = page
params['per_page'] = init.numPRperPage
while True:
for token in self.tokens:
# for token in sorted(self.tokens, key=lambda t: t.when(url)):
if not token.ready(url):
continue
try:
r = token.request(url, method=method, data=data, **params)
# print(r.url)
except requests.ConnectionError:
print('except requests.ConnectionError')
continue
except TokenNotReady:
continue
except requests.exceptions.Timeout:
timeout_counter += 1
if timeout_counter > len(self.tokens):
raise
continue # i.e. try again
if r.status_code in (404, 451):
print("404, 451 retry..")
return {}
# API v3 only
# raise RepoDoesNotExist(
# "GH API returned status %s" % r.status_code)
elif r.status_code == 409:
print("409 retry..")
# repository is empty https://developer.github.com/v3/git/
return {}
elif r.status_code == 410:
print("410 retry..")
# repository is empty https://developer.github.com/v3/git/
return {}
elif r.status_code == 401:
print("401,Bad credentials, please remove this token")
continue
elif r.status_code == 403:
# repository is empty https://developer.github.com/v3/git/
print("403 retry..")
time.sleep(randint(1, 60))
continue
elif r.status_code == 443:
# repository is empty https://developer.github.com/v3/git/
print("443 retry..")
time.sleep(randint(1, 29))
continue
elif r.status_code == 502:
# repository is empty https://developer.github.com/v3/git/
print("443 retry..")
time.sleep(randint(1, 29))
continue
r.raise_for_status()
res = r.json()
return res
next_res = min(token.when(url) for token in self.tokens)
sleep = int(next_res - time.time()) + 1
if sleep > 0:
logger.info(
"%s: out of keys, resuming in %d minutes, %d seconds",
datetime.now().strftime("%H:%M"), *divmod(sleep, 60))
time.sleep(sleep)
logger.info(".. resumed")
def request(self, url, method='get', paginate=False, data=None, **params):
# type: (str, str, bool, str) -> dict
""" Generic, API version agnostic request method """
timeout_counter = 0
if paginate:
paginated_res = []
params['page'] = 1
params['per_page'] = 100
while True:
for token in self.tokens:
# for token in sorted(self.tokens, key=lambda t: t.when(url)):
if not token.ready(url):
continue
try:
r = token.request(url, method=method, data=data, **params)
# print(r.url)
except requests.ConnectionError:
print('except requests.ConnectionError')
continue
except TokenNotReady:
continue
except requests.exceptions.Timeout:
timeout_counter += 1
if timeout_counter > len(self.tokens):
raise
continue # i.e. try again
if r.status_code in (404, 451):
print("404, 451 retry..")
return {}
# API v3 only
# raise RepoDoesNotExist(
# "GH API returned status %s" % r.status_code)
elif r.status_code == 409:
print("409 retry..")
# repository is empty https://developer.github.com/v3/git/
return {}
elif r.status_code == 410:
print("410 retry..")
# repository is empty https://developer.github.com/v3/git/
return {}
elif r.status_code == 401:
print("401,Bad credentials, please remove this token")
continue
elif r.status_code == 403:
# repository is empty https://developer.github.com/v3/git/
print("403 retry..")
time.sleep(randint(1, 60))
continue
elif r.status_code == 443:
# repository is empty https://developer.github.com/v3/git/
print("443 retry..")
time.sleep(randint(1, 29))
continue
elif r.status_code == 502:
# repository is empty https://developer.github.com/v3/git/
print("502 retry..")
time.sleep(randint(1, 29))
continue
elif r.status_code == 500:
# repository is empty https://developer.github.com/v3/git/
print("500 retry..")
time.sleep(randint(1, 29))
continue
r.raise_for_status()
res = r.json()
if paginate:
paginated_res.extend(res)
has_next = 'rel="next"' in r.headers.get("Link", "")
if not res or not has_next:
return paginated_res
else:
params["page"] += 1
continue
else:
return res
next_res = min(token.when(url) for token in self.tokens)
sleep = int(next_res - time.time()) + 1
if sleep > 0:
logger.info(
"%s: out of keys, resuming in %d minutes, %d seconds",
datetime.now().strftime("%H:%M"), *divmod(sleep, 60))
time.sleep(sleep)
logger.info(".. resumed")
def repo_issues(self, repo_name, page=None):
# type: (str, int) -> Iterable[dict]
url = "repos/%s/issues" % repo_name
if page is None:
data = self.request(url, paginate=True, state='all')
else:
data = self.request(url, page=page, per_page=100, state='all')
for issue in data:
if 'pull_request' not in issue:
yield {
'author': issue['user']['login'],
'closed': issue['state'] != "open",
'created_at': issue['created_at'],
'updated_at': issue['updated_at'],
'closed_at': issue['closed_at'],
'number': issue['number'],
'title': issue['title']
}
def repo_commits(self, repo_name):
url = "repos/%s/commits" % repo_name
for commit in self.request(url, paginate=True):
# might be None for commits authored outside of github
yield parse_commit(commit)
url = "repos/%s/pulls" % repo_name
for pr in self.request(url, paginate=True, state='all'):
body = pr.get('body', {})
head = pr.get('head', {})
head_repo = head.get('repo') or {}
base = pr.get('base', {})
base_repo = base.get('repo') or {}
yield {
'id': int(pr['number']), # no idea what is in the id field
'title': pr['title'],
'body': body,
'labels': 'labels' in pr and [l['name'] for l in pr['labels']],
'created_at': pr['created_at'],
'updated_at': pr['updated_at'],
'closed_at': pr['closed_at'],
'merged_at': pr['merged_at'],
'author': pr['user']['login'],
'head': head_repo.get('full_name'),
'head_branch': head.get('label'),
'base': base_repo.get('full_name'),
'base_branch': base.get('label'),
}
def pr_status(self, repo, pr_id):
url = "repos/%s/pulls/%s" % (repo, pr_id)
pr = self.request(url)
return pr['state']
def pull_request_commits(self, repo, pr_id):
# type: (str, int) -> Iterable[dict]
url = "repos/%s/pulls/%d/commits" % (repo, pr_id)
for commit in self.request(url, paginate=True, state='all'):
yield parse_commit(commit)
def issue_comments(self, repo, issue_id):
""" Return comments on an issue or a pull request
Note that for pull requests this method will return only general
comments to the pull request, but not review comments related to
some code. Use review_comments() to get those instead
:param repo: str 'owner/repo'
:param issue_id: int, either an issue or a Pull Request id
"""
url = "repos/%s/issues/%s/comments" % (repo, issue_id)
for comment in self.request(url, paginate=True, state='all'):
yield {
'body': comment['body'],
'author': comment['user']['login'],
'created_at': comment['created_at'],
'updated_at': comment['updated_at'],
}
def get_issue_pr_timeline(self, repo, issue_id):
""" Return timeline on an issue or a pull request
:param repo: str 'owner/repo'url
:param issue_id: int, either an issue or a Pull Request id
"""
url = "repos/%s/issues/%s/timeline" % (repo, issue_id)
# print(url)
events = self.request(url, paginate=True, state='all')
return events
def issue_pr_timeline(self, repo, issue_id):
""" Return timeline on an issue or a pull request
:param repo: str 'owner/repo'url
:param issue_id: int, either an issue or a Pull Request id
"""
url = "repos/%s/issues/%s/timeline" % (repo, issue_id)
events = self.request(url, paginate=True, state='all')
for event in events:
# print('repo: ' + repo + ' issue: ' + str(issue_id) + ' event: ' + event['event'])
if event['event'] == 'cross-referenced':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': "",
'created_at': event.get('created_at'),
'id': event['source']['issue']['number'],
'repo': event['source']['issue']['repository']['full_name'],
'type': 'pull_request' if 'pull_request' in event['source']['issue'].keys() else 'issue',
'state': event['source']['issue']['state'],
'assignees': event['source']['issue']['assignees'],
'label': "",
'body': ''
}
elif event['event'] == 'referenced':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': event['commit_id'],
'created_at': event['created_at'],
'id': '',
'repo': '',
'type': 'commit',
'state': '',
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'labeled':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': '',
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "label",
'state': '',
'assignees': '',
'label': event['label']['name'],
'body': ''
}
elif event['event'] == 'committed':
yield {
'event': event['event'],
'author': event['author']['name'],
'email': event['author']['email'],
'author_type': '',
'author_association': '',
'commit_id': event['sha'],
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "commit",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'reviewed':
author = event['user'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': event['author_association'],
'commit_id': '',
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "review",
'state': event['state'],
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'commented':
yield {
'event': event['event'],
'author': event['user']['login'],
'email': '',
'author_type': event['user']['type'],
'author_association': event['author_association'],
'commit_id': '',
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "comment",
'state': '',
'assignees': '',
'label': '',
'body': event['body']
}
elif event['event'] == 'assigned':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': '',
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "comment",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'closed':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': event['commit_id'],
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "close",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'subscribed':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': event['commit_id'],
'created_at': event.get('created_at'),
'id': event['commit_id'],
'repo': '',
'type': "subscribed",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
elif event['event'] == 'merged':
author = event['actor'] or {}
yield {
'event': event['event'],
'author': author.get('login'),
'email': '',
'author_type': author.get('type'),
'author_association': '',
'commit_id': event['commit_id'],
'created_at': event.get('created_at'),
'id': event['commit_id'],
'repo': '',
'type': "merged",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
else:
yield {
'event': event['event'],
'author': '',
'email': '',
'author_type': '',
'author_association': '',
'commit_id': '',
'created_at': event.get('created_at'),
'id': '',
'repo': '',
'type': "",
'state': '',
'assignees': '',
'label': '',
'body': ''
}
def pr_changedFiles(self, repo, pr_id):
""" Return changed file list on an issue or a pull request
:param repo: str 'owner/repo'url
:param pr_id: int, Pull Request id
"""
url = "repos/%s/pulls/%s/files" % (repo, pr_id)
files = self.request(url, paginate=True, state='all')
for file in files:
# print('repo: ' + repo + ' issue: ' + str(issue_id) + ' event: ' + event['event'])
yield {
'filename': file['filename'],
'status': file['status'],
'additions': file['additions'],
'deletions': file['deletions'],
'changes': file['changes'],
'blob_url': file['blob_url'],
'raw_url': file['raw_url'],
'contents_url': file['contents_url']
}
def commit_changedFile(self, repo, sha):
""" Return changed file list on an issue or a pull request
:param repo: str 'owner/repo'url
:param sha,
"""
url = "repos/%s/commits/%s" % (repo, sha)
commitInfo = self.request(url)
files = commitInfo['files']
for file in files:
yield {
'filename': file['filename'],
'status': file['status'],
'additions': file['additions'],
'deletions': file['deletions'],
'changes': file['changes']
}
def repoLastPushDate(self, repoUrl):
url = "repos/%s" % (repoUrl)
repoInfo = self.request(url)
if (len(repoInfo) == 0):
print(repoUrl + " deleted")
return ''
else:
return repoInfo['pushed_at']
def userEmail(self, loginID):
""" Return changed file list on an issue or a pull request
:param repo: str 'owner/repo'url
:param sha,
"""
url = "users/%s" % (loginID)
userInfo = self.request(url)
if (len(userInfo) == 0):
print(loginID + " deleted")
return ''
else:
email = userInfo['email']
return email
# this function get repo by specifying constraints
def get_repo(self, language, created_date_from, created_date_to):
""" Return timeline on an issue or a pull request
:param repo: str 'owner/repo'url
:param issue_id: int, either an issue or a Pull Request id
"""
# append to repos['items'] list
# keep going through the results pages and extract ['items']
# append extracted items to original
url = 'search/repositories?q=language%3A\"'+language+'\"+created%3A'+created_date_from+'..'+created_date_to+"&s=stars"
repos = self.request(url, paginate=False)
page = 1
total_repos = min(repos['total_count'], 1000)
items_remaining = total_repos - len(repos['items'])
while items_remaining > 0:
print("Repository search results remaining: {}".format(items_remaining))
# next page
page += 1
url = 'search/repositories?q=language%3A\"'+language+'\"+created%3A'+created_date_from+'..'+created_date_to+'&s=stars'+'&page='+str(page)
repos['items'] += self.request(url, paginate=False)['items']
items_remaining = total_repos - len(repos['items'])
return repos
def review_comments(self, repo, pr_id):
""" Pull request comments attached to some code
See also issue_comments()
"""
url = "repos/%s/pulls/%s/comments" % (repo, pr_id)
for comment in self.request(url, paginate=True, state='all'):
yield {
'id': comment['id'],
'body': comment['body'],
'author': comment['user']['login'],
'created_at': comment['created_at'],
'updated_at': comment['updated_at'],
'author_association': comment['author_association']
}
def user_info(self, user):
# Docs: https://developer.github.com/v3/users/#response
return self.request("users/" + user)
def org_members(self, org):
# TODO: support pagination
return self.request("orgs/%s/members" % org)
def user_orgs(self, user):
# TODO: support pagination
return self.request("users/%s/orgs" % user)
@staticmethod
def project_exists(repo_name):
return bool(requests.head("https://github.com/" + repo_name))
@staticmethod
def canonical_url(project_url):
# type: (str) -> str
""" Normalize URL
- remove trailing .git (IMPORTANT)
- lowercase (API is insensitive to case, but will allow to deduplicate)
- prepend "github.com"
:param project_url: str, user_name/repo_name
:return: github.com/user_name/repo_name with both names normalized
>>> GitHubAPI.canonical_url("pandas-DEV/pandas")
'github.com/pandas-dev/pandas'
>>> GitHubAPI.canonical_url("http://github.com/django/django.git")
'github.com/django/django'
>>> GitHubAPI.canonical_url("https://github.com/A/B/")
'github.com/a/b/'
"""
url = project_url.lower()
for chunk in ("httpp://", "https://", "github.com"):
if url.startswith(chunk):
url = url[len(chunk):]
if url.endswith("/"):
url = url[:-1]
while url.endswith(".git"):
url = url[:-4]
return "github.com/" + url
@staticmethod
def activity(repo_name):
# type: (str) -> dict
"""Unofficial method to get top 100 contributors commits by week"""
url = "https://github.com/%s/graphs/contributors" % repo_name
headers = {
'X-Requested-With': 'XMLHttpRequest',
'Accept-Encoding': "gzip,deflate,br",
'Accept': "application/json",
'Origin': 'https://github.com',
'Referer': url,
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) "
"Gecko/20100101 Firefox/53.0",
"Host": 'github.com',
"Accept-Language": 'en-US,en;q=0.5',
"Connection": "keep-alive",
"Cache-Control": 'max-age=0',
}
cookies = requests.get(url).cookies
r = requests.get(url + "-data", cookies=cookies, headers=headers)
r.raise_for_status()
return r.json()
class GitHubAPIv4(GitHubAPI):
def v4(self, query, **params):
# type: (str) -> dict
payload = json.dumps({"query": query, "variables": params})
return self.request("graphql", 'post', data=payload)
def repo_issues(self, repo_name, cursor=None):
# type: (str, str) -> Iterable[dict]
owner, repo = repo_name.split("/")
query = """query ($owner: String!, $repo: String!, $cursor: String) {
repository(name: $repo, owner: $owner) {
hasIssuesEnabled
issues (first: 100, after: $cursor,
orderBy: {field:CREATED_AT, direction: ASC}) {
nodes {author {login}, closed, createdAt,
updatedAt, number, title}
pageInfo {endCursor, hasNextPage}
}}}"""
while True:
data = self.v4(query, owner=owner, repo=repo, cursor=cursor
)['data']['repository']
if not data: # repository is empty, deleted or moved
break
for issue in data["issues"]:
yield {
'author': issue['author']['login'],
'closed': issue['closed'],
'created_at': issue['createdAt'],
'updated_at': issue['updatedAt'],
'closed_at': None,
'number': issue['number'],
'title': issue['title']
}
cursor = data["issues"]["pageInfo"]["endCursor"]
if not data["issues"]["pageInfo"]["hasNextPage"]:
break
def repo_commits(self, repo_name, cursor=None):
# type: (str, str) -> Iterable[dict]
"""As of June 2017 GraphQL API does not allow to get commit parents
Until this issue is fixed this method is only left for a reference
Please use commits() instead"""
owner, repo = repo_name.split("/")
query = """query ($owner: String!, $repo: String!, $cursor: String) {
repository(name: $repo, owner: $owner) {
ref(qualifiedName: "master") {
target { ... on Commit {
history (first: 100, after: $cursor) {
nodes {sha:oid, author {name, email, user{login}}
message, committedDate}
pageInfo {endCursor, hasNextPage}
}}}}}}"""
while True:
data = self.v4(query, owner=owner, repo=repo, cursor=cursor
)['data']['repository']
if not data:
break
for commit in data["ref"]["target"]["history"]["nodes"]:
yield {
'sha': commit['sha'],
'author': commit['author']['user']['login'],
'author_name': commit['author']['name'],
'author_email': commit['author']['email'],
'authored_date': None,
'message': commit['message'],
'committed_date': commit['committedDate'],
'parents': None,
'verified': None
}
cursor = data["ref"]["target"]["history"]["pageInfo"]["endCursor"]
if not data["ref"]["target"]["history"]["pageInfo"]["hasNextPage"]:
break
def fetch_pr_code_info(repo, pr_id, must_in_local=False):
global file_list_cache
ind = (repo, pr_id)
if ind in file_list_cache:
return file_list_cache[ind]
path = LOCAL_DATA_PATH + '/pr_data/%s/%s' % (repo, pr_id)
# if os.path.exists(path + '/toobig.txt'):
# return []
raw_diff_path = path + '/raw_diff.json'
pull_files_path = path + '/pull_files.json'
if os.path.exists(raw_diff_path) or os.path.exists(pull_files_path):
if os.path.exists(raw_diff_path):
file_list = localfile.get_file(raw_diff_path)
elif os.path.exists(pull_files_path):
pull_files = localfile.get_file(pull_files_path)
file_list = [parse_diff(file["file_full_name"], file["changed_code"]) for file in pull_files]
else:
raise Exception('error on fetch local file %s' % path)
else:
if must_in_local:
raise Exception('not found in local')
file_list = fetch_file_list(repo, pr_id)
codeOnlyFileList = filterNonCodeFiles(file_list,path)
if len(codeOnlyFileList) > 0:
file_list_cache[ind] = codeOnlyFileList
return codeOnlyFileList
def filterNonCodeFiles(file_list, outfile_prefix):
newFileList = []
count = 0
for f in file_list:
if count > 500:
localfile.write_to_file(outfile_prefix + "/toobig.txt", '500file')
return []
if not language_tool.is_text(f['name']):
newFileList.append(f)
count +=1
return newFileList
# -------------------About Repo--------------------------------------------------------
def get_repo_PRlist(repo, type, renew):
api = GitHubAPI()
save_path = LOCAL_DATA_PATH + '/pr_data/' + repo + '/%s_list.json' % type
# todo: could be extended to analyze forks in the future
if type == 'fork':
save_path = LOCAL_DATA_PATH + '/result/' + repo + '/forks_list.json'
if (os.path.exists(save_path)) and (not renew):
print("read from local files and return")
try:
return localfile.get_file(save_path)
except:
pass
print('files does not exist in local disk, start to fetch new list for ', repo, type)
if (type == 'pull') or (type == 'issue'):
ret = api.request('repos/%s/%ss' % (repo, type), state='all', paginate=True)
else:
if type == 'branch':
type = 'branche'
ret = api.request('repos/%s/%ss' % (repo, type), True)
localfile.write_to_file(save_path, ret)
return ret
def get_repo_info_forPR_experiment(repo, type, renew):
filtered_result = []
api = GitHubAPI()
print(init.local_pr_data_dir + repo + '/pull_list.json')
save_path = LOCAL_DATA_PATH + '/pr_data/' + repo + '/pull_list.json'
if (os.path.exists(save_path)) and (not renew):
try:
return localfile.get_file(save_path)
except:
pass
def fetch_commit(url, renew=False):
api = GitHubAPI()
save_path = LOCAL_DATA_PATH + '/pr_data/%s.json' % url.replace('https://api.github.com/repos/', '')
if os.path.exists(save_path) and (not renew):
try:
return localfile.get_file(save_path)
except:
pass
c = api.request(url)
time.sleep(0.7)
file_list = []
for f in c['files']:
if 'patch' in f:
file_list.append(fetch_raw_diff.parse_diff(f['filename'], f['patch']))