-
Notifications
You must be signed in to change notification settings - Fork 2
/
bitbucket_issues_to_github.py
248 lines (191 loc) · 7.56 KB
/
bitbucket_issues_to_github.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
#!/usr/bin/python
import json
import os
import sys
import requests
import requests_toolbelt # type: ignore
from dateutil import parser
from requests import Request, Response
from requests_toolbelt.utils import dump # type: ignore
from typing import Union, Dict, Any
import config
def repo_url():
return 'https://api.github.com/repos/' + config.TARGET_REPO
def issue_url():
return repo_url() + '/issues'
def do_request(req) -> Response:
prep_req = req.prepare()
s = requests.session()
res = s.send(prep_req)
data = dump.dump_all(res)
print(data.decode('utf-8'))
if not res.ok:
res.raise_for_status()
return res
def read_json_file(f):
json_object = json.load(f)
return json_object
def get_github_access_token() -> Union[str, None]:
if 'GITHUB_ACCESS_TOKEN' in os.environ:
return os.environ['GITHUB_ACCESS_TOKEN']
else:
return None
def do_github_request(req) -> Response:
headers = {'User-Agent': requests_toolbelt.user_agent('bitbucket_issues_to_github', '1.0.0')}
token = get_github_access_token()
if token is not None:
headers['Authorization'] = 'token ' + token
req.headers.update(headers)
return do_request(req)
def query_all_repo_gissues():
# The issues endpoint is a paginated API.
# We need to iterate over all issues to make this script idempotent.
query_url = issue_url()
issues = []
while True:
res = do_github_request(Request('GET', url=query_url, params={'per_page': 100, 'state': 'all'}))
issues.extend(res.json())
if 'next' in res.links:
query_url = res.links['next']['url']
else:
break
return issues
def post_bissue_to_github(bissue):
# We patch the remaining elements right after posting the issue.
incomplete_gissue = {
"title": bissue['title'],
"body": bissue['content'],
}
res = do_github_request(Request('POST', url=issue_url(), json=incomplete_gissue))
full_gissue = res.json()
return full_gissue
def is_gissue_patch_different(gissue, gissue_patch):
if gissue['state'] != gissue_patch['state']:
return True
if gissue['body'] != gissue_patch['body']:
return True
patch_assignees = set(gissue_patch['assignees'])
current_assignees = set(map(lambda assignee: assignee['login'], gissue['assignees']))
if current_assignees != patch_assignees:
return True
patch_labels = set(gissue_patch['labels'])
current_labels = set(map(lambda label: label['name'], gissue['labels']))
if current_labels != patch_labels:
return True
return False
def map_bstatus_to_gstate(bissue):
bstatus = bissue['status']
if bstatus in config.OPEN_ISSUE_STATES:
return 'open'
else:
return 'closed'
def map_bassignee_to_gassignees(bissue):
bassignee = bissue['assignee']
if bassignee is None:
return []
elif bassignee in config.USER_MAPPING:
return [config.USER_MAPPING[bassignee]]
else:
return []
def map_bstatus_to_glabels(bissue, glabels):
bstatus = bissue['status']
if bstatus in config.STATE_MAPPING:
glabels.add(config.STATE_MAPPING[bstatus])
def map_bkind_to_glabels(bissue, glabels):
bkind = bissue['kind']
if bkind in config.KIND_MAPPING:
label = config.KIND_MAPPING[bkind]
else:
label = bkind
glabels.add(label)
def time_string_to_date_string(timestring) -> str:
datetime = parser.parse(timestring)
return datetime.strftime("%Y-%m-%d")
def append_time_label(sb, timestring, label):
sb.append('\n[' + label + ': ' + timestring + ']')
def append_bcomment(sb, bcomment):
content = bcomment['content']
if content is None:
return # There are bitbucket comments without any content. We ignore them.
sb.append('\n')
comment_label = 'Comment created by ' + bcomment['user']
comment_created_on = time_string_to_date_string(timestring=bcomment['created_on'])
append_time_label(sb=sb, timestring=comment_created_on, label=comment_label)
sb.append('\n')
sb.append(content)
def construct_gissue_content(bissue, bexport):
sb = [bissue['content'], '\n']
created_on = time_string_to_date_string(timestring=bissue['created_on'])
updated_on = time_string_to_date_string(timestring=bissue['updated_on'])
append_time_label(sb=sb, timestring=created_on, label='Issue created by ' + bissue['reporter'])
if created_on != updated_on:
append_time_label(sb=sb, timestring=updated_on, label='Last updated on bitbucket')
bcomments = bexport.comment_map[bissue['id']]
for bcomment in bcomments:
append_bcomment(sb=sb, bcomment=bcomment)
return ''.join(sb)
def patch_gissue(gissue, bissue, bexport):
if gissue['title'] != bissue['title']:
raise ValueError('Inconsistent issues')
glabels = set()
map_bkind_to_glabels(bissue=bissue, glabels=glabels)
map_bstatus_to_glabels(bissue=bissue, glabels=glabels)
gissue_patch = {
"body": construct_gissue_content(bissue=bissue, bexport=bexport),
"assignees": map_bassignee_to_gassignees(bissue=bissue),
"labels": list(glabels),
"state": map_bstatus_to_gstate(bissue=bissue),
}
if is_gissue_patch_different(gissue=gissue, gissue_patch=gissue_patch):
do_github_request(Request('PATCH', url=issue_url() + '/' + str(gissue['number']), json=gissue_patch))
else:
print('Skip issue "' + gissue['title'] + '" since there are no changes compared to ' + repo_url())
def find_gissue_with_bissue_title(gissues, bissue):
for gissue in gissues:
if gissue['title'] == bissue['title']:
return gissue
return None
def bitbucket_to_github(bexport):
bissues = bexport.bissues
old_gissues = query_all_repo_gissues()
print('Number of github issues in ' + repo_url() + ' before POSTing:', len(old_gissues))
print('Number of bitbucket issues in ' + bexport.f_name + ':', len(bissues))
for bissue in bissues:
gissue = find_gissue_with_bissue_title(gissues=old_gissues, bissue=bissue)
if gissue is None:
gissue = post_bissue_to_github(bissue=bissue)
patch_gissue(gissue=gissue, bissue=bissue, bexport=bexport)
class BitbucketExport:
def __init__(self, bissues, comment_map, f_name):
self.bissues = bissues
self.comment_map = comment_map
self.f_name = f_name
def parse_bitbucket_export(f, f_name) -> BitbucketExport:
print('Parsing ' + f_name + '...')
bexport_json = read_json_file(f)
bissues = bexport_json['issues']
if len(bissues) == 0:
raise ValueError('Could not find any issue in ' + f_name)
bissues = sorted(bissues, key=lambda bissue: bissue['id'])
comments = bexport_json['comments']
comment_map: Dict[str, Any] = {}
for bissue in bissues:
comment_map[bissue['id']] = []
for comment in comments:
bissue_idx = comment['issue']
comment_map[bissue_idx].append(comment)
for comments in comment_map.values():
comments.reverse()
return BitbucketExport(bissues=bissues, comment_map=comment_map, f_name=f_name)
def main():
if len(sys.argv) < 2:
print('Usage: ' + sys.argv[0] + ' <bitbucket export json file>')
exit(-1)
f_name = sys.argv[1]
if get_github_access_token() is None:
print(
'Warning: Environment variable GITHUB_ACCESS_TOKEN is not set. This script will fail for private repositories.')
with open(f_name, 'r', encoding='utf8') as f:
bexport = parse_bitbucket_export(f=f, f_name=f_name)
bitbucket_to_github(bexport=bexport)
main()