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
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)
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
421
def publish_derived(self, local_branch, base_branch, name, project=None,
422
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)
427
owner = self.current_user['login']
429
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)
435
note(gettext('Forking new repository %s from %s') %
436
(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']))
441
push_result = remote_dir.push_branch(
442
local_branch, revision_id=revision_id, overwrite=overwrite,
443
name=name, tag_selector=tag_selector)
444
except errors.NoRoundtrippingSupport:
447
push_result = remote_dir.push_branch(
448
local_branch, revision_id=revision_id,
449
overwrite=overwrite, name=name, lossy=True,
450
tag_selector=tag_selector)
451
return push_result.target_branch, github_url_to_bzr_url(
452
remote_repo['html_url'], name)
454
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)
459
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)
463
owner = self.current_user['login']
465
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)
469
return _mod_branch.Branch.open(full_url)
470
except NoSuchProject:
471
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
473
def get_proposer(self, source_branch, target_branch):
474
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
476
def iter_proposals(self, source_branch, target_branch, status='open'):
477
(source_owner, source_repo_name, source_branch_name) = (
478
parse_github_branch_url(source_branch))
479
(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)
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:
498
# 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):
503
yield GitHubMergeProposal(self, pull)
505
def hosts(self, branch):
507
parse_github_branch_url(branch)
514
def probe_from_url(cls, url, possible_transports=None):
516
parse_github_url(url)
518
raise UnsupportedHoster(url)
519
transport = get_transport(
520
API_GITHUB_URL, possible_transports=possible_transports)
521
return cls(transport)
524
def iter_instances(cls):
525
yield cls(get_transport(API_GITHUB_URL))
527
def iter_my_proposals(self, status='open'):
530
query.append('is:open')
531
elif status == 'closed':
532
query.append('is:unmerged')
533
# Also use "is:closed" otherwise unmerged open pull requests are
535
query.append('is:closed')
536
elif status == 'merged':
537
query.append('is:merged')
538
query.append('author:%s' % self.current_user['login'])
539
for issue in self._search_issues(query=' '.join(query)):
540
url = issue['pull_request']['url']
541
response = self._api_request('GET', url)
542
if response.status != 200:
543
raise UnexpectedHttpStatus(url, response.status)
544
yield GitHubMergeProposal(self, json.loads(response.text))
546
def get_proposal_by_url(self, url):
547
raise UnsupportedHoster(url)
549
def iter_my_forks(self):
550
response = self._api_request('GET', '/user/repos')
551
if response.status != 200:
552
raise UnexpectedHttpStatus(self.transport.user_url, response.status)
553
for project in json.loads(response.text):
554
if not project['fork']:
556
yield project['full_name']
558
def delete_project(self, path):
559
path = 'repos/' + path
560
response = self._api_request('DELETE', path)
561
if response.status == 404:
562
raise NoSuchProject(path)
563
if response.status == 204:
565
if response.status == 200:
566
return json.loads(response.text)
567
raise UnexpectedHttpStatus(path, response.status)
569
def get_current_user(self):
570
if self._token is not None:
571
return self.current_user['login']
574
def get_user_url(self, username):
575
return urlutils.join(self.base_url, username)
578
class GitHubMergeProposalBuilder(MergeProposalBuilder):
580
def __init__(self, gh, source_branch, target_branch):
582
self.source_branch = source_branch
583
self.target_branch = target_branch
584
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
585
parse_github_branch_url(self.target_branch))
586
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
587
parse_github_branch_url(self.source_branch))
589
def get_infotext(self):
590
"""Determine the initial comment for the merge proposal."""
592
info.append("Merge %s into %s:%s\n" % (
593
self.source_branch_name, self.target_owner,
594
self.target_branch_name))
595
info.append("Source: %s\n" % self.source_branch.user_url)
596
info.append("Target: %s\n" % self.target_branch.user_url)
599
def get_initial_body(self):
600
"""Get a body for the proposal for the user to modify.
602
:return: a str or None.
606
def create_proposal(self, description, reviewers=None, labels=None,
607
prerequisite_branch=None, commit_message=None,
608
work_in_progress=False, allow_collaboration=False):
609
"""Perform the submission."""
610
if prerequisite_branch is not None:
611
raise PrerequisiteBranchUnsupported(self)
612
# Note that commit_message is ignored, since github doesn't support it.
613
# TODO(jelmer): Probe for right repo name
614
if self.target_repo_name.endswith('.git'):
615
self.target_repo_name = self.target_repo_name[:-4]
616
# TODO(jelmer): Allow setting title explicitly?
617
title = determine_title(description)
618
target_repo = self.gh._get_repo(
619
self.target_owner, self.target_repo_name)
623
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)