1
# Copyright (C) 2018 Breezy Developers
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Support for GitHub."""
22
from ...propose import (
30
PrerequisiteBranchUnsupported,
37
branch as _mod_branch,
42
version_string as breezy_version,
44
from ...config import AuthenticationConfig, GlobalStack
45
from ...errors import (
50
from ...git.urls import git_url_to_bzr_url
51
from ...i18n import gettext
52
from ...trace import note
53
from ...transport import get_transport
54
from ...transport.http import default_user_agent
57
GITHUB_HOST = 'github.com'
58
WEB_GITHUB_URL = 'https://github.com'
59
API_GITHUB_URL = 'https://api.github.com'
63
def store_github_token(scheme, host, token):
64
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
68
def retrieve_github_token(scheme, host):
69
path = os.path.join(bedding.config_dir(), 'github.conf')
70
if not os.path.exists(path):
72
with open(path, 'r') as f:
73
return f.read().strip()
76
class ValidationFailed(errors.BzrError):
78
_fmt = "GitHub validation failed: %(error)s"
80
def __init__(self, error):
81
errors.BzrError.__init__(self)
85
class NotGitHubUrl(errors.BzrError):
87
_fmt = "Not a GitHub URL: %(url)s"
89
def __init__(self, url):
90
errors.BzrError.__init__(self)
94
class GitHubLoginRequired(HosterLoginRequired):
96
_fmt = "Action requires GitHub login."
100
"""Connect to GitHub.
102
user_agent = default_user_agent()
103
auth = AuthenticationConfig()
105
credentials = auth.get_credentials('https', GITHUB_HOST)
106
if credentials is not None:
107
return Github(credentials['user'], credentials['password'],
108
user_agent=user_agent)
110
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
111
if token is not None:
112
return Github(token, user_agent=user_agent)
114
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
115
return Github(user_agent=user_agent)
118
class GitHubMergeProposal(MergeProposal):
120
def __init__(self, gh, pr):
125
return "<%s at %r>" % (type(self).__name__, self.url)
131
return self._pr['html_url']
133
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'])
138
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'))
147
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']
156
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
def set_description(self, description):
177
'title': determine_title(description),
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'])
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):
236
(scheme, user, password, host, port, path) = urlutils.parse_url(
238
if host != GITHUB_HOST:
239
raise NotGitHubUrl(url)
240
(owner, repo_name) = path.strip('/').split('/')
241
if repo_name.endswith('.git'):
242
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
return owner, repo_name, branch.name
252
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]
260
class GitHub(Hoster):
264
supports_merge_proposal_labels = True
265
supports_merge_proposal_commit_message = False
266
supports_allow_collaboration = True
267
merge_proposal_description_format = 'markdown'
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
278
response = self.transport.request(
279
method, urlutils.join(self.transport.base, path),
280
headers=headers, body=body, retries=3)
281
if response.status == 401:
282
raise GitHubLoginRequired(self)
285
def _get_repo(self, owner, repo):
286
path = 'repos/%s/%s' % (owner, repo)
287
response = self._api_request('GET', path)
288
if response.status == 404:
289
raise NoSuchProject(path)
290
if response.status == 200:
291
return json.loads(response.text)
292
raise UnexpectedHttpStatus(path, response.status)
294
def _get_repo_pulls(self, path, head=None, state=None):
298
params['head'] = head
299
if state is not None:
300
params['state'] = state
301
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
302
for k, v in params.items()])
303
response = self._api_request('GET', path)
304
if response.status == 404:
305
raise NoSuchProject(path)
306
if response.status == 200:
307
return json.loads(response.text)
308
raise UnexpectedHttpStatus(path, response.status)
310
def _create_pull(self, path, title, head, base, body=None, labels=None,
311
assignee=None, draft=False, maintainer_can_modify=False):
317
'maintainer_can_modify': maintainer_can_modify,
319
if labels is not None:
320
data['labels'] = labels
321
if assignee is not None:
322
data['assignee'] = assignee
326
response = self._api_request(
327
'POST', path, body=json.dumps(data).encode('utf-8'))
328
if response.status == 403:
329
raise PermissionDenied(path, response.text)
330
if response.status != 201:
331
raise UnexpectedHttpStatus(path, response.status)
332
return json.loads(response.text)
334
def _get_user_by_email(self, email):
335
path = 'search/users?q=%s+in:email' % email
336
response = self._api_request('GET', path)
337
if response.status != 200:
338
raise UnexpectedHttpStatus(path, response.status)
339
ret = json.loads(response.text)
340
if ret['total_count'] == 0:
341
raise KeyError('no user with email %s' % email)
342
elif ret['total_count'] > 1:
343
raise ValueError('more than one result for email %s' % email)
344
return ret['items'][0]
346
def _get_user(self, username=None):
348
path = 'users/%s' % username
351
response = self._api_request('GET', path)
352
if response.status != 200:
353
raise UnexpectedHttpStatus(path, response.status)
354
return json.loads(response.text)
356
def _get_organization(self, name):
357
path = 'orgs/%s' % name
358
response = self._api_request('GET', path)
359
if response.status != 200:
360
raise UnexpectedHttpStatus(path, response.status)
361
return json.loads(response.text)
363
def _list_paged(self, path, parameters=None, per_page=None):
364
if parameters is None:
367
parameters = dict(parameters.items())
369
parameters['per_page'] = str(per_page)
373
parameters['page'] = str(page)
374
response = self._api_request(
376
';'.join(['%s=%s' % (k, urlutils.quote(v))
377
for (k, v) in parameters.items()]))
378
if response.status != 200:
379
raise UnexpectedHttpStatus(path, response.status)
380
data = json.loads(response.text)
381
for entry in data['items']:
384
if i >= data['total_count']:
388
def _search_issues(self, query):
389
path = 'search/issues'
390
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
392
def _create_fork(self, path, owner=None):
393
if owner and owner != self.current_user['login']:
394
path += '?organization=%s' % owner
395
response = self._api_request('POST', path)
396
if response.status != 202:
397
raise UnexpectedHttpStatus(path, response.status)
398
return json.loads(response.text)
402
return WEB_GITHUB_URL
404
def __init__(self, transport):
405
self._token = retrieve_github_token('https', GITHUB_HOST)
406
self.transport = transport
407
self._current_user = None
410
def current_user(self):
411
if self._current_user is None:
412
self._current_user = self._get_user()
413
return self._current_user
415
def publish_derived(self, local_branch, base_branch, name, project=None,
416
owner=None, revision_id=None, overwrite=False,
417
allow_lossy=True, tag_selector=None):
418
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
419
base_repo = self._get_repo(base_owner, base_project)
421
owner = self.current_user['login']
423
project = base_repo['name']
425
remote_repo = self._get_repo(owner, project)
426
except NoSuchProject:
427
base_repo = self._get_repo(base_owner, base_project)
428
remote_repo = self._create_fork(base_repo['forks_url'], owner)
429
note(gettext('Forking new repository %s from %s') %
430
(remote_repo['html_url'], base_repo['html_url']))
432
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
433
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
435
push_result = remote_dir.push_branch(
436
local_branch, revision_id=revision_id, overwrite=overwrite,
437
name=name, tag_selector=tag_selector)
438
except errors.NoRoundtrippingSupport:
441
push_result = remote_dir.push_branch(
442
local_branch, revision_id=revision_id,
443
overwrite=overwrite, name=name, lossy=True,
444
tag_selector=tag_selector)
445
return push_result.target_branch, github_url_to_bzr_url(
446
remote_repo['html_url'], name)
448
def get_push_url(self, branch):
449
owner, project, branch_name = parse_github_branch_url(branch)
450
repo = self._get_repo(owner, project)
451
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
453
def get_derived_branch(self, base_branch, name, project=None, owner=None):
454
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
455
base_repo = self._get_repo(base_owner, base_project)
457
owner = self.current_user['login']
459
project = base_repo['name']
461
remote_repo = self._get_repo(owner, project)
462
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
463
return _mod_branch.Branch.open(full_url)
464
except NoSuchProject:
465
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
467
def get_proposer(self, source_branch, target_branch):
468
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
470
def iter_proposals(self, source_branch, target_branch, status='open'):
471
(source_owner, source_repo_name, source_branch_name) = (
472
parse_github_branch_url(source_branch))
473
(target_owner, target_repo_name, target_branch_name) = (
474
parse_github_branch_url(target_branch))
475
target_repo = self._get_repo(target_owner, target_repo_name)
481
pulls = self._get_repo_pulls(
482
strip_optional(target_repo['pulls_url']),
483
head=target_branch_name,
486
if (status == 'closed' and pull['merged'] or
487
status == 'merged' and not pull['merged']):
489
if pull['head']['ref'] != source_branch_name:
491
if pull['head']['repo'] is None:
492
# Repo has gone the way of the dodo
494
if (pull['head']['repo']['owner']['login'] != source_owner or
495
pull['head']['repo']['name'] != source_repo_name):
497
yield GitHubMergeProposal(self, pull)
499
def hosts(self, branch):
501
parse_github_branch_url(branch)
508
def probe_from_url(cls, url, possible_transports=None):
510
parse_github_url(url)
512
raise UnsupportedHoster(url)
513
transport = get_transport(
514
API_GITHUB_URL, possible_transports=possible_transports)
515
return cls(transport)
518
def iter_instances(cls):
519
yield cls(get_transport(API_GITHUB_URL))
521
def iter_my_proposals(self, status='open'):
524
query.append('is:open')
525
elif status == 'closed':
526
query.append('is:unmerged')
527
# Also use "is:closed" otherwise unmerged open pull requests are
529
query.append('is:closed')
530
elif status == 'merged':
531
query.append('is:merged')
532
query.append('author:%s' % self.current_user['login'])
533
for issue in self._search_issues(query=' '.join(query)):
534
url = issue['pull_request']['url']
535
response = self._api_request('GET', url)
536
if response.status != 200:
537
raise UnexpectedHttpStatus(url, response.status)
538
yield GitHubMergeProposal(self, json.loads(response.text))
540
def get_proposal_by_url(self, url):
541
raise UnsupportedHoster(url)
543
def iter_my_forks(self):
544
response = self._api_request('GET', '/user/repos')
545
if response.status != 200:
546
raise UnexpectedHttpStatus(self.transport.user_url, response.status)
547
for project in json.loads(response.text):
548
if not project['fork']:
550
yield project['full_name']
552
def delete_project(self, path):
553
path = 'repos/' + path
554
response = self._api_request('DELETE', path)
555
if response.status == 404:
556
raise NoSuchProject(path)
557
if response.status == 204:
559
if response.status == 200:
560
return json.loads(response.text)
561
raise UnexpectedHttpStatus(path, response.status)
563
def get_current_user(self):
564
return self.current_user['login']
566
def get_user_url(self, username):
567
return urlutils.join(self.base_url, username)
570
class GitHubMergeProposalBuilder(MergeProposalBuilder):
572
def __init__(self, gh, source_branch, target_branch):
574
self.source_branch = source_branch
575
self.target_branch = target_branch
576
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
577
parse_github_branch_url(self.target_branch))
578
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
579
parse_github_branch_url(self.source_branch))
581
def get_infotext(self):
582
"""Determine the initial comment for the merge proposal."""
584
info.append("Merge %s into %s:%s\n" % (
585
self.source_branch_name, self.target_owner,
586
self.target_branch_name))
587
info.append("Source: %s\n" % self.source_branch.user_url)
588
info.append("Target: %s\n" % self.target_branch.user_url)
591
def get_initial_body(self):
592
"""Get a body for the proposal for the user to modify.
594
:return: a str or None.
598
def create_proposal(self, description, reviewers=None, labels=None,
599
prerequisite_branch=None, commit_message=None,
600
work_in_progress=False, allow_collaboration=False):
601
"""Perform the submission."""
602
if prerequisite_branch is not None:
603
raise PrerequisiteBranchUnsupported(self)
604
# Note that commit_message is ignored, since github doesn't support it.
605
# TODO(jelmer): Probe for right repo name
606
if self.target_repo_name.endswith('.git'):
607
self.target_repo_name = self.target_repo_name[:-4]
608
# TODO(jelmer): Allow setting title explicitly?
609
title = determine_title(description)
610
target_repo = self.gh._get_repo(
611
self.target_owner, self.target_repo_name)
615
for reviewer in reviewers:
617
user = self.gh._get_user_by_email(reviewer)
619
user = self.gh._get_user(reviewer)
620
assignees.append(user['login'])
624
pull_request = self.gh._create_pull(
625
strip_optional(target_repo['pulls_url']),
626
title=title, body=description,
627
head="%s:%s" % (self.source_owner, self.source_branch_name),
628
base=self.target_branch_name,
629
labels=labels, assignee=assignees,
630
draft=work_in_progress,
631
maintainer_can_modify=allow_collaboration,
633
except ValidationFailed:
634
raise MergeProposalExists(self.source_branch.user_url)
635
return GitHubMergeProposal(self.gh, pull_request)