forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_changelog.py
executable file
·1393 lines (1144 loc) · 51.4 KB
/
generate_changelog.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
#!/usr/bin/env python3
import re
import urllib.request
import urllib.parse
import urllib.error
import json
import itertools
import logging
import threading
import collections
import time
import os
import sys
import argparse
import pathlib
import contextlib
import xml.etree.ElementTree
from datetime import time as dtime, date, datetime, timedelta
log = logging.getLogger('generate_changelog')
class MissingCommitException(Exception):
pass
class JenkinsBuild:
"""Representation of a Jenkins Build"""
def __init__(self, number, last_hash, branch, build_dttm, is_building,
build_result, block_ms, wait_ms, build_ms):
self.number = number
self.last_hash = last_hash
self.branch = branch
self.build_dttm = build_dttm
self.is_building = is_building
self.build_result = build_result
self.wait_ms = wait_ms
self.build_ms = build_ms
self.block_ms = block_ms
def was_successful(self):
return not self.is_building and self.build_result == 'SUCCESS'
def __str__(self):
return (f'{self.__class__.__name__}[{self.number} - '
f'{self.last_hash} - {self.build_dttm} - '
f'{self.build_result}]')
class Commit(object):
"""Representation of a generic GitHub Commit"""
def __init__(self, hash_id, message, commit_dttm, author, parents):
self.hash = hash_id
self.message = message
self.commit_dttm = commit_dttm
self.author = author
self.parents = parents
@property
def commit_date(self):
return self.commit_dttm.date()
def committed_after(self, commit_dttm):
return self.commit_dttm is not None and self.commit_dttm >= commit_dttm
def committed_before(self, commit_dttm):
return self.commit_dttm is not None and self.commit_dttm <= commit_dttm
@property
def is_merge(self):
return len(self.parents) > 1
def __str__(self):
return (f'{self.__class__.__name__}[{self.hash} - '
f'{self.commit_dttm} - {self.message} BY {self.author}]')
class PullRequest(object):
"""Representation of a generic GitHub Pull Request"""
def __init__(self, pr_id, title, author, state, body, merge_hash,
merge_dttm, update_dttm):
self.id = pr_id
self.author = author
self.title = title
self.body = body
self.state = state
self.merge_hash = merge_hash
self.merge_dttm = merge_dttm
self.update_dttm = update_dttm
@property
def update_date(self):
return self.update_dttm.date()
@property
def merge_date(self):
return self.merge_dttm.date()
@property
def is_merged(self):
return self.merge_dttm is not None
def merged_after(self, merge_dttm):
return self.merge_dttm is not None and self.merge_dttm >= merge_dttm
def merged_before(self, merge_dttm):
return self.merge_dttm is not None and self.merge_dttm <= merge_dttm
def updated_after(self, update_dttm):
return self.update_dttm is not None and self.update_dttm >= update_dttm
def updated_before(self, update_dttm):
return self.update_dttm is not None and self.update_dttm <= update_dttm
def __str__(self):
return (f'{self.__class__.__name__}[{self.id} - {self.merge_dttm} - '
f'{self.title} BY {self.author}]')
class SummaryType:
"""Different valid Summary Types. Intended to be used as a enum/constant
class, no instantiation needed."""
NONE = 'NONE'
FEATURES = 'FEATURES'
CONTENT = 'CONTENT'
INTERFACE = 'INTERFACE'
MODS = 'MODS'
BALANCE = 'BALANCE'
BUGFIXES = 'BUGFIXES'
PERFORMANCE = 'PERFORMANCE'
INFRASTRUCTURE = 'INFRASTRUCTURE'
BUILD = 'BUILD'
I18N = 'I18N'
class CDDAPullRequest(PullRequest):
"""A Pull Request with logic specific to CDDA Repository and their
"Summary" descriptions"""
SUMMARY_REGEX = re.compile(
r'(?i:####\sSummary)\s*'
r'`*(?i:SUMMARY:?\s*)?(?P<pr_type>\w+)\s*(?:"(?P<pr_desc>.+)")?',
re.MULTILINE)
VALID_SUMMARY_CATEGORIES = (
'Content',
'Features',
'Interface',
'Mods',
'Balance',
'I18N',
'Bugfixes',
'Performance',
'Build',
'Infrastructure',
'None',
)
EXAMPLE_SUMMARIES_IN_TEMPLATE = (
("Category", "description"),
("Category", "Brief description"),
("Content", "Adds new mutation category 'Mouse'"),
)
def __init__(self, pr_id, title, author, state, body, merge_hash,
merge_dttm, update_dttm, store_body=False):
super().__init__(
pr_id, title, author, state, body if store_body else '',
merge_hash, merge_dttm, update_dttm)
self.summ_type, self.summ_desc = self._get_summary(body)
@property
def summ_type(self):
return self._summ_type
@summ_type.setter
def summ_type(self, value):
self._summ_type = value.upper() if value is not None else None
@property
def has_valid_summary(self):
return (self.summ_type == SummaryType.NONE or
(self.summ_type is not None and self.summ_desc is not None))
def _get_summary(self, body):
matches = list(re.finditer(self.SUMMARY_REGEX, body))
# Fix weird cases where a PR have multiple SUMMARY
# coming mostly from template lines that weren't removed by the pull
# requester. For example:
# https://api.github.com/repos/CleverRaven/Cataclysm-DDA/pulls/25604
def summary_filter(x):
return ((x.group('pr_type'), x.group('pr_desc')) not in
self.EXAMPLE_SUMMARIES_IN_TEMPLATE)
matches = list(filter(summary_filter, matches))
if len(matches) > 1:
log.warning(f'More than one SUMMARY defined in PR {self.id}!')
match = matches[0] if matches else None
upper_cats = (x.upper() for x in self.VALID_SUMMARY_CATEGORIES)
if match is None or match.group('pr_type').upper() not in upper_cats:
return None, None
else:
return match.group('pr_type'), match.group('pr_desc')
def __str__(self):
if self.has_valid_summary and self.summ_type == SummaryType.NONE:
return (f'{self.__class__.__name__}'
f'[{self.id} - {self.merge_dttm} - {self.summ_type} - '
f'{self.title} BY {self.author}]')
elif self.has_valid_summary:
return (f'{self.__class__.__name__}'
f'[{self.id} - {self.merge_dttm} - {self.summ_type} - '
f'{self.summ_desc} BY {self.author}]')
else:
return (f'{self.__class__.__name__}'
f'[{self.id} - {self.merge_dttm} - '
f'{self.title} BY {self.author}]')
class JenkinsBuildFactory:
"""Abstraction for instantiation of new Commit objects"""
def create(self, number, last_hash, branch, build_dttm, is_building,
build_result, block_ms, wait_ms, build_ms):
return JenkinsBuild(number, last_hash, branch, build_dttm, is_building,
build_result, block_ms, wait_ms, build_ms)
class CommitFactory:
"""Abstraction for instantiation of new Commit objects"""
def create(self, hash_id, message, commit_date, author, parents):
return Commit(hash_id, message, commit_date, author, parents)
class CDDAPullRequestFactory:
"""Abstraction for instantiation of new CDDAPullRequests objects"""
def __init__(self, store_body=False):
self.store_body = store_body
def create(self, pr_id, title, author, state, body, merge_hash, merge_dttm,
update_dttm):
return CDDAPullRequest(pr_id, title, author, state, body, merge_hash,
merge_dttm, update_dttm, self.store_body)
class CommitRepository:
"""Groups Commits for storage and common operations"""
def __init__(self):
self.ref_by_commit_hash = {}
self._latest_commit = None
def add(self, commit):
is_newer = (self._latest_commit is None or
self._latest_commit.commit_date < commit.commit_date)
if is_newer:
self._latest_commit = commit
self.ref_by_commit_hash[commit.hash] = commit
def add_multiple(self, commits):
for commit in commits:
self.add(commit)
def get_commit(self, commit_hash):
if commit_hash in self.ref_by_commit_hash:
return self.ref_by_commit_hash[commit_hash]
return None
def get_latest_commit(self):
return self._latest_commit
def get_all_commits(self, filter_by=None, sort_by=None):
"""Return all Commits in Repository. No order is guaranteed."""
commit_list = self.ref_by_commit_hash.values()
if filter_by is not None:
commit_list = filter(filter_by, commit_list)
if sort_by is not None:
commit_list = sorted(commit_list, key=sort_by)
for commit in commit_list:
yield commit
def traverse_commits_by_first_parent(self, initial_hash=None):
"""Iterate through Commits connected by the first Parent, until a
parent is not found in the Repository
This is like using 'git log --first-parent $commit', which avoids
Commits "inside" Pull Requests / Merges.
But returns Merge Commits (which often can be related to a single PR)
and Commits directly added to a Branch.
"""
if initial_hash is not None:
commit = self.get_commit(initial_hash)
else:
commit = self.get_latest_commit()
while commit is not None:
yield commit
commit = self.get_commit(commit.parents[0])
def get_commit_range_by_hash(self, latest_hash, oldest_hash):
"""Return Commits between initial_hash (including) and oldest_hash
(excluding) connected by the first Parent."""
for commit in self.traverse_commits_by_first_parent(latest_hash):
if commit.hash == oldest_hash:
return
yield commit
# consumed the whole commit list in the Repo and didn't find
# oldest_hash so returned commit list is incomplete
raise MissingCommitException(
"Can't generate commit list for specified hash range."
" There are missing Commits in CommitRepository."
)
def get_commit_range_by_date(self, latest_dttm, oldest_dttm):
"""Return Commits between latest_dttm (including) and oldest_dttm
(excluding) connected by the first Parent."""
for commit in self.traverse_commits_by_first_parent():
# assuming that traversing by first parent have chronological order
# (should be DESC BY commit_dttm)
if commit.commit_dttm <= oldest_dttm:
return
if latest_dttm >= commit.commit_dttm > oldest_dttm:
yield commit
# consumed the whole commit list and didn't find a commit past our
# build. So returned commit list *could be* incomplete
raise MissingCommitException(
"Can't generate commit list for specified date range."
" There are missing Commits in CommitRepository."
)
def purge_references(self):
self.ref_by_commit_hash.clear()
class CDDAPullRequestRepository:
"""Groups Pull Requests for storage and common operations"""
def __init__(self):
self.ref_by_pr_id = {}
self.ref_by_merge_hash = {}
def add(self, pull_request):
self.ref_by_pr_id[pull_request.id] = pull_request
if pull_request.merge_hash is not None:
self.ref_by_merge_hash[pull_request.merge_hash] = pull_request
def add_multiple(self, pull_requests):
for pr in pull_requests:
self.add(pr)
def get_pr_by_merge_hash(self, merge_hash):
if merge_hash in self.ref_by_merge_hash:
return self.ref_by_merge_hash[merge_hash]
return None
def get_all_pr(self, filter_by=None, sort_by=None):
"""Return all Pull Requests in Repository. No order is guaranteed."""
pr_list = self.ref_by_pr_id.values()
if filter_by is not None:
pr_list = filter(filter_by, pr_list)
if sort_by is not None:
pr_list = sorted(pr_list, key=sort_by)
for pr in pr_list:
yield pr
def get_merged_pr_list_by_date(self, latest_dttm, oldest_dttm):
"""Return PullRequests merged between latest_dttm (including) and
oldest_dttm (excluding)."""
for pr in self.get_all_pr(filter_by=lambda x: x.is_merged,
sort_by=lambda x: -x.merge_dttm.timestamp()):
if latest_dttm >= pr.merge_dttm > oldest_dttm:
yield pr
def purge_references(self):
self.ref_by_merge_hash.clear()
class JenkinsBuildRepository:
"""Groups JenkinsBuilds for storage and common operations"""
def __init__(self):
self.ref_by_build_number = {}
def add(self, build):
if build.number is not None:
self.ref_by_build_number[build.number] = build
def add_multiple(self, builds):
for build in builds:
self.add(build)
def get_build_by_number(self, build_number):
if build_number in self.ref_by_build_number:
return self.ref_by_build_number[build_number]
return None
def get_previous_build(self, build_number, condition=lambda x: True):
for x in range(build_number - 1, 0, -1):
prev_build = self.get_build_by_number(x)
if prev_build is not None and condition(prev_build):
return prev_build
return None
def get_previous_successful_build(self, build_number):
return self.get_previous_build(build_number,
lambda x: x.was_successful())
def get_all_builds(self, filter_by=None, sort_by=None):
"""Return all Builds in Repository. No order is guaranteed."""
build_list = self.ref_by_build_number.values()
if filter_by is not None:
build_list = filter(filter_by, build_list)
if sort_by is not None:
build_list = sorted(build_list, key=sort_by)
for build in build_list:
yield build
def purge_references(self):
self.ref_by_build_number.clear()
class JenkinsApi:
JENKINS_BUILD_LIST_API = \
r'http://gorgon.narc.ro:8080/job/Cataclysm-Matrix/api/xml'
JENKINS_BUILD_LONG_LIST_PARAMS = {
'tree': r'allBuilds[number,timestamp,building,result,actions[buildingDurationMillis,waitingDurationMillis,blockedDurationMillis,lastBuiltRevision[branch[name,SHA1]]]]', # noqa: E501
'xpath': r'//allBuild',
'wrapper': r'allBuilds',
'exclude': r'//action[not(buildingDurationMillis|waitingDurationMillis|blockedDurationMillis|lastBuiltRevision/branch)]' # noqa: E501
}
JENKINS_BUILD_SHORT_LIST_PARAMS = {
'tree': r'builds[number,timestamp,building,result,actions[buildingDurationMillis,waitingDurationMillis,blockedDurationMillis,lastBuiltRevision[branch[name,SHA1]]]]', # noqa: E501
'xpath': r'//build',
'wrapper': r'builds',
'exclude': r'//action[not(buildingDurationMillis|waitingDurationMillis|blockedDurationMillis|lastBuiltRevision/branch)]' # noqa: E501
}
def __init__(self, build_factory):
self.build_factory = build_factory
def get_build_list(self):
"""Return the builds from Jenkins. API limits the result to last 999
builds."""
request_url = (self.JENKINS_BUILD_LIST_API + '?' +
urllib.parse.urlencode(
self.JENKINS_BUILD_LONG_LIST_PARAMS))
api_request = urllib.request.Request(request_url)
log.debug(f'Processing Request {api_request.full_url}')
with urllib.request.urlopen(api_request) as api_response:
api_data = xml.etree.ElementTree.fromstring(api_response.read())
log.debug('Jenkins Request DONE!')
for build_data in api_data:
yield self._create_build_from_api_data(build_data)
def _create_build_from_api_data(self, build_data):
"""Create a JenkinsBuild instance based on data from Jenkins API"""
jb_number = int(build_data.find('number').text)
jb_build_dttm = datetime.utcfromtimestamp(
int(build_data.find('timestamp').text) // 1000)
jb_is_building = build_data.find('building').text == 'true'
jb_block_ms = timedelta(0)
jb_wait_ms = timedelta(0)
jb_build_ms = timedelta(0)
jb_build_result = None
if not jb_is_building:
jb_build_result = build_data.find('result').text
jb_block_ms = timedelta(milliseconds=int(
build_data.find(r'.//action/blockedDurationMillis').text))
jb_wait_ms = timedelta(milliseconds=int(
build_data.find(r'.//action/waitingDurationMillis').text))
jb_build_ms = timedelta(milliseconds=int(
build_data.find(r'.//action/buildingDurationMillis').text))
jb_last_hash = None
jb_branch = None
sha1 = build_data.find(r'.//action/lastBuiltRevision/branch/SHA1')
if sha1 is not None:
jb_last_hash = sha1.text
jb_branch = build_data.find(
r'.//action/lastBuiltRevision/branch/name').text
return self.build_factory.create(
jb_number, jb_last_hash, jb_branch, jb_build_dttm, jb_is_building,
jb_build_result, jb_block_ms, jb_wait_ms, jb_build_ms)
class CommitApi:
def __init__(self, commit_factory, api_token):
self.commit_factory = commit_factory
self.api_token = api_token
def get_commit_list(self, min_commit_dttm, max_commit_dttm,
branch='master', max_threads=15):
"""Return a list of Commits from specified commit date up to now. Order
is not guaranteed by threads.
params:
min_commit_dttm = None or minimum commit date to be part of the
result set (UTC+0 timezone)
max_commit_dttm = None or maximum commit date to be part of the
result set (UTC+0 timezone)
"""
if min_commit_dttm is None:
min_commit_dttm = datetime.min
if max_commit_dttm is None:
max_commit_dttm = datetime.utcnow()
results_queue = collections.deque()
request_generator = CommitApiGenerator(self.api_token, min_commit_dttm,
max_commit_dttm, branch)
threaded = MultiThreadedGitHubApi()
threaded.process_api_requests(
request_generator,
self._process_commit_data_callback(results_queue),
max_threads=max_threads)
return (commit for commit in results_queue
if commit.committed_after(min_commit_dttm) and
commit.committed_before(max_commit_dttm))
def _process_commit_data_callback(self, results_queue):
"""Returns a callback that will process data into Commits instances and
stop threads when needed."""
def _process_commit_data_callback_closure(json_data, request_generator,
api_request):
nonlocal results_queue
commit_list = [
self._create_commit_from_api_data(x) for x in json_data]
for commit in commit_list:
results_queue.append(commit)
if request_generator.is_active and len(commit_list) == 0:
log.debug('Target page found, stop giving threads more '
f'requests. Target URL: {api_request.full_url}')
request_generator.deactivate()
return _process_commit_data_callback_closure
def _create_commit_from_api_data(self, commit_data):
"""Create a Commit instance based on data from GitHub API"""
if commit_data is None:
return None
commit_sha = commit_data['sha']
# some commits have null in author.login :S like:
# https://api.github.com/repos/CleverRaven/Cataclysm-DDA/commits/569bef1891a843ec71654530a64d51939aabb3e2
# I try to use author.login when possible or fallback to
# "commit.author" which doesn't match with usernames in pull requests
# API (I guess it comes from the distinction between "name" and
# "username".
# I rather have a name that doesn't match that leave it empty.
# Anyways, I'm surprised but GitHub API sucks, is super inconsistent
# and not well thought or documented.
if commit_data['author'] is not None:
if 'login' in commit_data['author']:
commit_author = commit_data['author']['login']
else:
commit_author = 'null'
else:
commit_author = commit_data['commit']['author']['name']
if commit_data['commit']['message']:
commit_message = commit_data['commit']['message'].splitlines()[0]
else:
commit_message = ''
commit_dttm = commit_data['commit']['committer']['date']
if commit_dttm:
commit_dttm = datetime.fromisoformat(commit_dttm.rstrip('Z'))
else:
commit_dttm = None
commit_parents = tuple(p['sha'] for p in commit_data['parents'])
return self.commit_factory.create(
commit_sha, commit_message, commit_dttm, commit_author,
commit_parents)
class PullRequestApi:
GITHUB_API_SEARCH = r'https://api.github.com/search/issues'
def __init__(self, pr_factory, api_token):
self.pr_factory = pr_factory
self.api_token = api_token
def search_for_pull_request(self, commit_hash):
"""Returns the Pull Request ID of a specific Commit Hash using a Search
API in GitHub
AVOID AT ALL COST: You have to check Commit by Commit and is super
slow!
Based on
https://help.github.com/articles/searching-issues-and-pull-requests/#search-by-commit-sha
No need to make this multi-threaded as GitHub limits this to 30
requests per minute.
"""
params = {
'q': 'is:pr is:merged repo:CleverRaven/Cataclysm-DDA '
f'{commit_hash}'
}
request_builder = GitHubApiRequestBuilder(self.api_token)
api_request = request_builder.create_request(self.GITHUB_API_SEARCH,
params)
api_data = do_github_request(api_request)
# I found some cases where the search found multiple PRs because of a
# reference of the commit hash in another PR description. But it had a
# huge difference in score, it seems the engine scores over 100 the one
# that actually has the commit hash as "Merge Commit SHA".
# Output example:
# https://api.github.com/search/issues
# ?q=is%3Apr+is%3Amerged+repo%3ACleverRaven%2FCataclysm-DDA+f0c6908d154cd0fb190c2116de2bf2d3131458c3
# If the API don't return a score of 100 or more for the highest score
# item (the first item), then the commit is probably not part of any
# pull request. This assumption was backed up by checking ~9 months of
# commits
if api_data['total_count'] == 0 or api_data['items'][0]['score'] < 100:
return None
else:
return api_data['items'][0]['number']
def get_pr_list(self, min_dttm, max_dttm=None, state='all',
merged_only=False, max_threads=15):
"""Return a list of PullRequests from specified commit date up to now.
Order is not guaranteed by threads.
params:
min_dttm = None or minimum update date on the PR to be part of
the result set (UTC+0 timezone)
max_dttm = None or maximum update date on the PR to be part of
the result set (UTC+0 timezone)
state = 'open' | 'closed' | 'all'
merged_only = search only 'closed' state PRs, and filter PRs by
merge date instead of update date
"""
if min_dttm is None:
min_dttm = datetime.min
if max_dttm is None:
max_dttm = datetime.utcnow()
if merged_only:
state = 'closed'
results_queue = collections.deque()
request_generator = PullRequestApiGenerator(self.api_token, state)
threaded = MultiThreadedGitHubApi()
threaded.process_api_requests(
request_generator,
self._process_pr_data_callback(results_queue, min_dttm),
max_threads=max_threads)
if merged_only:
return (pr for pr in results_queue
if pr.is_merged and pr.merged_after(min_dttm) and
pr.merged_before(max_dttm))
else:
return (pr for pr in results_queue
if pr.updated_after(min_dttm) and
pr.updated_before(max_dttm))
def _process_pr_data_callback(self, results_queue, min_dttm):
"""Returns a callback that will process data into Pull Requests objects
and stop threads when needed."""
def _process_pr_data_callback_closure(json_data, request_generator,
api_request):
nonlocal results_queue, min_dttm
pull_request_list = [
self._create_pr_from_api_data(x) for x in json_data]
for pr in pull_request_list:
results_queue.append(pr)
# this check on update date makes sure we get the GitHub API pages
# we need a more precise PR filter of the result is made from
# results_queue later
target_page_found = not any(
pr.updated_after(min_dttm) for pr in pull_request_list)
if len(pull_request_list) == 0 or target_page_found:
if request_generator.is_active:
log.debug(
'Target page found, stop giving threads more '
f'requests. Target URL: {api_request.full_url}')
request_generator.deactivate()
return _process_pr_data_callback_closure
def _create_pr_from_api_data(self, pr_data):
"""Create a PullRequest instance based on data from GitHub API"""
if pr_data is None:
return None
pr_number = pr_data['number']
pr_author = pr_data['user']['login']
pr_title = pr_data['title']
pr_state = pr_data['state']
pr_merge_hash = pr_data['merge_commit_sha']
# python expects an ISO date with the Z to properly parse it, so I
# strip it.
if pr_data['merged_at']:
pr_merge_dttm = datetime.fromisoformat(
pr_data['merged_at'].rstrip('Z'))
else:
pr_merge_dttm = None
if pr_data['updated_at']:
pr_update_dttm = datetime.fromisoformat(
pr_data['updated_at'].rstrip('Z'))
else:
pr_update_dttm = None
# PR description can be empty :S example:
# https://github.com/CleverRaven/Cataclysm-DDA/pull/24213
pr_body = pr_data['body'] if pr_data['body'] else ''
return self.pr_factory.create(
pr_number, pr_title, pr_author, pr_state, pr_body, pr_merge_hash,
pr_merge_dttm, pr_update_dttm)
class MultiThreadedGitHubApi:
def process_api_requests(self, request_generator, callback,
max_threads=15):
"""Process HTTP API requests on threads and call the callback for each
result JSON
params:
callback = executed when data is available, should expect two
params: (json data, request_generator)
"""
# start threads
threads = []
for x in range(1, max_threads + 1):
t = threading.Thread(
target=exit_on_exception(
self._process_api_requests_on_threads),
args=(request_generator, callback))
t.name = f'WORKER_{x:03}'
threads.append(t)
t.daemon = True
t.start()
time.sleep(0.1)
# block waiting until threads get all results
for t in threads:
t.join()
log.debug('Threads have finished processing all the required GitHub '
'API Requests!!!')
@staticmethod
def _process_api_requests_on_threads(request_generator, callback):
"""Process HTTP API requests and call the callback for each result
JSON"""
log.debug('Thread Started!')
api_request = request_generator.generate()
while api_request is not None:
callback(do_github_request(api_request), request_generator,
api_request)
api_request = request_generator.generate()
log.debug('No more requests left, killing Thread.')
class GitHubApiRequestBuilder(object):
def __init__(self, api_token, timezone='Etc/UTC'):
self.api_token = api_token
self.timezone = timezone
def create_request(self, url, params=None):
"""Creates an API request based on provided URL and GET Parameters"""
if params is None:
request_url = url
else:
request_url = url + '?' + urllib.parse.urlencode(params)
if self.api_token is None:
api_request = urllib.request.Request(request_url)
else:
api_headers = {
'Authorization': 'token ' + self.api_token,
'Time-Zone': self.timezone,
}
api_request = urllib.request.Request(
request_url, headers=api_headers)
return api_request
class CommitApiGenerator(GitHubApiRequestBuilder):
"""Generates multiple HTTP requests to get Commits, used from Threads to
get data until a condition is met."""
GITHUB_API_LIST_COMMITS = \
r'https://api.github.com/repos/CleverRaven/Cataclysm-DDA/commits'
def __init__(self, api_token, since_dttm=None, until_dttm=None,
sha='master', initial_page=1, step=1, timezone='Etc/UTC'):
super().__init__(api_token, timezone)
self.sha = sha
self.since_dttm = since_dttm
self.until_dttm = until_dttm
self.page = initial_page
self.step = step
self.lock = threading.RLock()
self.is_active = True
@property
def is_active(self):
with self.lock:
return self._is_active
@is_active.setter
def is_active(self, value):
with self.lock:
self._is_active = value
def deactivate(self):
"""Stop generate() from creating new HTTP requests on future calls."""
self.is_active = False
def generate(self):
"""Returns an HTTP request to get Commits for a different API result
page each call until deactivate()."""
with self.lock:
if self.is_active:
req = self.create_request(self.since_dttm, self.until_dttm,
self.sha, self.page)
self.page += self.step
return req
else:
return None
def create_request(self, since_dttm=None, until_dttm=None, sha='master',
page=1):
"""Creates an HTTP Request to GitHub API to get Commits from CDDA
repository."""
params = {
'sha': sha,
'page': page,
}
if since_dttm is not None:
params['since'] = since_dttm.isoformat()
if until_dttm is not None:
params['until'] = until_dttm.isoformat()
return super().create_request(self.GITHUB_API_LIST_COMMITS, params)
class PullRequestApiGenerator(GitHubApiRequestBuilder):
"""Generates multiple HTTP requests to get Pull Requests, used from Threads
to get data until a condition is met."""
GITHUB_API_LIST_PR = \
r'https://api.github.com/repos/CleverRaven/Cataclysm-DDA/pulls'
def __init__(self, api_token, state='all', initial_page=1, step=1,
timezone='Etc/UTC'):
super().__init__(api_token, timezone)
self.page = initial_page
self.step = step
self.state = state
self.lock = threading.RLock()
self.is_active = True
@property
def is_active(self):
with self.lock:
return self._is_active
@is_active.setter
def is_active(self, value):
with self.lock:
self._is_active = value
def deactivate(self):
"""Stop generate() from creating new HTTP requests on future calls."""
self.is_active = False
def generate(self):
"""Returns an HTTP request to get Pull Requests for a different API
result page each call until deactivate()."""
with self.lock:
if self.is_active:
req = self.create_request(self.state, self.page)
self.page += self.step
return req
else:
return None
def create_request(self, state='all', page=1):
"""Creates an HTTP Request to GitHub API to get Pull Requests from CDDA
repository.
params:
state = 'open' | 'closed' | 'all'
"""
params = {
'state': state,
'sort': 'updated',
'direction': 'desc',
'page': page,
}
return super().create_request(self.GITHUB_API_LIST_PR, params)
def exit_on_exception(func):
"""Decorator to terminate the main script and all threads if a thread
generates an Exception"""
def exit_on_exception_closure(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as err:
log.exception(f'Unhandled Exception: {err}')
os._exit(-10)
return exit_on_exception_closure
def do_github_request(api_request, retry_on_limit=3):
"""Do an HTTP request to GitHub and retries in case of hitting API
limits"""
for retry in range(1, retry_on_limit + 2):
try:
log.debug(f'Processing Request {api_request.full_url}')
with urllib.request.urlopen(api_request) as api_response:
return json.load(api_response)
except urllib.error.HTTPError as err:
# hit rate limit, wait and retry
is_403 = err.code == 403
is_502 = err.code == 502
if is_403 and err.getheader('Retry-After'):
wait = int(err.getheader('Retry-After')) + 5
log.info(f'Reached GitHub API rate limit. Retry {retry}, '
f'waiting {wait} secs...')
time.sleep(wait)
elif is_403 and err.getheader('X-RateLimit-Remaining') == '0':
reset = int(err.getheader('X-RateLimit-Reset'))
delta = datetime.utcfromtimestamp(reset) - datetime.utcnow()
wait = delta.seconds + 5
log.info(f'Reached GitHub API rate limit. Retry {retry}, '
f'waiting {wait} secs...')
time.sleep(wait)
elif is_502:
wait = 5
log.info(f'GitHub API 502 Gateway Error. Retry {retry}, '
f'waiting {wait} secs...')
time.sleep(wait)
else:
# other kind of http error, just implode
log.exception(f'Unhandled Exception: {err} - '
f'HTTP Headers: {err.getheaders()}')
raise
raise Exception('Retry limit reached')
def read_personal_token(filename):
"""Return Personal Token from specified file, None if no file is provided
or file doesn't exist.
Personal Tokens can be generated in https://github.com/settings/tokens
This makes GitHub API have higher usage limits
"""
if filename is None:
return None
try:
with open(
pathlib.Path(str(filename)).expanduser(),
encoding="utf-8") as token_file:
match = re.search('(?P<token>\\S+)', token_file.read(),
flags=re.MULTILINE)
if match is not None:
return match.group('token')
except IOError:
pass
return None
@contextlib.contextmanager