-
Notifications
You must be signed in to change notification settings - Fork 6
/
github-mirror.py
executable file
·1583 lines (1235 loc) · 41.7 KB
/
github-mirror.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
"""
Github Repo Mirror Tool
This mirrors pull requests, with special handling for maintaining a fork
of an "awesome" repo.
Setup:
1. `pip install ghapi`
2. Create token in Developer settings > Personal access tokens
3. Put token in ~/.private/github-token
List a page of PRs:
./bin/github-mirror.py -s 1
Mirror PR number 10:
./bin/github-mirror.py -m 10
For more help use `-h` flag and comments in this file.
"""
import yaml, json, sys, re, os, logging, shutil
import sqlite3
import requests
from collections import defaultdict
from dataclasses import dataclass, field, fields, asdict
from time import sleep
from pprint import pprint
from subprocess import run, PIPE, STDOUT
from pathlib import Path
from functools import wraps
from textwrap import indent
from datetime import datetime
from shlex import quote
from ghapi.all import GhApi, paged
from urllib.error import HTTPError
###############################################################
# Classes
@dataclass
class Repo:
"""Github Repo."""
owner: str
repo: str
@property
def gh(self):
return asdict(self)
def __str__(self):
return f'{self.owner}/{self.repo}'
@dataclass
class Pull:
"""Github Pull Request Reference."""
remote: str
num: int
@property
def gh(self):
return dict(
pull_number=self.num,
issue_number=self.num,
owner=self.repo.owner,
repo=self.repo.repo,
)
@property
def repo(self):
return REMOTES[self.remote]
def __str__(self):
return f'{self.repo}#{self.num}'
@property
def key(self):
return f'pull/{self.repo}/{self.num}'
class Record:
"""Generic DB Record."""
key: str = '' # normalized url
ver: int = 0
def __init__(self, **kw):
self.__dict__ = kw
def __setitem__(self, k, v):
setattr(self, k, v)
def __getitem__(self, k):
return getattr(self, k)
def get(self, key, default=None):
return getattr(self, key, default)
def keys(self):
return self.__dict__.keys()
def __str__(self):
return 'Record(%s)' % self.__dict__
@dataclass
class ListInfo:
"""Awesome List Metadata."""
url: str = ''
key: str = '' # normalized url
title: str = ''
topic: str = ''
desc: str = ''
stars: int = 0
updated: str = ''
size: int = 0
status: str = ''
redir: str = ''
code: int = 0
error: str = ''
ver: int = 0
owner: str = '' # ignored - old
head: str = '' # ignored - old
links: list = None # ignored - old
# not stored, only for sort+fixup
indent = ''
alts = None
def build_link(self, prefix=None):
title = self.title
if prefix:
title = ': '.join([*prefix, title])
link = f'{self.indent}- [{title}]({self.url})'
if self.desc:
link += f' - {self.desc}'
return link
def __str__(self):
out = []
for f in 'topic desc url stars size redir error status'.split():
if v := getattr(self, f, None):
out.append((f, v))
if self.code not in [0, 200]:
out.append(('code', self.code))
if self.updated:
out.append(('mtime', _format_time(self.updated)))
if m := re.match(r'https?://github.com/([^/#]+)/([^/#]+)', self.url):
head = f'{self.title} from @{m[1]}'
else:
head = f'{self.title}'
if self.alts:
for alt in self.alts:
out.append(('alt', '\n' + indent(str(alt), ' ')))
return head + ':\n' + '\n'.join('%7s: %s' % i for i in out)
@dataclass
class PullInfo:
"""Github Pull Request Info."""
remote: str = ''
num: int = 0 # srcpr.num
ver: int = 0
pull: str = ''
head: str = '' # repo:branch
created: datetime = None
status: str = ''
error: str = ''
links: list[str] = field(default_factory=list) # links to lists
extra: list[str] = field(default_factory=list) # extra lines in diff
@property
def title(self):
if self.links:
return get_list_info(self.links[0]).title
else:
return 'no links'
@property
def ref(self):
"""Return best ref for this PR."""
# use local ref if available
if 0 == sh_code(f'git rev-parse --verify {self.branch} >/dev/null 2>&1'):
return f'{self.branch}'
# fallback to special github remote pull branch
if 0 != sh_code(f'git rev-parse --verify {self.remote_ref} >/dev/null 2>&1'):
sh(f'git fetch -q {self.remote} refs/pull/{self.num}/head:{self.remote_ref}')
return self.remote_ref
@property
def remote_ref(self):
"""Remote ref for PR."""
return f'remotes/{self.remote}/pull/{self.num}/head'
@property
def branch(self):
"""Return local branch name for this PR."""
# use head if a local PR
if self.remote == 'origin':
return self.head.split(':')[1]
else:
return f'pull/{self.remote}/{self.num}'
def __str__(self):
out = f' pull: {self.pull}'
out += f'\ncreated: {_format_time(self.created)}'
counts = defaultdict(int)
if self.head:
out += f'\n head: {self.head}'
for line in self.extra:
out += f'\n extra: {line}'
links = []
for url in self.links:
link = get_list_info(url)
counts[link.status] += 1
if link.status != 'dup' or args.dups:
links.append('List ' + str(link))
out += '\n counts: ' + ' '.join(f'{k}={v}' for k,v in counts.items())
for link in links:
out += '\n\n' + link
return out
###############################################################
# Globals
WORKDIR = Path('./work~')
DEST_REPO = Repo(owner="0ex", repo="more-awesome")
REMOTES = dict(
origin=DEST_REPO,
sind=Repo(owner="sindresorhus", repo="awesome"),
emijrp=Repo(owner="emijrp", repo="awesome-awesome"),
)
FETCH_BRANCH_VER = 8
IN_PATH = 'readme.md README.md'
OUT_PATH = 'README.md'
gh = None
db = None
args = None
sess = requests.Session()
###############################################################
# Main and top-level commands
def main():
from logging import basicConfig, getLogger, DEBUG, INFO
basicConfig(
level=INFO,
format=" %(levelname)s: %(message)s",
)
#getLogger('urllib3.connectionpool').setLevel(INFO)
print('GITHUB MIRROR:\n')
parse_args()
login()
if args.debug:
gh.debug = lambda req: print(req.summary())
if args.verbose:
getLogger('root').setLevel(DEBUG)
if not (WORKDIR / '.git').exists():
WORKDIR.mkdir(exists_ok=True, parents=True)
sh('git clone . work')
# start in a predictable state
shutil.copyfile('.git/config', WORKDIR / '.git/config')
os.chdir(WORKDIR)
sh('git co main && git pull')
if args.scan is not None:
scan_pulls(args.src, args.scan)
return
if args.sort:
sort_readme()
return
if args.untagged:
list_untagged()
return
if not args.prnum:
log('EArgs', 'No pull requests given')
return
for prnum in args.prnum:
srcpr = Pull(args.src, prnum)
if args.mirror:
info = build_pull_info(srcpr)
fetch_branch(info)
copy_ghpr(srcpr)
if args.info:
show_info(srcpr, long=True, diff=not args.brief)
if args.rebase:
semantic_merge(srcpr)
show_diff(srcpr)
if args.accept:
show_info(srcpr, long=True, diff=not args.brief)
accept_pull(srcpr)
log('IDone')
def parse_args(argv=None):
global args
from argparse import ArgumentParser
p = ArgumentParser()
# global behavior
p.add_argument('-r', '--redo', type=str, default='')
p.add_argument('-d', '--debug', action='store_true')
p.add_argument('-v', '--verbose', action='store_true')
p.add_argument('-t', '--tag', action='store_true', help='tag repos')
p.add_argument('-T', '--throttle', type=int, default=0, help='throttle')
p.add_argument('-B', '--brief', action='store_true')
p.add_argument('--max', type=int, default=0, help='stop after max links')
p.add_argument('--dups', action='store_true', help='no not skip dups')
# repo operations
p.add_argument('-s', '--scan', type=str, help='scan: ALL or page number')
p.add_argument('--list', action='store_true', help='list links')
p.add_argument('--sort', action='store_true', help='sort readme')
p.add_argument('--fixup', action='store_true', help='fixup while sorting')
p.add_argument('--untagged', action='store_true', help='list untagged PRs')
p.add_argument('-S', '--src', type=str,
default='origin', choices=list(REMOTES), help='source repo')
# PR operations
p.add_argument('prnum', type=int, nargs='*', help='pull requests')
p.add_argument('-b', '--rebase', action='store_true', help='rebase pr with main')
p.add_argument('-a', '--accept', action='store_true', help='accept pr')
p.add_argument('-m', '--mirror', action='store_true', help='copy branch and create pr')
p.add_argument('-i', '--info', action='store_true', help='print PR info')
args = p.parse_args(argv or sys.argv[1:])
def login():
global gh, db
db = DB()
path = os.getenv('GITHUB_TOKEN_PATH', None) or '~/.private/github-token'
cfg = Path(path).expanduser()
with open(cfg) as f:
token = f.read().strip()
gh = GhApi(token=token)
# print(json.dumps(gh.rate_limit.get(), indent=4))
def sort_readme():
"""Sort and normalize."""
print('\nSORT:\n')
lines = []
topic_parts = []
topic = False
seen = set()
with open(OUT_PATH) as f:
for line in f:
log('DLine', repr(line))
if topic:
if topic_parts and not line.strip():
# end of topic
topic = False
lines += sorted(topic_parts, key=lambda p: p.lower())
lines += ['\n']
elif line.strip().startswith('-'):
# extract title, url, desc
info = parse_line(line, [topic])
if info:
log('DLink', repr(info.key), info.url, info.title)
if info.key in seen:
log('WDup', line.strip())
continue
else:
seen.add(info.key)
if args.info:
print(indent(str(info), ' '), '\n')
if args.fixup:
line = info.build_link() + '\n'
# we don't sort second-level entries
if line[0] == '-':
topic_parts.append(line)
else:
topic_parts[-1] = topic_parts[-1] + line
elif not topic_parts:
# leading blank lines and text
lines.append(line)
else:
# append sub-lists to exiting part - do not sort
topic_parts[-1] += line
else:
m = re.match(r'##+ +(.*)', line)
if not m:
m = re.match(r'\*\*(.*)\*\*', line)
if m:
log('ISection', m[1])
topic = m[1]
topic_parts = []
lines.append(line)
with open(OUT_PATH, 'w') as f:
f.write(''.join(lines))
log('ISorted')
def scan_pulls(remote, page):
repo = REMOTES[remote]
args = dict(
**repo.gh,
state='closed',
sort='created',
direction='asc',
)
if page == 'ALL':
pulls = all_pages(gh.pulls.list, per_page=100, **args)
else:
pulls = gh.pulls.list(**args, page=page, per_page=20)
for pr in pulls:
srcpr = Pull(remote, pr.number)
show_info(srcpr, ghpr=pr)
def list_untagged():
"""List PRs which are merged but untagged."""
for rec in db.scan('pull/%'):
tag = rec.get('tag')
if not tag:
srcpr = PullInfo(**rec)
destpr = get_destpr(srcpr)
dest = gh.pulls.get(**destpr.gh)
if dest.merged:
print(rec['key'])
def show_info(srcpr, ghpr=None, long=False, diff=True):
"""Summarize PR."""
if not ghpr:
ghpr = gh.pulls.get(**srcpr.gh)
# high-level status estimation
if ghpr.merged_at:
status = 'merged'
elif srcpr.repo == DEST_REPO:
status = 'local'
elif ghpr.user.login == srcpr.repo.owner:
# internal PRs
status = 'self'
else:
status = None
if not status or long:
info = build_pull_info(srcpr)
status = info.status
print(
color(status, '#%-5d %7s %20.20s' % (srcpr.num, status, ghpr.head.label)),
ghpr.title[:50])
if long or status in ['new', 'bad']:
print()
print(indent(str(info), ' '))
print()
if diff:
diff = sh_out(f'git diff -U1 --color=always --merge-base main {info.ref} | tail -n +5')
print('\nDIFF:\n\n', indent(diff, ' '))
def fetch_branch(info: PullInfo):
"""Fetch branch from upstream into origin."""
print('\nFETCH:\n')
verify = sh_code(f'git rev-parse --verify {info.branch} >/dev/null 2>&1')
if verify == 0:
log('WExists', f'{info.branch} already exists')
return
sh(f'git checkout --no-guess -q -b {info.branch} {info.ref}')
# remove junk commits
ret = sh_out('git rev-list --grep="Meta tweaks" main..')
revs = ret.strip().splitlines()
for rev in revs:
try:
sh(f'git revert --no-edit {rev}')
except Exception as e:
log('WRevert', str(e))
sh('git checkout -q main')
def add_link(info: ListInfo):
"""Add link to README."""
lines = []
found_line = False
found_topic = False
found_item = False # seen at least one item in topic
topic_list = info.topic.split(': ')
extra_topic = []
log('DInsert', info.topic, info.title)
with open(OUT_PATH) as f:
for line in f:
#log('DLine', repr(line))
if found_line:
# just copy everything for here on out
pass
elif found_topic:
# look for alphabetical location
m = re.match(r'[-*] *(?:\[([^][]+)\]|([\w ]+))', line)
if m:
pos = m[1] or m[2]
found_item = True
elif found_item and not line.strip():
pos = 'zzz'
else:
pos = None
if extra_topic:
target_pos = extra_topic[0]
else:
target_pos = info.title
if pos and pos >= target_pos:
found_line = True
link = info.build_link(extra_topic[1:] if extra_topic else None)
if link.strip() == line.strip():
log('WDup', 'avoiding duplicate line')
elif pos == target_pos:
log('DInsert', 'inserting after', line.strip())
lines.append(line)
lines.append('\t' + link + '\n')
continue
else:
log('DInsert', 'inserting before', line.strip())
if extra_topic:
lines.append(f'- {extra_topic[0]}\n')
lines.append('\t' + link + '\n')
else:
lines.append(link + '\n')
else:
# look for matching header
m = re.match(r'#+ *(.*)', line)
# log('DHead', m[1] if m else 'no match')
if not m:
pass
elif m[1].lower() == 'to sort':
found_topic = True
extra_topic = topic_list
log('IToSort', 'missing topic', info.topic)
else:
for i, part in enumerate(topic_list):
if m[1].lower() == part.lower():
found_topic = True
extra_topic = topic_list[i+1:]
log('DSection', 'found topic', info.topic, 'extra=', extra_topic)
lines.append(line)
if not found_line:
raise RuntimeError('EBadMerge')
with open(OUT_PATH, 'w') as f:
f.write(''.join(lines))
def semantic_merge(srcpr):
"""Semantic Merge.
Add new entries into markdown file manually. We do this
because git auto-merge never works and can cause issues,
especially if a .gitattributes file specifies `driver=union`.
"""
print('SEMANTIC_MERGE:\n')
info = build_pull_info(srcpr)
destpr = get_destpr(info)
sh(f'git checkout --no-guess -q {info.branch}')
log('DMerge', 'attempting semantic merge')
if info.error:
log('WExtra', 'cannot manage PRs with errors')
sh('git merge --abort')
return
#sh('rm .gitattributes', check=False)
sh('git merge -q -X theirs --no-commit --no-stat main >/dev/null', check=False)
sh('test -f readme.md && git rm readme.md', check=False)
sh(f'git checkout main {OUT_PATH}')
for url in info.links:
link = get_list_info(url)
if link.status == 'new':
add_link(link)
if 0 == sh_code('git diff --quiet'):
log('WMerge', 'no differences')
msg = quote(f'Merge {destpr} {info.title}')
sh(f'git commit -m {msg} -a')
sh(f'git checkout -q main && git push -q -u origin {info.branch}')
log('IMerge', 'done')
def show_diff(srcpr):
info = build_pull_info(srcpr)
diff = sh_out(f'git diff -U1 --color=always main..{info.branch} | tail -n +5')
print('\nDIFF:\n\n', indent(diff, ' '))
def copy_ghpr(srcpr):
"""Copy pull description and comments."""
print('\nCOPY GHPR:\n')
if srcpr.repo == DEST_REPO:
log('WPullCopy', 'not copying into same repo')
write_pull_desc(srcpr)
return
destpr = copy_pull_desc(srcpr)
copy_issue_comments(srcpr, destpr)
copy_review_comments(srcpr, destpr)
dest = gh.pulls.get(**destpr.gh)
log('IPullCopy', dest.html_url)
def write_pull_desc(srcpr):
"""Create pull description for existing PR."""
pull = gh.pulls.get(**srcpr.gh)
body = ''
for line in str(build_pull_info(srcpr)).strip().splitlines():
body += line + '\n'
body = strip_junk(body)
body = clean_body(srcpr, body, tag_repos=args.tag, pull_desc=args.tag)
# copy original PR description above line
above = ''
for line in pull.body.splitlines():
if line == '---':
break
else:
above += line + '\n'
body = above + '\n---\n\n' + body
log('IPull', 'updating PR', pull.number)
gh.pulls.update(
**DEST_REPO.gh,
pull_number=srcpr.num,
body=body,
)
def copy_pull_desc(srcpr) -> Pull:
"""Create or update PR in github, except comments.
Return destpr.
"""
ver = 6
key = f'copy/{srcpr.key}'
rec = db.get(key)
if not rec:
redo = 'new'
rec = {'idmap': {}, 'ver': 0, 'tag': False}
elif 'copy' in args.redo:
redo = 'force'
elif rec['ver'] < ver:
redo = 'update'
elif args.tag and not rec['tag']:
redo = 'add-tag'
else:
log('DCached', key, rec)
return Pull('origin', rec['num'])
# do not remove tags once added
rec['tag'] = rec['tag'] or args.tag
log('ICalc', redo, key, rec)
orig = gh.pulls.get(**srcpr.gh)
body = f'**Pull request** from @{orig.user.login}:\n\n'
info = build_pull_info(srcpr)
for line in str(info).strip().splitlines():
body += line + '\n'
if orig.body:
body += '\n---\n' + orig.body.strip()
body = strip_junk(body)
body = clean_body(srcpr, body, tag_repos=rec['tag'], pull_desc=rec['tag'])
destpr = get_destpr(info)
if destpr:
log('IPull', 'updating PR', destpr.num)
gh.pulls.update(
**destpr.gh,
title=orig.title,
body=body,
)
else:
log('IPull', 'creating new PR', info.branch)
sh(f'git push -q -u origin {info.branch}')
pr = gh.pulls.create(
**DEST_REPO.gh,
title=orig.title,
body=body,
head=info.branch, # "rajee-a:patch-1",
base="main",
)
throttle()
destpr = Pull('origin', pr.number)
rec['num'] = destpr.num
rec['ver'] = ver
db.set(key, rec)
return destpr
def get_destpr(prinfo: PullInfo):
"""Find existing destpr for srcpr."""
pulls = gh.pulls.list(
**DEST_REPO.gh,
state='all',
head=f'{DEST_REPO.owner}:{prinfo.branch}',
sort='created',
direction='desc',
)
if pulls:
return Pull('origin', pulls[0].number)
def copy_issue_comments(srcpr, destpr):
ver = 3
key = f'dest/pull/{destpr.num}/comments'
rec = db.get(key)
if not rec:
redo = 'new'
rec = {'idmap': {}}
elif 'comments' in args.redo:
redo = 'force'
elif rec.get('ver', 0) < ver:
redo = 'update'
elif args.tag and not rec.get('tag'):
redo = 'add-tag'
else:
log('DCached', key, rec)
return 'DONE'
# do not remove tags once added
rec['tag'] = rec.get('tag') or args.tag
log('ICalc', redo, key, rec)
if not rec['idmap']:
# delete old comments
for c in all_pages(gh.issues.list_comments, **destpr.gh):
log('IDel', c.id, c.user.login)
gh.issues.delete_comment(**destpr.gh, comment_id=c.id)
for c in all_pages(gh.issues.list_comments, **srcpr.gh):
new_id = rec['idmap'].get(str(c.id))
body = attr_body(srcpr, c, tag_repos=rec['tag'])
if new_id:
cmt = gh.issues.update_comment(
**destpr.gh,
comment_id=new_id,
body=body,
)
else:
cmt = gh.issues.create_comment(
**destpr.gh,
body=body,
)
rec['idmap'][c.id] = cmt.id
log('IEdit', 'edit' if new_id else 'new', c.id, '→', cmt.id, c.user.login)
throttle(1)
rec['ver'] = ver
db.set(key, rec)
def copy_review_comments(srcpr, destpr):
ver = 1
key = f'dest/pull/{destpr.num}/review_comments'
rec = db.get(key)
if not rec:
redo = 'new'
rec = {'idmap': {}}
elif 'comments' in args.redo:
redo = 'force'
elif rec.get('ver', 0) < ver:
redo = 'update'
elif args.tag and not rec.get('tag'):
redo = 'add-tag'
else:
log('DCached', key, rec)
return 'DONE'
# do not remove tags once added
rec['tag'] = rec.get('tag') or args.tag
log('ICalc', redo, key, rec)
if not rec['idmap']:
# delete old comments
for c in all_pages(gh.pulls.list_review_comments, **destpr.gh):
log('IDel', c.id, c.user.login)
gh.pulls.delete_review_comment(**destpr.gh, comment_id=c.id)
for c in all_pages(gh.pulls.list_review_comments, **srcpr.gh):
new_id = rec['idmap'].get(str(c.id))
in_reply_to = rec['idmap'].get(str(getattr(c, 'in_reply_to_id', None)))
body = attr_body(srcpr, c, tag_repos=rec['tag'])
if new_id:
cmt = gh.pulls.update_review_comment(
**destpr.gh,
comment_id=new_id,
body=body,
)
else:
if c.line is None and c.original_line:
pos = dict(
commit_id=c.original_commit_id,
line=c.original_line,
start_line=c.original_start_line,
)
else:
pos = dict(
commit_id=c.commit_id,
line=c.line,
start_line=c.start_line,
)
try:
cmt = gh.pulls.create_review_comment(
**destpr.gh,
**pos,
body=body,
in_reply_to=in_reply_to,
path=c.path,
side=c.side,
start_side=c.start_side,
)
rec['idmap'][c.id] = cmt.id
except HTTPError as e:
log('WReviewComment', e)
continue
log('ICmt', cmt.id, cmt.user.login, cmt.line)
throttle(1)
rec['ver'] = ver
db.set(key, rec)
def attr_body(srcpr, comment, tag_repos=False):
when = datetime.strptime(comment.created_at, '%Y-%m-%dT%H:%M:%S%z')
out = f'**@-{comment.user.login}** on {when:%Y-%m-%d %H:%M} says: '
if comment.body.strip().startswith('>'):
out += '\n'
out += clean_body(srcpr, comment.body, tag_repos=tag_repos)
return out
def clean_body(srcpr, body, tag_repos=False, pull_desc=False):
"""Avoid tagging users/issues for every comment.
See "auto linked references" in github docs.
If pull_desc is True, leave references to users.
"""
# tag user in body, except sind.*
if pull_desc:
out = re.sub(r'@(sind.*)', r'**@-\1**', body)
else:
out = re.sub(r'@(\w[-\w]+)', r'**@-\1**', body)
# adjust naked references to original repo
out = re.sub(r'(?<!\w)#([0-9]+)', rf'{srcpr.repo}#\1', out)
# strip out auto-linked references
if not tag_repos:
out = re.sub(r'([^ ]+)#(\d+)', r'**\1#-\2**', out)
out = re.sub(
r'https?://github.com/([^/ ]+)/([^/ ]+)/(?:pull|issues)/(\d+)',
r'**\1/\2#-\3**', out)
# always strip out refences to upstream repo in comments
if not pull_desc:
out = re.sub(rf'({srcpr.repo})#(\d+)', r'**\1#-\2**', out)
return out.strip()
def test_clean_body():
repo = Repo('xxx', 'yyy')
srcpr = Pull(repo, 2060)
# basic
out = clean_body(srcpr, 'list: https://github.com/xxx/yyy/pull/1497')
assert out == 'list: **xxx/yyy#-1497**'
# with tag_repos=False
assert 'in **xxx/yyy#-1245** but' == clean_body(srcpr, 'in #1245 but')
assert '**but#-333**' == clean_body(srcpr, 'but#333')
assert '**xxx/yyy#-123**' == clean_body(srcpr, '#123')
# with tag_repos=True
assert 'but#333' == clean_body(srcpr, 'but#333', tag_repos=True)
# with pull_desc=False
assert '**@-maehr**.' == clean_body(srcpr, '@maehr.')
assert 'see **xxx/yyy#-1363**.' == clean_body(srcpr, 'see xxx/yyy#1363.')
# with pull_desc=True
assert '@maehr.' == clean_body(srcpr, '@maehr.', pull_desc=True)
assert '**@-sindre.**' == clean_body(srcpr, '@sindre.', pull_desc=True)
assert 'see xxx/yyy#1363.' == clean_body(srcpr, 'see xxx/yyy#1363.',
tag_repos=True, pull_desc=True)
def strip_junk(body):
out = body
out = re.sub(
r'## Requirements for your pull request.*',
'\\[ boilerplate snipped \\]', out, flags=re.S)
out = re.sub(
r'#+ By submitting this pull .*',
'\\[ boilerplate snipped \\]', out, flags=re.S)
out = re.sub(