118
104
class GitHubMergeProposal(MergeProposal):
120
def __init__(self, gh, pr):
106
def __init__(self, pr):
125
return "<%s at %r>" % (type(self).__name__, self.url)
131
return self._pr['html_url']
111
return self._pr.html_url
133
113
def _branch_from_part(self, part):
134
if part['repo'] is None:
136
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
114
return github_url_to_bzr_url(part.repo.html_url, part.ref)
138
116
def get_source_branch_url(self):
139
return self._branch_from_part(self._pr['head'])
141
def get_source_revision(self):
142
"""Return the latest revision for the source branch."""
143
from breezy.git.mapping import default_mapping
144
return default_mapping.revision_id_foreign_to_bzr(
145
self._pr['head']['sha'].encode('ascii'))
117
return self._branch_from_part(self._pr.head)
147
119
def get_target_branch_url(self):
148
return self._branch_from_part(self._pr['base'])
150
def get_source_project(self):
151
return self._pr['head']['repo']['full_name']
153
def get_target_project(self):
154
return self._pr['base']['repo']['full_name']
120
return self._branch_from_part(self._pr.base)
156
122
def get_description(self):
157
return self._pr['body']
159
def get_commit_message(self):
162
def set_commit_message(self, message):
163
raise errors.UnsupportedOperation(self.set_commit_message, self)
165
def _patch(self, data):
166
response = self._gh._api_request(
167
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
168
if response.status == 422:
169
raise ValidationFailed(json.loads(response.text))
170
if response.status != 200:
171
raise UnexpectedHttpStatus(self._pr['url'], response.status)
172
self._pr = json.loads(response.text)
174
125
def set_description(self, description):
177
'title': determine_title(description),
126
self._pr.edit(body=description, title=determine_title(description))
180
128
def is_merged(self):
181
return bool(self._pr.get('merged_at'))
184
return self._pr['state'] == 'closed' and not bool(self._pr.get('merged_at'))
188
self._patch({'state': 'open'})
189
except ValidationFailed as e:
190
raise ReopenFailed(e.error['errors'][0]['message'])
129
return self._pr.merged
193
self._patch({'state': 'closed'})
195
def can_be_merged(self):
196
return self._pr['mergeable']
198
def merge(self, commit_message=None):
199
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
202
data['commit_message'] = commit_messae
203
response = self._gh._api_request(
204
'PUT', self._pr['url'] + "/merge", body=json.dumps(data).encode('utf-8'))
205
if response.status == 422:
206
raise ValidationFailed(json.loads(response.text))
207
if response.status != 200:
208
raise UnexpectedHttpStatus(self._pr['url'], response.status)
210
def get_merged_by(self):
211
merged_by = self._pr.get('merged_by')
212
if merged_by is None:
214
return merged_by['login']
216
def get_merged_at(self):
217
merged_at = self._pr.get('merged_at')
218
if merged_at is None:
221
return iso8601.parse_date(merged_at)
223
def post_comment(self, body):
224
data = {'body': body}
225
response = self._gh._api_request(
226
'POST', self._pr['comments_url'], body=json.dumps(data).encode('utf-8'))
227
if response.status == 422:
228
raise ValidationFailed(json.loads(response.text))
229
if response.status != 201:
230
raise UnexpectedHttpStatus(
231
self._pr['comments_url'], response.status)
232
json.loads(response.text)
235
def parse_github_url(url):
132
self._pr.edit(state='closed')
135
def parse_github_url(branch):
136
url = urlutils.split_segment_parameters(branch.user_url)[0]
236
137
(scheme, user, password, host, port, path) = urlutils.parse_url(
238
if host != GITHUB_HOST:
139
if host != 'github.com':
239
140
raise NotGitHubUrl(url)
240
141
(owner, repo_name) = path.strip('/').split('/')
241
142
if repo_name.endswith('.git'):
242
143
repo_name = repo_name[:-4]
243
return owner, repo_name
246
def parse_github_branch_url(branch):
247
url = urlutils.strip_segment_parameters(branch.user_url)
248
owner, repo_name = parse_github_url(url)
249
144
return owner, repo_name, branch.name
252
147
def github_url_to_bzr_url(url, branch_name):
253
return git_url_to_bzr_url(url, branch_name)
256
def strip_optional(url):
257
return url.split('{')[0]
149
branch_name = branch_name.encode('utf-8')
150
return urlutils.join_segment_parameters(
151
git_url_to_bzr_url(url), {"branch": branch_name})
154
def convert_github_error(fn):
155
def convert(self, *args, **kwargs):
158
return fn(self, *args, **kwargs)
159
except github.GithubException as e:
161
raise GitHubLoginRequired(self)
260
166
class GitHub(Hoster):
264
170
supports_merge_proposal_labels = True
265
supports_merge_proposal_commit_message = False
266
supports_allow_collaboration = True
267
merge_proposal_description_format = 'markdown'
269
172
def __repr__(self):
270
173
return "GitHub()"
272
def _api_request(self, method, path, body=None):
274
'Content-Type': 'application/json',
275
'Accept': 'application/vnd.github.v3+json'}
277
headers['Authorization'] = 'token %s' % self._token
279
response = self.transport.request(
280
method, urlutils.join(self.transport.base, path),
281
headers=headers, body=body, retries=3)
282
except UnexpectedHttpStatus as e:
284
raise GitHubLoginRequired(self)
287
if response.status == 401:
288
raise GitHubLoginRequired(self)
291
def _get_repo(self, owner, repo):
292
path = 'repos/%s/%s' % (owner, repo)
293
response = self._api_request('GET', path)
294
if response.status == 404:
295
raise NoSuchProject(path)
296
if response.status == 200:
297
return json.loads(response.text)
298
raise UnexpectedHttpStatus(path, response.status)
300
def _get_repo_pulls(self, path, head=None, state=None):
304
params['head'] = head
305
if state is not None:
306
params['state'] = state
307
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
308
for k, v in params.items()])
309
response = self._api_request('GET', path)
310
if response.status == 404:
311
raise NoSuchProject(path)
312
if response.status == 200:
313
return json.loads(response.text)
314
raise UnexpectedHttpStatus(path, response.status)
316
def _create_pull(self, path, title, head, base, body=None, labels=None,
317
assignee=None, draft=False, maintainer_can_modify=False):
323
'maintainer_can_modify': maintainer_can_modify,
325
if labels is not None:
326
data['labels'] = labels
327
if assignee is not None:
328
data['assignee'] = assignee
332
response = self._api_request(
333
'POST', path, body=json.dumps(data).encode('utf-8'))
334
if response.status == 403:
335
raise PermissionDenied(path, response.text)
336
if response.status != 201:
337
raise UnexpectedHttpStatus(path, response.status)
338
return json.loads(response.text)
340
def _get_user_by_email(self, email):
341
path = 'search/users?q=%s+in:email' % email
342
response = self._api_request('GET', path)
343
if response.status != 200:
344
raise UnexpectedHttpStatus(path, response.status)
345
ret = json.loads(response.text)
346
if ret['total_count'] == 0:
347
raise KeyError('no user with email %s' % email)
348
elif ret['total_count'] > 1:
349
raise ValueError('more than one result for email %s' % email)
350
return ret['items'][0]
352
def _get_user(self, username=None):
354
path = 'users/%s' % username
357
response = self._api_request('GET', path)
358
if response.status != 200:
359
raise UnexpectedHttpStatus(path, response.status)
360
return json.loads(response.text)
362
def _get_organization(self, name):
363
path = 'orgs/%s' % name
364
response = self._api_request('GET', path)
365
if response.status != 200:
366
raise UnexpectedHttpStatus(path, response.status)
367
return json.loads(response.text)
369
def _list_paged(self, path, parameters=None, per_page=None):
370
if parameters is None:
373
parameters = dict(parameters.items())
375
parameters['per_page'] = str(per_page)
379
parameters['page'] = str(page)
380
response = self._api_request(
382
';'.join(['%s=%s' % (k, urlutils.quote(v))
383
for (k, v) in parameters.items()]))
384
if response.status != 200:
385
raise UnexpectedHttpStatus(path, response.status)
386
data = json.loads(response.text)
387
for entry in data['items']:
390
if i >= data['total_count']:
394
def _search_issues(self, query):
395
path = 'search/issues'
396
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
398
def _create_fork(self, path, owner=None):
399
if owner and owner != self.current_user['login']:
400
path += '?organization=%s' % owner
401
response = self._api_request('POST', path)
402
if response.status != 202:
403
raise UnexpectedHttpStatus(path, response.status)
404
return json.loads(response.text)
407
176
def base_url(self):
408
return WEB_GITHUB_URL
410
def __init__(self, transport):
411
self._token = retrieve_github_token('https', GITHUB_HOST)
412
self.transport = transport
413
self._current_user = None
416
def current_user(self):
417
if self._current_user is None:
418
self._current_user = self._get_user()
419
return self._current_user
177
# TODO(jelmer): Can we get the default URL from the Python API package
179
return "https://github.com"
182
self.gh = connect_github()
184
@convert_github_error
421
185
def publish_derived(self, local_branch, base_branch, name, project=None,
422
186
owner=None, revision_id=None, overwrite=False,
423
allow_lossy=True, tag_selector=None):
424
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
425
base_repo = self._get_repo(base_owner, base_project)
189
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
190
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
426
191
if owner is None:
427
owner = self.current_user['login']
192
owner = self.gh.get_user().login
428
193
if project is None:
429
project = base_repo['name']
194
project = base_repo.name
431
remote_repo = self._get_repo(owner, project)
432
except NoSuchProject:
433
base_repo = self._get_repo(base_owner, base_project)
434
remote_repo = self._create_fork(base_repo['forks_url'], owner)
196
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
198
except github.UnknownObjectException:
199
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
200
if owner == self.gh.get_user().login:
201
owner_obj = self.gh.get_user()
203
owner_obj = self.gh.get_organization(owner)
204
remote_repo = owner_obj.create_fork(base_repo)
435
205
note(gettext('Forking new repository %s from %s') %
436
(remote_repo['html_url'], base_repo['html_url']))
206
(remote_repo.html_url, base_repo.html_url))
438
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
439
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
208
note(gettext('Reusing existing repository %s') % remote_repo.html_url)
209
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
441
211
push_result = remote_dir.push_branch(
442
212
local_branch, revision_id=revision_id, overwrite=overwrite,
443
name=name, tag_selector=tag_selector)
444
214
except errors.NoRoundtrippingSupport:
445
215
if not allow_lossy:
447
217
push_result = remote_dir.push_branch(
448
218
local_branch, revision_id=revision_id,
449
overwrite=overwrite, name=name, lossy=True,
450
tag_selector=tag_selector)
219
overwrite=overwrite, name=name, lossy=True)
451
220
return push_result.target_branch, github_url_to_bzr_url(
452
remote_repo['html_url'], name)
221
remote_repo.html_url, name)
223
@convert_github_error
454
224
def get_push_url(self, branch):
455
owner, project, branch_name = parse_github_branch_url(branch)
456
repo = self._get_repo(owner, project)
457
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
225
owner, project, branch_name = parse_github_url(branch)
226
repo = self.gh.get_repo('%s/%s' % (owner, project))
227
return github_url_to_bzr_url(repo.ssh_url, branch_name)
229
@convert_github_error
459
230
def get_derived_branch(self, base_branch, name, project=None, owner=None):
460
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
461
base_repo = self._get_repo(base_owner, base_project)
232
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
233
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
462
234
if owner is None:
463
owner = self.current_user['login']
235
owner = self.gh.get_user().login
464
236
if project is None:
465
project = base_repo['name']
237
project = base_repo.name
467
remote_repo = self._get_repo(owner, project)
468
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
239
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
240
full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
469
241
return _mod_branch.Branch.open(full_url)
470
except NoSuchProject:
471
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
242
except github.UnknownObjectException:
243
raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
245
@convert_github_error
473
246
def get_proposer(self, source_branch, target_branch):
474
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
247
return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
249
@convert_github_error
476
250
def iter_proposals(self, source_branch, target_branch, status='open'):
477
251
(source_owner, source_repo_name, source_branch_name) = (
478
parse_github_branch_url(source_branch))
252
parse_github_url(source_branch))
479
253
(target_owner, target_repo_name, target_branch_name) = (
480
parse_github_branch_url(target_branch))
481
target_repo = self._get_repo(target_owner, target_repo_name)
254
parse_github_url(target_branch))
255
target_repo = self.gh.get_repo(
256
"%s/%s" % (target_owner, target_repo_name))
484
259
'merged': 'closed',
485
260
'closed': 'closed',
487
pulls = self._get_repo_pulls(
488
strip_optional(target_repo['pulls_url']),
489
head=target_branch_name,
492
if (status == 'closed' and pull['merged'] or
493
status == 'merged' and not pull['merged']):
495
if pull['head']['ref'] != source_branch_name:
497
if pull['head']['repo'] is None:
262
for pull in target_repo.get_pulls(
263
head=target_branch_name,
264
state=state[status]):
265
if (status == 'closed' and pull.merged or
266
status == 'merged' and not pull.merged):
268
if pull.head.ref != source_branch_name:
270
if pull.head.repo is None:
498
271
# Repo has gone the way of the dodo
500
if (pull['head']['repo']['owner']['login'] != source_owner or
501
pull['head']['repo']['name'] != source_repo_name):
273
if (pull.head.repo.owner.login != source_owner or
274
pull.head.repo.name != source_repo_name):
503
yield GitHubMergeProposal(self, pull)
276
yield GitHubMergeProposal(pull)
505
278
def hosts(self, branch):
507
parse_github_branch_url(branch)
280
parse_github_url(branch)
508
281
except NotGitHubUrl:
514
def probe_from_url(cls, url, possible_transports=None):
287
def probe(cls, branch):
516
parse_github_url(url)
289
parse_github_url(branch)
517
290
except NotGitHubUrl:
518
raise UnsupportedHoster(url)
519
transport = get_transport(
520
API_GITHUB_URL, possible_transports=possible_transports)
521
return cls(transport)
291
raise UnsupportedHoster(branch)
524
295
def iter_instances(cls):
525
yield cls(get_transport(API_GITHUB_URL))
298
@convert_github_error
527
299
def iter_my_proposals(self, status='open'):
528
300
query = ['is:pr']
529
301
if status == 'open':
606
343
def create_proposal(self, description, reviewers=None, labels=None,
607
prerequisite_branch=None, commit_message=None,
608
work_in_progress=False, allow_collaboration=False):
344
prerequisite_branch=None):
609
345
"""Perform the submission."""
610
346
if prerequisite_branch is not None:
611
347
raise PrerequisiteBranchUnsupported(self)
612
# Note that commit_message is ignored, since github doesn't support it.
613
349
# TODO(jelmer): Probe for right repo name
614
350
if self.target_repo_name.endswith('.git'):
615
351
self.target_repo_name = self.target_repo_name[:-4]
352
target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
616
353
# TODO(jelmer): Allow setting title explicitly?
617
354
title = determine_title(description)
618
target_repo = self.gh._get_repo(
619
self.target_owner, self.target_repo_name)
355
# TOOD(jelmer): Set maintainers_can_modify?
357
pull_request = target_repo.create_pull(
358
title=title, body=description,
359
head="%s:%s" % (self.source_owner, self.source_branch_name),
360
base=self.target_branch_name)
361
except github.GithubException as e:
363
raise MergeProposalExists(self.source_branch.user_url)
623
366
for reviewer in reviewers:
625
user = self.gh._get_user_by_email(reviewer)
627
user = self.gh._get_user(reviewer)
628
assignees.append(user['login'])
632
pull_request = self.gh._create_pull(
633
strip_optional(target_repo['pulls_url']),
634
title=title, body=description,
635
head="%s:%s" % (self.source_owner, self.source_branch_name),
636
base=self.target_branch_name,
637
labels=labels, assignee=assignees,
638
draft=work_in_progress,
639
maintainer_can_modify=allow_collaboration,
641
except ValidationFailed:
642
raise MergeProposalExists(self.source_branch.user_url)
643
return GitHubMergeProposal(self.gh, pull_request)
367
pull_request.assignees.append(
368
self.gh.get_user(reviewer))
371
pull_request.issue.labels.append(label)
372
return GitHubMergeProposal(pull_request)