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."""
19
from __future__ import absolute_import
24
from ...propose import (
32
PrerequisiteBranchUnsupported,
39
branch as _mod_branch,
44
version_string as breezy_version,
46
from ...config import AuthenticationConfig, GlobalStack
47
from ...errors import (
52
from ...git.urls import git_url_to_bzr_url
53
from ...i18n import gettext
54
from ...sixish import PY3
55
from ...trace import note
56
from ...transport import get_transport
57
from ...transport.http import default_user_agent
60
GITHUB_HOST = 'github.com'
61
WEB_GITHUB_URL = 'https://github.com'
62
API_GITHUB_URL = 'https://api.github.com'
66
def store_github_token(scheme, host, token):
67
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
71
def retrieve_github_token(scheme, host):
72
path = os.path.join(bedding.config_dir(), 'github.conf')
73
if not os.path.exists(path):
75
with open(path, 'r') as f:
76
return f.read().strip()
79
class ValidationFailed(errors.BzrError):
81
_fmt = "GitHub validation failed: %(error)s"
83
def __init__(self, error):
84
errors.BzrError.__init__(self)
88
class NotGitHubUrl(errors.BzrError):
90
_fmt = "Not a GitHub URL: %(url)s"
92
def __init__(self, url):
93
errors.BzrError.__init__(self)
97
class GitHubLoginRequired(HosterLoginRequired):
99
_fmt = "Action requires GitHub login."
102
def connect_github():
103
"""Connect to GitHub.
105
user_agent = default_user_agent()
106
auth = AuthenticationConfig()
108
credentials = auth.get_credentials('https', GITHUB_HOST)
109
if credentials is not None:
110
return Github(credentials['user'], credentials['password'],
111
user_agent=user_agent)
113
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
114
if token is not None:
115
return Github(token, user_agent=user_agent)
117
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
118
return Github(user_agent=user_agent)
121
class GitHubMergeProposal(MergeProposal):
123
def __init__(self, gh, pr):
128
return "<%s at %r>" % (type(self).__name__, self.url)
134
return self._pr['html_url']
136
def _branch_from_part(self, part):
137
if part['repo'] is None:
139
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
141
def get_source_branch_url(self):
142
return self._branch_from_part(self._pr['head'])
144
def get_source_revision(self):
145
"""Return the latest revision for the source branch."""
146
from breezy.git.mapping import default_mapping
147
return default_mapping.revision_id_foreign_to_bzr(
148
self._pr['head']['sha'].encode('ascii'))
150
def get_target_branch_url(self):
151
return self._branch_from_part(self._pr['base'])
153
def get_source_project(self):
154
return self._pr['head']['repo']['full_name']
156
def get_target_project(self):
157
return self._pr['base']['repo']['full_name']
159
def get_description(self):
160
return self._pr['body']
162
def get_commit_message(self):
165
def set_commit_message(self, message):
166
raise errors.UnsupportedOperation(self.set_commit_message, self)
168
def _patch(self, data):
169
response = self._gh._api_request(
170
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
171
if response.status == 422:
172
raise ValidationFailed(json.loads(response.text))
173
if response.status != 200:
174
raise UnexpectedHttpStatus(self._pr['url'], response.status)
175
self._pr = json.loads(response.text)
177
def set_description(self, description):
180
'title': determine_title(description),
184
return bool(self._pr.get('merged_at'))
187
return self._pr['state'] == 'closed' and not bool(self._pr.get('merged_at'))
191
self._patch({'state': 'open'})
192
except ValidationFailed as e:
193
raise ReopenFailed(e.error['errors'][0]['message'])
196
self._patch({'state': 'closed'})
198
def can_be_merged(self):
199
return self._pr['mergeable']
201
def merge(self, commit_message=None):
202
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
205
data['commit_message'] = commit_messae
206
response = self._gh._api_request(
207
'PUT', self._pr['url'] + "/merge", body=json.dumps(data).encode('utf-8'))
208
if response.status == 422:
209
raise ValidationFailed(json.loads(response.text))
210
if response.status != 200:
211
raise UnexpectedHttpStatus(self._pr['url'], response.status)
213
def get_merged_by(self):
214
merged_by = self._pr.get('merged_by')
215
if merged_by is None:
217
return merged_by['login']
219
def get_merged_at(self):
220
merged_at = self._pr.get('merged_at')
221
if merged_at is None:
224
return iso8601.parse_date(merged_at)
226
def post_comment(self, body):
227
data = {'body': body}
228
response = self._gh._api_request(
229
'POST', self._pr['comments_url'], body=json.dumps(data).encode('utf-8'))
230
if response.status == 422:
231
raise ValidationFailed(json.loads(response.text))
232
if response.status != 201:
233
raise UnexpectedHttpStatus(
234
self._pr['comments_url'], response.status)
235
json.loads(response.text)
238
def parse_github_url(url):
239
(scheme, user, password, host, port, path) = urlutils.parse_url(
241
if host != GITHUB_HOST:
242
raise NotGitHubUrl(url)
243
(owner, repo_name) = path.strip('/').split('/')
244
if repo_name.endswith('.git'):
245
repo_name = repo_name[:-4]
246
return owner, repo_name
249
def parse_github_branch_url(branch):
250
url = urlutils.strip_segment_parameters(branch.user_url)
251
owner, repo_name = parse_github_url(url)
252
return owner, repo_name, branch.name
255
def github_url_to_bzr_url(url, branch_name):
257
branch_name = branch_name.encode('utf-8')
258
return git_url_to_bzr_url(url, branch_name)
261
def strip_optional(url):
262
return url.split('{')[0]
265
class GitHub(Hoster):
269
supports_merge_proposal_labels = True
270
supports_merge_proposal_commit_message = False
271
supports_allow_collaboration = True
272
merge_proposal_description_format = 'markdown'
277
def _api_request(self, method, path, body=None):
279
'Content-Type': 'application/json',
280
'Accept': 'application/vnd.github.v3+json'}
282
headers['Authorization'] = 'token %s' % self._token
284
response = self.transport.request(
285
method, urlutils.join(self.transport.base, path),
286
headers=headers, body=body, retries=3)
287
except UnexpectedHttpStatus as e:
289
raise GitHubLoginRequired(self)
292
if response.status == 401:
293
raise GitHubLoginRequired(self)
296
def _get_repo(self, owner, repo):
297
path = 'repos/%s/%s' % (owner, repo)
298
response = self._api_request('GET', path)
299
if response.status == 404:
300
raise NoSuchProject(path)
301
if response.status == 200:
302
return json.loads(response.text)
303
raise UnexpectedHttpStatus(path, response.status)
305
def _get_repo_pulls(self, path, head=None, state=None):
309
params['head'] = head
310
if state is not None:
311
params['state'] = state
312
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
313
for k, v in params.items()])
314
response = self._api_request('GET', path)
315
if response.status == 404:
316
raise NoSuchProject(path)
317
if response.status == 200:
318
return json.loads(response.text)
319
raise UnexpectedHttpStatus(path, response.status)
321
def _create_pull(self, path, title, head, base, body=None, labels=None,
322
assignee=None, draft=False, maintainer_can_modify=False):
328
'maintainer_can_modify': maintainer_can_modify,
330
if labels is not None:
331
data['labels'] = labels
332
if assignee is not None:
333
data['assignee'] = assignee
337
response = self._api_request(
338
'POST', path, body=json.dumps(data).encode('utf-8'))
339
if response.status == 403:
340
raise PermissionDenied(path, response.text)
341
if response.status != 201:
342
raise UnexpectedHttpStatus(path, response.status)
343
return json.loads(response.text)
345
def _get_user_by_email(self, email):
346
path = 'search/users?q=%s+in:email' % email
347
response = self._api_request('GET', path)
348
if response.status != 200:
349
raise UnexpectedHttpStatus(path, response.status)
350
ret = json.loads(response.text)
351
if ret['total_count'] == 0:
352
raise KeyError('no user with email %s' % email)
353
elif ret['total_count'] > 1:
354
raise ValueError('more than one result for email %s' % email)
355
return ret['items'][0]
357
def _get_user(self, username=None):
359
path = 'users/%s' % username
362
response = self._api_request('GET', path)
363
if response.status != 200:
364
raise UnexpectedHttpStatus(path, response.status)
365
return json.loads(response.text)
367
def _get_organization(self, name):
368
path = 'orgs/%s' % name
369
response = self._api_request('GET', path)
370
if response.status != 200:
371
raise UnexpectedHttpStatus(path, response.status)
372
return json.loads(response.text)
374
def _list_paged(self, path, parameters=None, per_page=None):
375
if parameters is None:
378
parameters = dict(parameters.items())
380
parameters['per_page'] = str(per_page)
384
parameters['page'] = str(page)
385
response = self._api_request(
387
';'.join(['%s=%s' % (k, urlutils.quote(v))
388
for (k, v) in parameters.items()]))
389
if response.status != 200:
390
raise UnexpectedHttpStatus(path, response.status)
391
data = json.loads(response.text)
392
for entry in data['items']:
395
if i >= data['total_count']:
399
def _search_issues(self, query):
400
path = 'search/issues'
401
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
403
def _create_fork(self, path, owner=None):
404
if owner and owner != self.current_user['login']:
405
path += '?organization=%s' % owner
406
response = self._api_request('POST', path)
407
if response.status != 202:
408
raise UnexpectedHttpStatus(path, response.status)
409
return json.loads(response.text)
413
return WEB_GITHUB_URL
415
def __init__(self, transport):
416
self._token = retrieve_github_token('https', GITHUB_HOST)
417
self.transport = transport
418
self._current_user = None
421
def current_user(self):
422
if self._current_user is None:
423
self._current_user = self._get_user()
424
return self._current_user
426
def publish_derived(self, local_branch, base_branch, name, project=None,
427
owner=None, revision_id=None, overwrite=False,
428
allow_lossy=True, tag_selector=None):
429
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
430
base_repo = self._get_repo(base_owner, base_project)
432
owner = self.current_user['login']
434
project = base_repo['name']
436
remote_repo = self._get_repo(owner, project)
437
except NoSuchProject:
438
base_repo = self._get_repo(base_owner, base_project)
439
remote_repo = self._create_fork(base_repo['forks_url'], owner)
440
note(gettext('Forking new repository %s from %s') %
441
(remote_repo['html_url'], base_repo['html_url']))
443
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
444
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
446
push_result = remote_dir.push_branch(
447
local_branch, revision_id=revision_id, overwrite=overwrite,
448
name=name, tag_selector=tag_selector)
449
except errors.NoRoundtrippingSupport:
452
push_result = remote_dir.push_branch(
453
local_branch, revision_id=revision_id,
454
overwrite=overwrite, name=name, lossy=True,
455
tag_selector=tag_selector)
456
return push_result.target_branch, github_url_to_bzr_url(
457
remote_repo['html_url'], name)
459
def get_push_url(self, branch):
460
owner, project, branch_name = parse_github_branch_url(branch)
461
repo = self._get_repo(owner, project)
462
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
464
def get_derived_branch(self, base_branch, name, project=None, owner=None):
465
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
466
base_repo = self._get_repo(base_owner, base_project)
468
owner = self.current_user['login']
470
project = base_repo['name']
472
remote_repo = self._get_repo(owner, project)
473
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
474
return _mod_branch.Branch.open(full_url)
475
except NoSuchProject:
476
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
478
def get_proposer(self, source_branch, target_branch):
479
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
481
def iter_proposals(self, source_branch, target_branch, status='open'):
482
(source_owner, source_repo_name, source_branch_name) = (
483
parse_github_branch_url(source_branch))
484
(target_owner, target_repo_name, target_branch_name) = (
485
parse_github_branch_url(target_branch))
486
target_repo = self._get_repo(target_owner, target_repo_name)
492
pulls = self._get_repo_pulls(
493
strip_optional(target_repo['pulls_url']),
494
head=target_branch_name,
497
if (status == 'closed' and pull['merged'] or
498
status == 'merged' and not pull['merged']):
500
if pull['head']['ref'] != source_branch_name:
502
if pull['head']['repo'] is None:
503
# Repo has gone the way of the dodo
505
if (pull['head']['repo']['owner']['login'] != source_owner or
506
pull['head']['repo']['name'] != source_repo_name):
508
yield GitHubMergeProposal(self, pull)
510
def hosts(self, branch):
512
parse_github_branch_url(branch)
519
def probe_from_url(cls, url, possible_transports=None):
521
parse_github_url(url)
523
raise UnsupportedHoster(url)
524
transport = get_transport(
525
API_GITHUB_URL, possible_transports=possible_transports)
526
return cls(transport)
529
def iter_instances(cls):
530
yield cls(get_transport(API_GITHUB_URL))
532
def iter_my_proposals(self, status='open'):
535
query.append('is:open')
536
elif status == 'closed':
537
query.append('is:unmerged')
538
# Also use "is:closed" otherwise unmerged open pull requests are
540
query.append('is:closed')
541
elif status == 'merged':
542
query.append('is:merged')
543
query.append('author:%s' % self.current_user['login'])
544
for issue in self._search_issues(query=' '.join(query)):
545
url = issue['pull_request']['url']
546
response = self._api_request('GET', url)
547
if response.status != 200:
548
raise UnexpectedHttpStatus(url, response.status)
549
yield GitHubMergeProposal(self, json.loads(response.text))
551
def get_proposal_by_url(self, url):
552
raise UnsupportedHoster(url)
554
def iter_my_forks(self):
555
response = self._api_request('GET', '/user/repos')
556
if response.status != 200:
557
raise UnexpectedHttpStatus(self.transport.user_url, response.status)
558
for project in json.loads(response.text):
559
if not project['fork']:
561
yield project['full_name']
563
def delete_project(self, path):
564
path = 'repos/' + path
565
response = self._api_request('DELETE', path)
566
if response.status == 404:
567
raise NoSuchProject(path)
568
if response.status == 204:
570
if response.status == 200:
571
return json.loads(response.text)
572
raise UnexpectedHttpStatus(path, response.status)
574
def get_current_user(self):
575
if self._token is not None:
576
return self.current_user['login']
579
def get_user_url(self, username):
580
return urlutils.join(self.base_url, username)
583
class GitHubMergeProposalBuilder(MergeProposalBuilder):
585
def __init__(self, gh, source_branch, target_branch):
587
self.source_branch = source_branch
588
self.target_branch = target_branch
589
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
590
parse_github_branch_url(self.target_branch))
591
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
592
parse_github_branch_url(self.source_branch))
594
def get_infotext(self):
595
"""Determine the initial comment for the merge proposal."""
597
info.append("Merge %s into %s:%s\n" % (
598
self.source_branch_name, self.target_owner,
599
self.target_branch_name))
600
info.append("Source: %s\n" % self.source_branch.user_url)
601
info.append("Target: %s\n" % self.target_branch.user_url)
604
def get_initial_body(self):
605
"""Get a body for the proposal for the user to modify.
607
:return: a str or None.
611
def create_proposal(self, description, reviewers=None, labels=None,
612
prerequisite_branch=None, commit_message=None,
613
work_in_progress=False, allow_collaboration=False):
614
"""Perform the submission."""
615
if prerequisite_branch is not None:
616
raise PrerequisiteBranchUnsupported(self)
617
# Note that commit_message is ignored, since github doesn't support it.
618
# TODO(jelmer): Probe for right repo name
619
if self.target_repo_name.endswith('.git'):
620
self.target_repo_name = self.target_repo_name[:-4]
621
# TODO(jelmer): Allow setting title explicitly?
622
title = determine_title(description)
623
target_repo = self.gh._get_repo(
624
self.target_owner, self.target_repo_name)
628
for reviewer in reviewers:
630
user = self.gh._get_user_by_email(reviewer)
632
user = self.gh._get_user(reviewer)
633
assignees.append(user['login'])
637
pull_request = self.gh._create_pull(
638
strip_optional(target_repo['pulls_url']),
639
title=title, body=description,
640
head="%s:%s" % (self.source_owner, self.source_branch_name),
641
base=self.target_branch_name,
642
labels=labels, assignee=assignees,
643
draft=work_in_progress,
644
maintainer_can_modify=allow_collaboration,
646
except ValidationFailed:
647
raise MergeProposalExists(self.source_branch.user_url)
648
return GitHubMergeProposal(self.gh, pull_request)