-
Notifications
You must be signed in to change notification settings - Fork 7
/
__main__.py
2494 lines (2203 loc) · 142 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2019 Philip Starkey
#
# This file is part of bitbucket-hg-exporter.
# https://github.com/philipstarkey/bitbucket-hg-exporter
#
# bitbucket-hg-exporter is distributed under the GPLv3.
# See the LICENSE file in the GitHub repository for further details.
import argparse
from collections import OrderedDict
import copy
import datetime
import gc
import getpass
import html
import json
import queue
import re
import requests
import threading
import time
import os
import shutil
import subprocess
import sys
from urllib import parse
#from OpenSSL.SSL import SysCallError
from distutils.dir_util import copy_tree
from . import hg2git
from . import __version__ as software_version
from .issue_migrate import import_issues_to_github
bitbucket_api_url = 'https://api.bitbucket.org/2.0/'
github_api_url = 'https://api.github.com/'
def pad_message(msg):
width = shutil.get_terminal_size()[0]
msg += " "*(width-len(msg)%width-1)
return msg
# setup signal handling to terminate threads nicely when
# this process is terminated
import signal
ABORT_EVENT = threading.Event()
_REGISTERED_THREADS = {}
_previous_sigint = signal.getsignal(signal.SIGINT)
_previous_sigterm = signal.getsignal(signal.SIGTERM)
# _previous_sigkill = signal.getsignal(signal.SIGKILL)
def _kill_threads_nicely(signum, frame):
print(pad_message('Signal received. Attempting to end threads nicely (this may take up to 2 seconds per thread)'))
ABORT_EVENT.set()
# Wait for threads to end with a timeout...
for name, thread in _REGISTERED_THREADS.items():
if thread.is_alive():
thread.join(2)
if thread.is_alive():
print(pad_message('WARNING: Thread {} did not terminate nicely'.format(name)))
else:
print(pad_message('Thread {} ended nicely'.format(name)))
if signum == signal.SIGINT and _previous_sigint not in [None, signal.SIG_IGN, signal.SIG_DFL]:
_previous_sigint(signum, frame)
if signum == signal.SIGTERM and _previous_sigterm not in [None, signal.SIG_IGN, signal.SIG_DFL]:
_previous_sigterm(signum, frame)
# if signum == signal.SIGKILL and _previous_sigkill not in [None, signal.SIG_IGN, signal.SIG_DFL]:
# _previous_sigkill(signum, frame)
# force terminate
os._exit(1)
signal.signal(signal.SIGINT, _kill_threads_nicely)
signal.signal(signal.SIGTERM, _kill_threads_nicely)
def bb_endpoint_to_full_url(endpoint):
return bitbucket_api_url + endpoint
def gh_endpoint_to_full_url(endpoint):
return github_api_url + endpoint
def full_url_to_query(url):
split_data = parse.urlsplit(url)
params = parse.parse_qs(split_data.query)
endpoint = parse.urlunsplit(list(split_data[0:3])+['',''])
return endpoint, params
def bb_query_api(endpoint, auth, params=None):
if not endpoint.startswith('https://'):
endpoint = bb_endpoint_to_full_url(endpoint)
endpoint, orig_params = full_url_to_query(endpoint)
if params is not None:
orig_params.update(params)
# Catch the API limit
retry = True
retry_count = 0
response = None
while retry:
try:
response = requests.get(endpoint, params=orig_params, auth=auth)
if response.status_code == 429:
retry_count += 1
if retry_count%5 == 4:
mins_wait = retry_count//5 + 1
print(pad_message('({}) BitBucket API limit likely exceeded. Will retry in {} mins...'.format(auth[0], mins_wait)))
# TODO: make this a sleep(1) in a loop that checks elapsed time, so that PC hibernate negates the sleep
time.sleep(60*mins_wait)
else:
time.sleep(5)
continue
retry = False
except (requests.exceptions.SSLError, requests.exceptions.ConnectionError):
retry_count += 1
if retry_count%5 == 4:
mins_wait = retry_count//5 + 1
print(pad_message('({}) BitBucket API limit likely exceeded. Will retry in {} mins...'.format(auth[0], mins_wait)))
# TODO: make this a sleep(1) in a loop that checks elapsed time, so that PC hibernate negates the sleep
time.sleep(60*mins_wait)
else:
time.sleep(5)
continue
except BaseException:
# retry = False
raise
if ABORT_EVENT.is_set():
raise RuntimeError('Raising exception so that the thread ends sooner')
return response
def bbapi_json(endpoint, auth, params=None):
response = bb_query_api(endpoint, auth, params)
try:
json_response = response.json()
except BaseException:
json_response = None
return response.status_code, json_response
def gh_query_api(endpoint, auth, params=None, data=None, headers=None):
if not endpoint.startswith('https://'):
endpoint = gh_endpoint_to_full_url(endpoint)
endpoint, orig_params = full_url_to_query(endpoint)
if params is not None:
orig_params.update(params)
# Catch the API limit
retry = True
response = None
while retry:
try:
response = requests.get(endpoint, params=orig_params, auth=auth, data=data, headers=headers)
retry = False
except requests.exceptions.SSLError:
print('API limit likely exceeded. Will retry in 5 mins...')
time.sleep(60*5)
except BaseException:
# retry = False
raise
return response
def ghapi_json(endpoint, auth, params=None, data=None, headers=None):
response = gh_query_api(endpoint, auth, params=params, data=data, headers=headers)
try:
json_response = response.json()
except BaseException:
json_response = None
return response.status_code, json_response
def flatten_comments(hierarchy, comments, reordered_comments, depth=0):
for h in hierarchy.values():
c = comments[h['index']]
# Add a depth counter so we know how far to indent, epecially if it's breaking nested commenst across pages
if "parent" in c:
c['parent']['depth'] = depth
reordered_comments.append(c)
flatten_comments(h['children'], comments, reordered_comments, depth=depth+1)
return reordered_comments
def get_all_pages(data_directory, first_filepath):
files = []
while first_filepath is not None:
with open(os.path.join(data_directory, *first_filepath.split('/')), 'r') as f:
data = json.load(f)
files.append(first_filepath)
first_filepath = data.get('next')
return files
import keyring
KEYRING_SERVICES = {
'bitbucket': 'bitbucket-to-github-exporter/bitbucket',
'github': 'bitbucket-to-github-exporter/github',
}
SERVICE_CHECKS = {
'bitbucket': lambda credentials: bbapi_json('user', credentials),
'github': lambda credentials: ghapi_json('user', credentials),
}
import questionary as q
class MigrationProject(object):
def __init__(self):
self.__auth_credentials = {}
for service in KEYRING_SERVICES:
self.__auth_credentials[service] = {}
self.__settings = {
'project_name': '',
'project_path': '',
'master_bitbucket_username': '',
'bitbucket_repo_owner': '',
'bitbucket_repo_project': None,
'bb_repositories_to_export': [],
'backup_issues': True,
'backup_pull_requests': True,
'backup_commit_comments': True,
'backup_forks': True,
'generate_static_issue_pages': True,
'generate_static_pull_request_pages': True,
'generate_static_commit_comments_pages': True,
'bitbucket_additional_users': [],
'fork_search_complete': False,
'bitbucket_api_download_complete': False,
# 'bitbucket_api_URL_replace_complete': False,
'bitbucket_api_download_complete_list': [],
'bitbucket_hg_download_complete': False,
'import_to_github': True,
'master_github_username': '',
'github_owner': '',
'github_user_mapping_path': '',
'bb_gh_user_mapping': {},
'github_import_issues': True,
'github_publish_pages': True,
'github_pages_repo_name': '',
'github_pages_url_type': 0,
'github_pages_custom_url': '',
'github_rewrite_additional_URLs': False,
'github_URL_rewrite_file_path': '',
'github_import_forks': True,
'github_import_forks_to': None,
'github_existing_repositories': {},
'hg_to_git_tool': 'github',
'local_git_repos_pushed': [],
# 'github_import_complete': False,
'github_git_download_complete': False,
'github_issue_import_complete': False,
'reorder_comments_complete': False,
'hash_link_complete': False,
}
p = argparse.ArgumentParser()
p.add_argument('--load', action='store_true')
p.add_argument('--storage-dir')
p.add_argument('--project-name')
arguments = p.parse_args()
choices = {"Start new project":0, "Load project":1}
if arguments.load:
response=list(choices.keys())[1]
else:
# prompt for new/load
response = q.select("What do you want to do?", choices=choices.keys()).ask()
if choices[response] == 0:
self.__start_project()
elif choices[response] == 1:
kwargs = {}
if arguments.storage_dir is not None:
kwargs['location'] = arguments.storage_dir
if arguments.project_name is not None:
kwargs['project'] = arguments.project_name
self.__load_project(**kwargs)
else:
raise RuntimeError('Unknown option selected')
def __load_project(self, location=os.getcwd(), project=None):
project_found = False
first_run = True
while not project_found:
if not first_run or location == os.getcwd():
location = q.text("Where is the project folder located?", default=location).ask()
if not first_run or project is None:
project_name = q.select("Select a project to load?", choices=sorted(os.listdir(location))).ask()
elif first_run and project is not None:
project_name = project
path = os.path.join(location, project_name, 'project.json')
if os.path.exists(path):
try:
with open(path, 'r') as f:
self.__settings.update(json.load(f))
project_found = True
except BaseException:
print('Could not load project.json file in {}. It may be corrupted. Please check the formatting and try again'.format(path))
else:
print('Could not find {}. Please select a differet folder.'.format(path))
first_run = False
# make sure we have a password/token or ask for it
self.__get_password('bitbucket', self.__settings['master_bitbucket_username'], silent=False)
self.__confirm_project_settings(load=True)
def __start_project(self):
# Get the project name and save loction
while not self.__get_project_name():
print('Could not create a migration project. Please ensure you have write permissions at the specified location and that the project name is unique')
# Get the Information on the BitBucket repo(s) to migrate
self.__get_bitbucket_info()
# find out what we should be saving
self.__get_backup_options()
# questions about import to GitHub
self.__get_github_import_options()
self.__confirm_project_settings()
def __confirm_project_settings(self, load=False):
# confirm settings before beginning
while not self.__print_project_settings():
choices = {
"Change primary BitBucket credentials":0,
"Add/remove additional BitBucket credentials":1,
"Change BitBucket repositories to export":2,
"Change export settings":3,
"Change primary GitHub credentials":4,
"Change GitHub import settings":5,
}
if load:
choices["Load different project"] = 6
response = q.select("What would you like to change?", choices=choices.keys()).ask()
if choices[response] == 0:
self.__get_master_bitbucket_credentials(force_new_password=True)
elif choices[response] == 1:
self.__get_additional_bitbucket_credentials()
elif choices[response] == 2:
while not self.__get_bitbucket_repositories():
pass
elif choices[response] == 3:
self.__get_backup_options()
elif choices[response] == 4:
self.__get_master_github_credentials(force_new_password=True)
elif choices[response] == 5:
self.__get_github_import_options()
elif choices[response] == 6:
self.__load_project()
else:
raise RuntimeError('Unknown option selected')
# save the project
self.__save_project_settings()
# prompt to start project
print('Project configuration saved!')
#TODO: make resume have nicer text prompts
choices = {
"Start export":0,
"Exit":1,
}
response = q.select("What would you like to do?", choices=choices.keys()).ask()
if choices[response] == 0:
faq_read = q.confirm("I have read the entire readme at https://github.com/philipstarkey/bitbucket-hg-exporter (including the FAQ) and understood the caveats listed. I understand that I use this tool at my own risk. Answer 'Y' for agree or 'N' to terminate the program:", default=False).ask()
if not faq_read:
sys.exit(1)
# load the user mapping
if self.__settings['github_user_mapping_path']:
while True:
try:
with open(self.__settings['github_user_mapping_path'], 'r') as f:
data = json.load(f)
if not isinstance(data, dict):
raise RuntimeError('')
self.__settings['bb_gh_user_mapping'] = data
break
except BaseException:
try_again = q.confirm('Could not load bitbucket to github user mapping file. Check it is a JSON dictionary containing bitbucket:github user key pairs. Would you like to try loading it again?').ask()
if not try_again:
break
owner = self.__settings['bitbucket_repo_owner']
auth = (self.__settings['master_bitbucket_username'], self.__get_password('bitbucket', self.__settings['master_bitbucket_username']))
# this is a new setting, so people upgrading need to have it set to the prior behaviour
if self.__settings['github_import_forks_to'] is None:
self.__settings['github_import_forks_to'] = self.__settings['github_owner']
self.__save_project_settings()
all_repo_names = [repository['full_name'] for repository in self.__settings['bb_repositories_to_export']]
initial_num_repos = len(all_repo_names)
def recursively_process_repositories(repository):
if 'links' not in repository or 'forks' not in repository['links'] or 'href' not in repository['links']['forks']:
return
status, json_response = bbapi_json(repository['links']['forks']['href'], auth, {'pagelen':100})
more = True
while more:
if status == 200 and json_response is not None:
# process repositories (don't add duplicates)
for r in json_response['values']:
if r['full_name'] not in all_repo_names:
r['is_fork'] = True
self.__settings['bb_repositories_to_export'].append(r)
all_repo_names.append(r['full_name'])
print('Finding all forks of {}'.format(r['full_name']))
recursively_process_repositories(r)
if 'next' in json_response:
status, json_response = bbapi_json(json_response['next'], auth, {'pagelen':100})
else:
more = False
elif status == 404:
# some forks might have been deleted, but they are still reported by Bitbucket API
# report the error and keep enumerating forks (of the remaining repos)
print('Warning: repository {} might have been deleted (404).'.format(repository['full_name']))
more = False
else:
print('Failed to query BitBucket API when determining forks for {}.'.format(repository['full_name']))
sys.exit(1)
if self.__settings['backup_forks']:
if self.__settings['fork_search_complete']:
search = q.confirm('A previous run of this script determined the list of all repository forks. Would you like to search for any new forks since the last run?', default=False).ask()
else:
search = True
if search:
for repository in self.__settings['bb_repositories_to_export']:
# recursively get list of all forks
print('Finding all forks of {}'.format(repository['full_name']))
recursively_process_repositories(repository)
self.__settings['fork_search_complete'] = True
else:
# remove forks
self.__settings['bb_repositories_to_export'] = [repository for repository in self.__settings['bb_repositories_to_export'] if 'is_fork' not in repository or not repository['is_fork']]
self.__settings['fork_search_complete'] = False
# TODO: Should we clean up files left over from fork backup?
self.__save_project_settings()
# if we've added new forks, then we need to download them
if len(self.__settings['bb_repositories_to_export']) > initial_num_repos:
self.__settings['bitbucket_api_download_complete'] = False
# self.__settings['bitbucket_api_URL_replace_complete'] = False
if not self.__settings['bitbucket_api_download_complete']:
import colorama
colorama.init()
auth_list = [auth] + [(user, self.__get_password('bitbucket', user)) for user in self.__settings['bitbucket_additional_users']]
message_queue = queue.Queue()
subset = [[] for _ in auth_list]
threads = {}
latest_messages = ['' for _ in auth_list]
needs_processing = [repo for repo in self.__settings['bb_repositories_to_export'] if repo['full_name'] not in self.__settings['bitbucket_api_download_complete_list']]
for i, repository in enumerate(needs_processing):
subset[i%len(auth_list)].append(repository['full_name'])
def thread_fn(i, message_queue, credentials):
exporter = BitBucketExport(owner, credentials, copy.deepcopy(self.__settings), lambda cmd, message, i=i, q=message_queue:message_queue.put((i,cmd,message)), subset=subset[i])
exporter.backup_api()
message_queue.put((i, 'finished', ''))
for i, credentials in enumerate(auth_list):
t = threading.Thread(target=thread_fn, args=(i, message_queue, credentials))
t.daemon = True
_REGISTERED_THREADS["Thread {} ({})".format(i, credentials[0])] = t
t.start()
threads[i] = t
last_update_time = time.time()-1
overwrite_last_lines = True
while threads:
force = False
try:
i, cmd, message = message_queue.get(timeout=0.25)
except queue.Empty:
pass
else:
if cmd == 'update':
if len(message) == 3:
force = message[2]
if message[1] == '\n':
print(pad_message("Thread {} ({}): {}".format(i, auth_list[i][0], message[0])))
# overwrite_last_lines = False
force = True
else:
latest_messages[i] = message[0]
elif cmd == 'complete':
self.__settings['bitbucket_api_download_complete_list'].append(message)
self.__save_project_settings()
elif cmd == 'finished':
del threads[i]
force = True
if time.time() - last_update_time > 0.25 or force:
last_update_time = time.time()
pm = '\n'.join([pad_message("Thread {} ({}): {}".format(i, auth_list[i][0], m)) for i,m in enumerate(latest_messages)])
end = '\n'
if overwrite_last_lines and threads:
# calculate number of links to move up
# lines = len(auth_list)
lines = (len(pm)+1)//shutil.get_terminal_size()[0]
pm += '\x1b[%d;%dH'%(shutil.get_terminal_size()[1]-lines+1, 1) #+ pm
end = ''
print(pm, end=end)
overwrite_last_lines = True
self.__settings['bitbucket_api_download_complete'] = True
self.__save_project_settings()
colorama.deinit()
# clone the Hg repos (including forks if specified)
do_hg_pull = True
if self.__settings['bitbucket_hg_download_complete']:
do_hg_pull = q.confirm("hg repositories were pulled during a previous run of this script. Do you want to update them?", default=False).ask()
logs = {}
for repository in self.__settings['bb_repositories_to_export']:
print('Processing mercurial repository {}'.format(repository['full_name']))
# TODO: use password from mercurial_keyring (which I think means saving an additional keyring entry with
# name and username as <username>@@<repo_url>)
clone_dest = os.path.join(self.__settings['project_path'], 'hg-repos', *repository['full_name'].split('/'))
clone_url = None
for clone_link in repository['links']['clone']:
if clone_link['name'] == 'https':
clone_url = clone_link['href']
break
if clone_url is None:
print('Failed to determine clone URL for BitBucket repository {}'.format(repository['full_name']))
sys.exit(1)
clone_dests = [(clone_dest, clone_url)]
# add path to wiki repository if it has one
if repository['has_wiki']:
clone_dests.append((clone_dest+'-wiki', clone_url+'/wiki'))
for clone_dest, clone_url in clone_dests:
if not os.path.exists(os.path.join(clone_dest, '.hg', 'hgrc')):
p=subprocess.Popen(['hg', 'clone', clone_url, clone_dest])
p.communicate()
if p.returncode:
print('Failed to hg clone {}'.format(clone_url))
sys.exit(1)
elif do_hg_pull:
p=subprocess.Popen(['hg', 'pull', '-R', clone_dest])
p.communicate()
if p.returncode:
print('Failed to hg update (pull) from {}'.format(clone_url))
sys.exit(1)
# Generate mapping for rewriting changesets and other items
logs[repository['full_name']] = {'hg': hg2git.get_hg_log(clone_dests[0][0])}
self.__settings['bitbucket_hg_download_complete'] = True
self.__save_project_settings()
github_auth = ('', '') # empty values. Will be filled in if we are actually using GitHub (see a few lines below)
github_headers = {"Accept": "application/vnd.github.barred-rock-preview"}
# If needed, import all repositories to GitHub
if self.__settings['import_to_github']:
github_auth = (self.__settings['master_github_username'], self.__get_password('github', self.__settings['master_github_username']))
if self.__settings['hg_to_git_tool'] == 'github':
for repository in self.__settings['bb_repositories_to_export']:
# skip forks if we are not importing them to github
if not self.__settings['github_import_forks']:
if 'is_fork' in repository and repository['is_fork']:
continue
# update status if we are in an error condition as this determines whether we should try again and we need to make sure we are not working from stale data
if repository['full_name'] in self.__settings['github_existing_repositories'] and self.__settings['github_existing_repositories'][repository['full_name']]['import_started'] and 'import_status' in self.__settings['github_existing_repositories'][repository['full_name']] and self.__settings['github_existing_repositories'][repository['full_name']]['import_status']['status'] == 'error':
import_status_check = requests.get(self.__settings['github_existing_repositories'][repository['full_name']]['import_url'], auth=github_auth, headers=github_headers)
if import_status_check.status_code == 200:
self.__settings['github_existing_repositories'][repository['full_name']]['import_status'] = import_status_check.json()
else:
pass
# handle this nicely
main_condition = repository['full_name'] not in self.__settings['github_existing_repositories'] or not self.__settings['github_existing_repositories'][repository['full_name']]['import_started']
error_condition = False
if not main_condition:
error_condition = ('import_status' in self.__settings['github_existing_repositories'][repository['full_name']] and self.__settings['github_existing_repositories'][repository['full_name']]['import_status']['status'] == 'error' and self.__settings['github_existing_repositories'][repository['full_name']]['import_status'].get("message", '') != "The imported repository is empty.")
if main_condition or error_condition:
clone_url = None
for clone_link in repository['links']['clone']:
if clone_link['name'] == 'https':
clone_url = clone_link['href']
break
if clone_url is None:
print('Failed to determine clone URL for BitBucket repository {}'.format(repository['full_name']))
sys.exit(1)
github_slug = self.create_github_slug(repository)
# Need to create the repository first! This should allow us to make it private! Yay!
# check if repository already exists
owner = self.__settings['github_import_forks_to'] if 'is_fork' in repository and repository['is_fork'] else self.__settings['github_owner']
if repository['full_name'] not in self.__settings['github_existing_repositories']:
response = self.create_or_get_github_repository(owner, github_slug, repository, github_auth)
self.__settings['github_existing_repositories'][repository['full_name']] = {
'name': '{owner}/{repo_name}'.format(owner=owner, repo_name=github_slug),
'repository': response,
'import_started': False,
'import_completed': False
}
self.__save_project_settings()
# cancel any error requests
if error_condition:
print('Cancelling import for repository {owner}/{repo_name}) as it was in an error state. We will re-request the import shortly.'.format(owner=owner, repo_name=github_slug))
response = requests.delete('https://api.github.com/repos/{owner}/{repo_name}/import'.format(owner=owner, repo_name=github_slug), auth=github_auth, headers=github_headers)
if response.status_code != 204:
print('WARNING: Failed to cancel import with error state (repository: {owner}/{repo_name}). We suggest visiting github.com/{owner}/{repo_name} and attempting to restart the import from there.'.format(owner=owner, repo_name=github_slug))
continue
# generate import request to GitHub
# TODO: Make this work for private repositories
# Need to confirm with user that they are happy for their BitBucket credentials to be given to GitHub
params = {
"vcs": "mercurial",
"vcs_url": clone_url,
# "vcs_username": auth[0],
# "vcs_password": auth[1]
}
print('Requesting source import for repository {}/{}'.format(owner, github_slug))
response = requests.put('https://api.github.com/repos/{owner}/{repo_name}/import'.format(owner=owner, repo_name=github_slug), auth=github_auth, headers=github_headers, json=params)
if response.status_code != 201:
print('Failed to import BitBucket repository {} to GitHub. Response code was: {}'.format(repository['full_name'], response.status_code))
sys.exit(1)
self.__settings['github_existing_repositories'][repository['full_name']].update({
'initial_import_response': response.json(),
'import_url': 'https://api.github.com/repos/{owner}/{repo_name}/import'.format(owner=owner, repo_name=github_slug),
'import_started': True,
})
self.__save_project_settings()
# enable LFS
response = requests.patch('https://api.github.com/repos/{owner}/{repo_name}/import/lfs'.format(owner=owner, repo_name=github_slug), auth=github_auth, headers=github_headers, json={"use_lfs": "opt_in"})
# wait for all imports to complete
all_finished = False
while not all_finished:
all_finished = True
for bitbucket_name, github_data in self.__settings['github_existing_repositories'].items():
if 'initial_import_response' not in github_data:
# A hack to handle repos that already existed and were not imported
# (we use this URL later when cloning the GitHub repo)
github_data['import_status'] = {}
github_data['import_status']['repository_url'] = 'https://api.github.com/repos/'+github_data['name']
# Skip checking imprt status for repos we didn't import ourselves
continue
if 'import_status' not in github_data or github_data['import_status']['status'] != 'complete':
# get the current status
response = requests.get(github_data['import_url'], auth=github_auth, headers=github_headers)
if response.status_code != 200:
all_finished = False
print('Failed to check status of import to {}. Will try again next loop.'.format(github_data['name']))
continue
github_data['import_status'] = response.json()
empty_repo = (github_data['import_status']['status'] == 'error' and github_data['import_status'].get("message", '') == "The imported repository is empty.")
if github_data['import_status']['status'] != 'complete' and not empty_repo:
print('Waiting on {} to complete. Current status is: {}'.format(github_data['name'],github_data['import_status']['status_text']))
all_finished = False
else:
github_data['import_completed'] = True
self.__save_project_settings()
if not all_finished:
print('sleeping for 30 seconds...')
time.sleep(30)
elif self.__settings['hg_to_git_tool'] == 'local':
# TODO: Write this
repo_mapping = {}
for repository in self.__settings['bb_repositories_to_export']:
# skip forks if we are not importing them to github
if not self.__settings['github_import_forks']:
if 'is_fork' in repository and repository['is_fork']:
continue
github_slug = self.create_github_slug(repository)
owner = self.__settings['github_import_forks_to'] if 'is_fork' in repository and repository['is_fork'] else self.__settings['github_owner']
response = self.create_or_get_github_repository(owner, github_slug, repository, github_auth)
github_repo_name = '{owner}/{repo_name}'.format(owner=owner, repo_name=github_slug)
self.__settings['github_existing_repositories'][repository['full_name']] = {
'name': github_repo_name,
'repository': response,
'import_started': False,
'import_completed': False,
'import_status': {
'repository_url': 'https://api.github.com/repos/'+github_repo_name
}
}
self.__save_project_settings()
hg_clone_dest = os.path.join(self.__settings['project_path'], 'hg-repos', *repository['full_name'].split('/'))
git_clone_dest = os.path.join(self.__settings['project_path'], 'git-repos', *github_repo_name.split('/'))
repo_mapping[hg_clone_dest] = git_clone_dest
# TODO: provide option to skip the mapping file write and user choice if it has been done before
# write out the mapping file
with open(os.path.join(self.__settings['project_path'], 'repo_mapping.json'), 'w') as f:
json.dump(repo_mapping, f, indent=4)
print('A mapping between local mercurial repository and expected git repository locations has been written to "repo_mapping.json" in the project directory.')
print('Please ensure that your local tool creates git repositories in the specified locations before continuing.')
# Pause and continue on user command
choices = {
"Continue (my local tool has produced git repositories in the appropriate location)":0,
"Exit (you can resume this tool later by loading the project and starting the export again)":1,
}
response = q.select("Select an option below:", choices=choices.keys()).ask()
if choices[response] != 0:
sys.exit(0)
# push repositories to git
# git remote add origin https://github.com/<blah>/<blah>
# git push origin --all # All branches
# git push origin --tags # All tags
# git push origin refs/notes/* # All notes
for repository in self.__settings['bb_repositories_to_export']:
# skip forks if we are not importing them to github
if not self.__settings['github_import_forks']:
if 'is_fork' in repository and repository['is_fork']:
continue
github_repo_name = self.__settings['github_existing_repositories'][repository['full_name']]['name']
clone_dest = os.path.join(self.__settings['project_path'], 'git-repos', *github_repo_name.split('/'))
if github_repo_name not in self.__settings['local_git_repos_pushed']:
clone_url = 'https://github.com/{name}'.format(name=github_repo_name)
self.call_git_subprocess('remote', 'add', 'origin', clone_url, cwd=clone_dest, error_message='Failed to add remote for git repository at {path}. Maybe it\'s already been added'.format(path=clone_dest), exit=False)
self.call_git_subprocess('push', 'origin', '--all', cwd=clone_dest, error_message='Failed to push {path} to remote repository'.format(path=clone_dest), retry=True)
self.call_git_subprocess('push', 'origin', '--tags', cwd=clone_dest, error_message='Failed to push tags in {path} to remote repository'.format(path=clone_dest), retry=True)
self.call_git_subprocess('push', 'origin', 'refs/notes/*', cwd=clone_dest, error_message='Failed to push notes in {path} to remote repository'.format(path=clone_dest), retry=True)
self.__settings['local_git_repos_pushed'].append(github_repo_name)
self.__save_project_settings()
# Get any known hg-> git hash mapping from the git notes of the converted repository
logs[repository['full_name']]['git_hg_hashes'] = hg2git.get_hg_hashes_from_git(clone_dest)
else:
print('Unknown conversion hg->git conversion tool specified.')
sys.exit(1)
# TODO: send user mappings
do_git_pull = True
if self.__settings['github_git_download_complete']:
do_git_pull = q.confirm("git repositories were pulled during a previous run of this script. Do you want to update them?", default=False).ask()
# clone the Github repos if needed
for repository in self.__settings['bb_repositories_to_export']:
# skip forks if we are not importing them to github
if not self.__settings['github_import_forks']:
if 'is_fork' in repository and repository['is_fork']:
continue
# get the github repository information
github_data = self.__settings['github_existing_repositories'][repository['full_name']]
response = requests.get(github_data['import_status']['repository_url'], auth=github_auth, headers=github_headers)
if response.status_code != 200:
print('Failed to get GitHub repository information for {}'.format(github_data['name']))
sys.exit(1)
github_data['repository'] = response.json()
self.__save_project_settings()
print('Processing git repository {}'.format(github_data['name']))
# TODO: use password from github keyring?
clone_dest = os.path.join(self.__settings['project_path'], 'git-repos', *github_data['name'].split('/'))
clone_url = github_data['repository']['clone_url']
if not os.path.exists(os.path.join(clone_dest, '.git', 'config')):
self.call_git_subprocess('clone', clone_url, clone_dest, error_message='Failed to git clone {}'.format(clone_url))
# p=subprocess.Popen(['git', 'clone', clone_url, clone_dest])
# p.communicate()
# if p.returncode:
# print('Failed to git clone {}'.format(clone_url))
# sys.exit(1)
# git fetch origin refs/notes/*:refs/notes/*
self.call_git_subprocess('fetch', 'origin', 'refs/notes/*:refs/notes/*', cwd=clone_dest, error_message='Failed to pull notes from remote repository to {path}'.format(path=clone_dest), exit=False)
elif do_git_pull:
if not self.call_git_subprocess('pull', clone_url, cwd=clone_dest, error_message='Failed to git update (pull) from {}'.format(clone_url), exit=False):
print('This is probably because the repository is empty? We\'ll try and continue...')
# p=subprocess.Popen(['git', 'pull', clone_url], cwd=clone_dest)
# p.communicate()
# if p.returncode:
# print('Failed to git update (pull) from {}'.format(clone_url))
# if os.path.exists(os.path.join(clone_dest, '.git', 'index')):
# sys.exit(1)
# else:
# print('This is probably because the repository is empty? We\'ll try and continue...')
# git fetch origin refs/notes/*:refs/notes/*
self.call_git_subprocess('fetch', 'origin', 'refs/notes/*:refs/notes/*', cwd=clone_dest, error_message='Failed to pull notes from remote repository to {path}'.format(path=clone_dest), exit=False)
# Generate mapping for rewriting changesets and other items
logs[repository['full_name']]['git'] = hg2git.get_git_log(clone_dest)
self.__settings['github_git_download_complete'] = True
self.__save_project_settings()
mapping = {}
if self.__settings['import_to_github']:
# Generate the git repo logs
for repository in self.__settings['bb_repositories_to_export']:
# skip forks if we are not importing them to github
if not self.__settings['github_import_forks']:
if 'is_fork' in repository and repository['is_fork']:
continue
# create the mapping
owner = self.__settings['github_import_forks_to'] if 'is_fork' in repository and repository['is_fork'] else self.__settings['github_owner']
# archive_url = 'https://{owner}.github.io/{repo}/'.format(owner=owner, repo=self.__settings['github_pages_repo_name'])
archive_url = self.get_github_pages_url()
archive_url += '/#!/'+repository['full_name']
known_hg_git_mapping = {}
if 'git_hg_hashes' in logs[repository['full_name']]:
known_hg_git_mapping = logs[repository['full_name']]['git_hg_hashes']
mapping[repository['full_name']] = hg2git.BbToGh(logs[repository['full_name']]['hg'], logs[repository['full_name']]['git'], repository['links']['html']['href'], self.__settings['github_existing_repositories'][repository['full_name']]['repository']['html_url'], self.__settings['bb_gh_user_mapping'], archive_url=archive_url, known_hg_git_mapping=known_hg_git_mapping)
# rewrite repository URLS (especiallly inter-repo issues and PRs and forks if appropriate) and changesets
# (also use the additional URLs to rewrite JSON file)
#
# Things we need to handle that probably aren't at the moment
# * markup-less commit references
# * URLS in issues such as links to forks, issues, and changesets (which currently always have a api.bitbucket.org link that is malformed...)
# * decide if we want to rewrite the commit messages in the git repository, which means we need to:
# a) Do it in the order of earlist to latest (since commit hashes will change when we do this)
# b) update the acquired git log with the new hash
# c) Make sure that all the authors are mapped appropriately since force pushing to the github repo will result in you not being able to map any more users.
# Note: This is now done as part of the call to exporter.backup_api() in order to not need to hold the entire structure of the
# BitBucket API (for every repo) in RAM until all repos/forks are downloaded.
#
# rewrite URLS to reference the downloaded ones
# if not self.__settings['bitbucket_api_URL_replace_complete']:
# exporter.make_urls_relative(mapping=mapping)
# self.__settings['bitbucket_api_URL_replace_complete'] = True
# self.__save_project_settings()
# copy the gh-pages template to the project directory
do_copy = True
if os.path.exists(os.path.join(self.__settings['project_path'], 'gh-pages', 'index.html')):
do_copy = q.confirm('Overwrite HTML app for GitHub pages site with latest version?').ask()
if do_copy:
# delete old version
try:
os.remove(os.path.join(self.__settings['project_path'], 'gh-pages', 'index.html'))
except BaseException:
pass
try:
shutil.rmtree(os.path.join(self.__settings['project_path'], 'gh-pages', 'ng'))
except BaseException:
pass
if do_copy:
copy_tree(os.path.join(os.path.dirname(__file__), 'gh-pages-template'), os.path.join(self.__settings['project_path'], 'gh-pages'))
# write out a list of downloaded repos and a link to their top level JSON file and other important JSON files
top_level_repo_data = {}
with open(os.path.join(self.__settings['project_path'], 'gh-pages', 'repos.json'), 'w') as f:
data = {}
for repository in self.__settings['bb_repositories_to_export']:
data[repository['full_name']] = {
'project_file': 'data/repositories/{}.json'.format(repository['full_name']),
'project_path': 'data/repositories/{}/'.format(repository['full_name']),
'is_fork': 'is_fork' in repository and repository['is_fork'],
}
# save github repo location (so we can link to changesets, files, etc)
if repository['full_name'] in self.__settings['github_existing_repositories']:
data[repository['full_name']]['github_repo'] = self.__settings['github_existing_repositories'][repository['full_name']]['repository']['html_url']
# load the top level JSON file for each project as we will use it more than once
data_path = os.path.join(self.__settings['project_path'], 'gh-pages', 'data', 'repositories', *repository['full_name'].split('/'))
pull_request_path = None
with open(data_path + '.json', 'r') as g:
top_level_repo_data[repository['full_name']] = json.load(g)
# if "links" in top_level_repo_data[repository['full_name']]:
# # write out links to issue files, pull requests, etc.
# for link_type in ['issues', 'pullrequests']:
# link_filepaths = get_all_pages(
# os.path.join(self.__settings['project_path'], 'gh-pages'),
# top_level_repo_data[repository['full_name']]['links'].get(link_type, {}).get('href')
# )
# data[repository['full_name']]['{}_files'.format(link_type)] = dict(enumerate(link_filepaths, 1))
json.dump(data, f, indent=4)
with open(os.path.join(self.__settings['project_path'], 'gh-pages', 'user_mapping.json'), 'w') as f:
json.dump(self.__settings['bb_gh_user_mapping'], f, indent=4)
# TODO: write out a site pages list for search indexing
# reprocess:
# * PR comments so they are in a useful order
print('Reordering comments...')
if not self.__settings['reorder_comments_complete']:
for repository in self.__settings['bb_repositories_to_export']:
# open repo.json file, find location of pull requests list
pull_request_path = None
repo_data = top_level_repo_data[repository['full_name']]
if "links" in repo_data and "pullrequests" in repo_data['links'] and 'href' in repo_data['links']['pullrequests']:
pull_request_path = os.path.join(self.__settings['project_path'], 'gh-pages', *repo_data['links']['pullrequests']['href'].split('/'))
# open that file, iterate over each pull requests, and find links to comments
comment_paths = []
while pull_request_path is not None:
with open(pull_request_path, 'r') as f:
pull_requests_data = json.load(f)
for pull_request in pull_requests_data['values']:
if 'links' in pull_request and 'comments' in pull_request['links'] and 'href' in pull_request['links']['comments']:
comment_paths.append(os.path.join(self.__settings['project_path'], 'gh-pages', *pull_request['links']['comments']['href'].split('/')))
if "next" in pull_requests_data:
pull_request_path = os.path.join(self.__settings['project_path'], 'gh-pages', *pull_requests_data['next'].split('/'))
else:
pull_request_path = None
# find location of commit list
if "links" in repo_data and "commits" in repo_data['links'] and 'href' in repo_data['links']['commits']:
pull_request_path = os.path.join(self.__settings['project_path'], 'gh-pages', *repo_data['links']['commits']['href'].split('/'))
# open that file, iterate over each commit, and find links to comments
# TODO: rename variables
while pull_request_path is not None:
with open(pull_request_path, 'r') as f:
pull_requests_data = json.load(f)
for pull_request in pull_requests_data['values']:
if 'links' in pull_request and 'comments' in pull_request['links'] and 'href' in pull_request['links']['comments']:
comment_paths.append(os.path.join(self.__settings['project_path'], 'gh-pages', *pull_request['links']['comments']['href'].split('/')))
if "next" in pull_requests_data:
pull_request_path = os.path.join(self.__settings['project_path'], 'gh-pages', *pull_requests_data['next'].split('/'))
else:
pull_request_path = None
# Note this code now handles both pull requests and commit comments (despite the variable names)
for pull_request_file in comment_paths:
comment_files = [pull_request_file]
comments = []
# Load all comments into RAM, then recursively iterate finding all the ones that have no parent, then all children of the top level, then children of that level, etc. etc. until all comments are placed into a hierarchy.
while pull_request_file:
with open(pull_request_file, 'r') as f:
comment_data = json.load(f)
if 'values' in comment_data:
comments.extend(comment_data['values'])
if 'next' in comment_data:
pull_request_file = os.path.join(self.__settings['project_path'], 'gh-pages', *comment_data['next'].split('/'))
comment_files.append(pull_request_file)
else:
pull_request_file = None
done_idxs = []
all_idxs = [c['id'] for c in comments]
all_parent_idxs = {c['parent']['id']:i for i, c in enumerate(reversed(comments)) if 'parent' in c}
dummy_comments = 0
for parent_idx, insert_index in all_parent_idxs.items():
if parent_idx not in all_idxs:
# insert dummy comment for parent before the comment if it is missing
child_comment = comments[insert_index]
dummy_comment = {
"links": {
"self": {
"href": child_comment['links']['self']['href'].replace(
'/{}.json'.format(child_comment['id']),
'/{}.json'.format(parent_idx)
)
},
"html": {
"href": child_comment['links']['html']['href'].replace(
'#comment-{}'.format(child_comment['id']),
'#comment-{}'.format(parent_idx)
)
}
},
"deleted": False,
"pullrequest": copy.deepcopy(child_comment['pullrequest']),
"content": {
"raw": "This comment could not be backed up from BitBucket, so this dummy comment was inserted in it's place.",
"markup": "markdown",
"html": "<p>This comment could not be backed up from BitBucket, so this dummy comment was inserted in it's place.</p>",
"type": "rendered"
},
"created_on": "1970-01-01T00:00:00.000000+00:00",
"user": {
"display_name": "Unknown User",
"uuid": "{00000000-0000-0000-0000-000000000000}",
"links": {
"self": {