forked from martinthomson/i-d-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive_repo.py
executable file
·870 lines (735 loc) · 21.5 KB
/
archive_repo.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
#!/usr/bin/env python3
import os
import sys
import json
import requests
import argparse
from datetime import datetime, timezone
import time
import re
import dateutil.parser as dp
import shutil
import warnings
from types import SimpleNamespace
from collections import namedtuple
parser = argparse.ArgumentParser(description="Archive repo issues and PRs.")
parser.add_argument("repo", help="GitHub repo to archive (e.g. quicwg/base-drafts)")
parser.add_argument("githubToken", help="GitHub OAuth token")
parser.add_argument("outFile", default=None, nargs="?", help="destination for output")
parser.add_argument(
"--reference oldfile",
dest="refFile",
nargs="?",
help="older file produced by this tool for reference",
)
parser.add_argument(
"--issues-only",
dest="issuesOnly",
default=False,
action="store_true",
help="download issues, but not pull requests",
)
parser.add_argument(
"--quiet",
dest="quiet",
default=False,
action="store_true",
help="do not output HTTP requests",
)
args = parser.parse_args()
if not args.githubToken and "GITHUB_API_TOKEN" in os.environ.keys():
args.githubToken = os.environ["GITHUB_API_TOKEN"]
if args.repo[-1] == "/":
args.repo = args.repo[:-1]
API_headers = {
"user-agent": "martinthomson/i-d-template/archive_repo.py",
"authorization": "bearer " + args.githubToken,
}
s = requests.Session()
s.headers.update(API_headers)
now = datetime.now(timezone.utc)
#######################
## Query definitions ##
#######################
# Query fragments
gql_LabelFields = """
fragment labels on Labelable {
labels(first: 5) {
nodes { name }
}
}
"""
gql_AssigneeFields = """
fragment assignees on Assignable {
assignees(first: 5) {
nodes { login }
}
}
"""
gql_AuthorFields = """
fragment author on Comment {
author { login }
authorAssociation
}
"""
gql_Comment_Fields = """
fragment commentFields on Comment {
body
createdAt
updatedAt
}
"""
gql_RateLimit = """
fragment rateLimit on Query {
rateLimit {
remaining
resetAt
}
}
"""
gql_Paged = """
pageInfo {
endCursor
hasNextPage
}
"""
# Issues
gql_Issue_Fields = (
"""
fragment issueFields on Issue {
number
id
title
url
state
...author
...assignees
...labels
...commentFields
closedAt
comments(first: 100) {
nodes {
...author
...commentFields
}
"""
+ gql_Paged
+ """
}
}
"""
+ gql_AuthorFields
+ gql_AssigneeFields
+ gql_Comment_Fields
+ gql_LabelFields
)
gql_Issues_Query = (
"nodes { ...issueFields }"
+ gql_Paged
+ """
}
}
...rateLimit
}
"""
+ gql_RateLimit
)
gql_AllIssues_First = (
"""
query($owner: String!, $repo: String!){
repository(owner: $owner, name: $repo) {
issues(first: 100) {
"""
+ gql_Issues_Query
)
gql_AllIssues_Subsequent = (
"""
query($owner: String!, $repo: String!, $cursor: String!){
repository(owner: $owner, name: $repo) {
issues(first: 100, after: $cursor) {
"""
+ gql_Issues_Query
)
gql_UpdatedIssues_First = (
"""
query($owner: String!, $repo: String!, $filters: IssueFilters){
repository(owner: $owner, name: $repo) {
issues(first: 100, filterBy: $filters) {
"""
+ gql_Issues_Query
)
gql_UpdatedIssues_Subsequent = (
"""
query($owner: String!, $repo: String!, $filters: IssueFilters, $cursor: String!){
repository(owner: $owner, name: $repo) {
issues(first: 100, filterBy: $filters, after: $cursor) {
"""
+ gql_Issues_Query
)
gql_Issue_Comments_Query = (
"""
query($id: ID!, $cursor: String!){
node(id: $id) {
...on Issue {
comments(first:100, after:$cursor) {
nodes {
...author
...commentFields
}
"""
+ gql_Paged
+ """
}
}
}
...rateLimit
}
"""
+ gql_Comment_Fields
+ gql_AuthorFields
+ gql_RateLimit
)
# Pull Requests
gql_Review_Fields = (
"""
fragment reviewFields on PullRequestReview {
id
commit { abbreviatedOid }
...author
state
...commentFields
comments(first: 50) {
nodes {
originalPosition
...commentFields
}
"""
+ gql_Paged
+ """
}
}
"""
+ gql_Comment_Fields
+ gql_AuthorFields
)
gql_PullRequest_Fields = (
"""
fragment prFields on PullRequest {
number
id
title
url
state
...author
...assignees
...labels
...commentFields
baseRepository { nameWithOwner }
baseRefName
baseRefOid
headRepository { nameWithOwner }
headRefName
headRefOid
closedAt
mergedAt
mergedBy { login }
mergeCommit { oid }
comments(first: 100) {
nodes {
...author
...commentFields
}
"""
+ gql_Paged
+ """
}
reviews(first: 50) {
nodes {
...reviewFields
}
"""
+ gql_Paged
+ """
}
}
"""
+ gql_AssigneeFields
+ gql_LabelFields
+ gql_Review_Fields
)
# ...reviewFields definition includes ...commentFields and ...author
gql_PullRequest_Query = (
"nodes { ...prFields }"
+ gql_Paged
+ """
}
}
...rateLimit
}
"""
+ gql_RateLimit
)
gql_AllPRs_Initial = (
"""
query($owner: String!, $repo: String!){
repository(owner: $owner, name: $repo) {
pullRequests(first: 10, orderBy: {field: UPDATED_AT, direction:DESC}) {
"""
+ gql_PullRequest_Query
)
gql_AllPRs_Subsequent = (
"""
query($owner: String!, $repo: String!, $cursor: String!){
repository(owner: $owner, name: $repo) {
pullRequests(first: 25, after: $cursor, orderBy: {field: UPDATED_AT, direction:DESC}) {
"""
+ gql_PullRequest_Query
)
gql_PR_Comments_Query = (
"""
query($id: ID!, $cursor: String!){
node(id: $id) {
...on PullRequest {
comments(first:100, after:$cursor) {
nodes { ...commentFields }
"""
+ gql_Paged
+ """
}
}
}
}
"""
+ gql_Comment_Fields
+ gql_RateLimit
)
gql_PR_Review_Query = (
"""
query($id: ID!, $cursor: String!){
node(id: $id) {
...on PullRequest {
reviews(first:100, after:$cursor) {
nodes { ...reviewFields }
"""
+ gql_Paged
+ """
}
}
}
...rateLimit
}
"""
+ gql_Review_Fields
+ gql_RateLimit
)
gql_PR_ReviewComments_Query = (
"""
query($id: ID!, $cursor: String!){
node(id: $id) {
...on PullRequestReview {
comments(first: 50, after:$cursor) {
nodes {
originalPosition
...commentFields
}
"""
+ gql_Paged
+ """
}
}
}
...rateLimit
}
"""
+ gql_Comment_Fields
+ gql_RateLimit
)
# Labels
gql_Labels_Query = (
"""
query($owner: String!, $repo: String!){
repository(owner: $owner, name: $repo) {
labels(first:100) {
nodes {
name
description
color
}
"""
+ gql_Paged
+ """
}
}
...rateLimit
}
"""
+ gql_RateLimit
)
gql_MoreLabels_Query = (
"""
query($owner: String!, $repo: String!, $cursor: String!) {
repository(owner: $owner, name: $repo) {
labels(first:100, after:$cursor) {
nodes {
name
description
color
}
"""
+ gql_Paged
+ """
}
}
...rateLimit
}
"""
+ gql_RateLimit
)
##########################
## Function definitions ##
##########################
last_request_limit = 5000
next_reset_time = datetime.now()
def stall_until(time):
time_to_sleep = time - datetime.now().timestamp() + 1
print("GitHub API rate-limited; waiting for" + str(time_to_sleep) + "seconds")
time.sleep(time_to_sleep)
def submit_query(query, variables, display):
global last_request_limit
global next_reset_time
url = "https://api.github.com/graphql"
bodyjson = {"query": re.sub(r"\s+", " ", query).strip()}
if variables:
bodyjson["variables"] = variables
body = json.dumps(bodyjson)
output = f"Submitting query for {display} with "
output += str(variables) if variables else "no parameters"
log(output)
result = dict()
for _attempt in range(3):
try:
response = s.post(url, body)
response.raise_for_status()
result = response.json()
except:
time.sleep(5)
pass
if (
"errors" in result
and "type" in result["errors"]
and result["errors"]["type"] == "RATE_LIMITED"
):
# We're rate-limited; STALL
if next_reset_time > datetime.now():
stall_until(next_reset_time)
else:
# We haven't made a successful request, so we don't know how long to sleep.
# Guesstimate 10 minutes and try again.
time.sleep(600)
continue
break
if "data" in result.keys() and result["data"] is not None:
if "rateLimit" in result["data"]:
last_request_limit = result["data"]["rateLimit"]["remaining"]
next_reset_time = dp.parse(result["data"]["rateLimit"]["resetAt"])
if last_request_limit < 2:
# We're about to be rate-limited; STALL
stall_until(next_reset_time)
last_request_limit = 5000
del result["data"]["rateLimit"]
return result["data"]
raise RuntimeError(result.get("errors", "Empty response"))
def followPagination(node, key, query, display):
if key not in node:
return
get_more = node[key]["pageInfo"]["hasNextPage"]
cursor = node[key]["pageInfo"]["endCursor"]
while get_more:
# Need to paginate
query_variables = {"id": node["id"], "cursor": cursor}
more = submit_query(query, query_variables, display)
node[key]["nodes"] += more["node"][key]["nodes"]
get_more = more["node"][key]["pageInfo"]["hasNextPage"]
cursor = more["node"][key]["pageInfo"]["endCursor"]
del node[key]["pageInfo"]
def collapse_single(thing, key, name):
"Collapse something in the form of { x: nodes [ { $name: 'stuff' }] }"
if key in thing:
thing[key] = [item[name] for item in thing[key]["nodes"]]
def collapse(thing, key):
"Collapse something in the form of { x: nodes [] }"
if key in thing:
thing[key] = thing[key]["nodes"]
def collapse_map(thing, key, name):
"""Collapse something in the form of { x: {$name: $value} } into {x: $value}
Where the {$name:...} can be null instead."""
if key in thing and thing[key] is not None:
thing[key] = thing[key][name]
def eprint(*str, **kwargs):
print(*str, file=sys.stderr, **kwargs)
if args.quiet:
def log(*str, **kwargs):
pass
else:
def log(*str, **kwargs):
eprint(*str, **kwargs)
def getIssues(refFile, fields=gql_Issue_Fields, updateOld=False):
issue_cursor = None
get_more_issues = True
while get_more_issues:
if issue_cursor is None:
# Initial issue fetch
query = gql_AllIssues_First
variables = {"owner": owner, "repo": repo}
if not updateOld and refFile.lastSuccess:
variables["filters"] = {"since": refFile.lastSuccess.isoformat()}
query = gql_UpdatedIssues_First
else:
# Fetching more issues
query = gql_AllIssues_Subsequent
variables = {"owner": owner, "repo": repo, "cursor": issue_cursor}
if refFile.lastSuccess and not updateOld:
variables["filters"] = {"since": lastSuccess.isoformat()}
query = gql_UpdatedIssues_Subsequent
data = submit_query(query + fields, variables, "issues")
# Iterate through the issues
issues = data["repository"]["issues"]
for issue in issues["nodes"]:
number = issue["number"]
if updateOld and number not in refFile.issues:
continue
# Are the comments on this issue complete?
followPagination(
issue,
"comments",
gql_Issue_Comments_Query,
f"additional comments on issue #{number}",
)
# Collapse some nodes
collapse_map(issue, "author", "login")
collapse_single(issue, "labels", "name")
collapse_single(issue, "assignees", "login")
collapse(issue, "comments")
for comment in issue.get("comments", []):
collapse_map(comment, "author", "login")
# Delete the old instance; add this instance
if not updateOld and number in refFile.issues:
del refFile.issues[number]
if number in refFile.issues:
refFile.issues[number].update(issue)
else:
refFile.issues[number] = issue
refFile.canCopy = False
get_more_issues = issues["pageInfo"]["hasNextPage"]
issue_cursor = issues["pageInfo"]["endCursor"]
def getPRs(refFile, fields=gql_PullRequest_Fields, updateOld=False):
issue_cursor = None
get_more_issues = True
# Since PRs can't be filtered by their update time, we retrieve
# them in update-time order and cut off pagination once we're
# older than the reference file.
while get_more_issues:
query = gql_AllPRs_Initial
variables = {"owner": owner, "repo": repo}
if issue_cursor is not None:
query = gql_AllPRs_Subsequent
variables["cursor"] = issue_cursor
data = submit_query(query + fields, variables, "pull requests")
# Iterate through the PRs
prs = data["repository"]["pullRequests"]
for pr in prs["nodes"]:
number = pr["number"]
# Since we can't filter, check if we already have this one.
if not updateOld:
if number in refFile.prs:
ref_updatedAt = dp.parse(refFile.prs[number]["updatedAt"])
dl_updatedAt = dp.parse(pr["updatedAt"])
if ref_updatedAt >= dl_updatedAt:
continue
elif number not in refFile.prs:
continue
# Issues only have comments; PRs have both comments and reviews,
# and reviews themselves have comments.
followPagination(
pr,
"comments",
gql_PR_Comments_Query,
f"additional comments on PR#{number}",
)
followPagination(
pr, "reviews", gql_PR_Review_Query, f"additional reviews on PR#{number}"
)
for review in pr.get("reviews", {}).get("nodes", {}):
followPagination(
review,
"comments",
gql_PR_ReviewComments_Query,
f"additional review comments on PR#{number}",
)
# Collapse some nodes
collapse_map(pr, "author", "login")
collapse_map(pr, "mergedBy", "login")
collapse_single(pr, "labels", "name")
collapse_map(pr, "baseRepository", "nameWithOwner")
collapse_map(pr, "headRepository", "nameWithOwner")
collapse_single(pr, "assignees", "login")
collapse(pr, "comments")
for comment in pr.get("comments", []):
collapse_map(comment, "author", "login")
collapse(pr, "reviews")
for review in pr.get("reviews", []):
collapse_map(review, "author", "login")
collapse(review, "comments")
# Delete the old instance; add this instance
if not updateOld and number in refFile.prs.keys():
del refFile.prs[number]
if number in refFile.prs.keys():
refFile.prs[number].update(pr)
else:
refFile.prs[number] = pr
refFile.canCopy = False
get_more_issues = prs["pageInfo"]["hasNextPage"]
issue_cursor = prs["pageInfo"]["endCursor"]
# Stop paginating if we've caught up to the last download
if not updateOld and prs["nodes"] and refFile.lastSuccess:
oldestRetrieved = dp.parse(prs["nodes"][-1]["updatedAt"])
if oldestRetrieved < refFile.lastSuccess:
get_more_issues = False
def newReferenceFile():
return SimpleNamespace(
magic=current_magic,
issues=dict(),
prs=dict(),
issues_only=True,
lastSuccess=None,
canCopy=False,
filename=None,
)
def loadReference(filename):
fileIsValid = False
reference = newReferenceFile()
reference.filename = filename
if filename:
try:
with open(filename, "r") as ref_file:
raw_reference = json.load(ref_file)
fileIsValid = True
for element in ("magic", "timestamp", "issues", "repo"):
if element not in raw_reference:
fileIsValid = False
break
if fileIsValid and (
raw_reference["magic"] == current_magic
or raw_reference["magic"] in upgrades
):
reference.magic = raw_reference["magic"]
else:
warnings.warn("Input file does not appear to be generated by this tool")
fileIsValid = False
if fileIsValid and raw_reference["repo"] != args.repo:
warnings.warn("Input file was generated from a different repo")
fileIsValid = False
if fileIsValid:
reference.lastSuccess = dp.parse(raw_reference["timestamp"])
reference.issues = dict(
[(issue["number"], issue) for issue in raw_reference["issues"]]
)
if "pulls" in raw_reference:
reference.issues_only = False
reference.prs = dict(
[(pr["number"], pr) for pr in raw_reference["pulls"]]
)
else:
reference.issues_only = True
reference.prs = dict()
except:
warnings.warn("Unable to read input file; proceeding without it")
pass
if not fileIsValid:
return newReferenceFile()
reference.canCopy = bool(reference.issues) and bool(
reference.prs or args.issuesOnly
)
return upgradeReference(reference)
#########################
## Upgrade definitions ##
#########################
current_magic = "E!vIA5L86J2I"
UpgradeInstruction = namedtuple("UpgradeInstruction", ["result", "issues", "prs"])
upgrades = {
"B8n2c@e8kvfx": UpgradeInstruction(
result="E!vIA5L86J2I",
issues=None,
prs="""
fragment prFields on PullRequest {
number
baseRepository { nameWithOwner }
baseRefName
baseRefOid
headRepository { nameWithOwner }
headRefName
headRefOid
mergeCommit { oid }
}""",
)
}
def upgradeReference(reference):
try:
while reference.magic in upgrades:
if upgrades[reference.magic].issues:
getIssues(reference, upgrades[reference.magic].issues, True)
if upgrades[reference.magic].prs:
getPRs(reference, upgrades[reference.magic].prs, True)
reference.magic = upgrades[reference.magic].result
except:
pass
if reference.magic != current_magic:
warnings.warn(
"Unable to upgrade input file to current version; proceeding without it"
)
return newReferenceFile()
return reference
#####################
## Body of program ##
#####################
(owner, repo) = args.repo.split("/", 1)
## Read in the reference files, if any
reference = loadReference(args.refFile)
## Download from GitHub the full issues list (if no reference) or the updated issues list (if reference)
getIssues(reference)
## Similar process with PRs, except they don't have a filter
if not args.issuesOnly:
getPRs(reference)
# Fetch the Labels fresh each time
labels_ref = list()
issue_cursor = None
get_more_issues = True
while get_more_issues:
query = gql_Labels_Query
variables = {"owner": owner, "repo": repo}
if issue_cursor is not None:
query = gql_MoreLabels_Query
variables["cursor"] = issue_cursor
labels = submit_query(query, variables, "labels")
labels_ref += labels["repository"]["labels"]["nodes"]
get_more_issues = labels["repository"]["labels"]["pageInfo"]["hasNextPage"]
issue_cursor = labels["repository"]["labels"]["pageInfo"]["endCursor"]
## Ready to output
## Pick up everything in the reference if nothing new was downloaded
if reference.canCopy and args.outFile:
shutil.copyfile(args.refFile, args.outFile)
else:
output = {
"magic": current_magic,
"timestamp": now.isoformat(),
"repo": args.repo,
"labels": labels_ref,
"issues": [issue for (id, issue) in sorted(reference.issues.items())],
}
if not args.issuesOnly:
output["pulls"] = [pr for (id, pr) in sorted(reference.prs.items())]
if args.outFile:
with open(args.outFile, "w") as output_file:
json.dump(output, output_file, indent=2)
else:
json.dump(output, sys.stdout, indent=2)