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 InvalidHttpResponse, PermissionDenied
48
from ...git.urls import git_url_to_bzr_url
49
from ...i18n import gettext
50
from ...sixish import PY3
51
from ...trace import note
52
from ...transport import get_transport
53
from ...transport.http import default_user_agent
56
GITHUB_HOST = 'github.com'
57
WEB_GITHUB_URL = 'https://github.com'
58
API_GITHUB_URL = 'https://api.github.com'
62
def store_github_token(scheme, host, token):
63
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
67
def retrieve_github_token(scheme, host):
68
path = os.path.join(bedding.config_dir(), 'github.conf')
69
if not os.path.exists(path):
71
with open(path, 'r') as f:
72
return f.read().strip()
75
class ValidationFailed(errors.BzrError):
77
_fmt = "GitHub validation failed: %(error)s"
79
def __init__(self, error):
80
errors.BzrError.__init__(self)
84
class NotGitHubUrl(errors.BzrError):
86
_fmt = "Not a GitHub URL: %(url)s"
88
def __init__(self, url):
89
errors.BzrError.__init__(self)
93
class GitHubLoginRequired(HosterLoginRequired):
95
_fmt = "Action requires GitHub login."
101
user_agent = default_user_agent()
102
auth = AuthenticationConfig()
104
credentials = auth.get_credentials('https', GITHUB_HOST)
105
if credentials is not None:
106
return Github(credentials['user'], credentials['password'],
107
user_agent=user_agent)
109
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
110
if token is not None:
111
return Github(token, user_agent=user_agent)
113
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
114
return Github(user_agent=user_agent)
117
class GitHubMergeProposal(MergeProposal):
119
def __init__(self, gh, pr):
124
return "<%s at %r>" % (type(self).__name__, self.url)
128
return self._pr['html_url']
130
def _branch_from_part(self, part):
131
if part['repo'] is None:
133
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
135
def get_source_branch_url(self):
136
return self._branch_from_part(self._pr['head'])
138
def get_target_branch_url(self):
139
return self._branch_from_part(self._pr['base'])
141
def get_source_project(self):
142
return self._pr['head']['repo']['full_name']
144
def get_target_project(self):
145
return self._pr['base']['repo']['full_name']
147
def get_description(self):
148
return self._pr['body']
150
def get_commit_message(self):
153
def set_commit_message(self, message):
154
raise errors.UnsupportedOperation(self.set_commit_message, self)
156
def _patch(self, data):
157
response = self._gh._api_request(
158
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
159
if response.status == 422:
160
raise ValidationFailed(json.loads(response.text))
161
if response.status != 200:
162
raise InvalidHttpResponse(self._pr['url'], response.text)
163
self._pr = json.loads(response.text)
165
def set_description(self, description):
168
'title': determine_title(description),
172
return bool(self._pr.get('merged_at'))
175
return self._pr['state'] == 'closed' and not bool(self._pr.get('merged_at'))
179
self._patch({'state': 'open'})
180
except ValidationFailed as e:
181
raise ReopenFailed(e.error['errors'][0]['message'])
184
self._patch({'state': 'closed'})
186
def can_be_merged(self):
187
return self._pr['mergeable']
189
def merge(self, commit_message=None):
190
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
191
self._pr.merge(commit_message=commit_message)
193
def get_merged_by(self):
194
merged_by = self._pr.get('merged_by')
195
if merged_by is None:
197
return merged_by['login']
199
def get_merged_at(self):
200
merged_at = self._pr.get('merged_at')
201
if merged_at is None:
204
return iso8601.parse_date(merged_at)
207
def parse_github_url(url):
208
(scheme, user, password, host, port, path) = urlutils.parse_url(
210
if host != GITHUB_HOST:
211
raise NotGitHubUrl(url)
212
(owner, repo_name) = path.strip('/').split('/')
213
if repo_name.endswith('.git'):
214
repo_name = repo_name[:-4]
215
return owner, repo_name
218
def parse_github_branch_url(branch):
219
url = urlutils.strip_segment_parameters(branch.user_url)
220
owner, repo_name = parse_github_url(url)
221
return owner, repo_name, branch.name
224
def github_url_to_bzr_url(url, branch_name):
226
branch_name = branch_name.encode('utf-8')
227
return git_url_to_bzr_url(url, branch_name)
230
def strip_optional(url):
231
return url.split('{')[0]
234
class GitHub(Hoster):
238
supports_merge_proposal_labels = True
239
supports_merge_proposal_commit_message = False
240
supports_allow_collaboration = True
241
merge_proposal_description_format = 'markdown'
246
def _api_request(self, method, path, body=None):
248
'Content-Type': 'application/json',
249
'Accept': 'application/vnd.github.v3+json'}
251
headers['Authorization'] = 'token %s' % self._token
252
response = self.transport.request(
253
method, urlutils.join(self.transport.base, path),
254
headers=headers, body=body, retries=3)
255
if response.status == 401:
256
raise GitHubLoginRequired(self)
259
def _get_repo(self, owner, repo):
260
path = 'repos/%s/%s' % (owner, repo)
261
response = self._api_request('GET', path)
262
if response.status == 404:
263
raise NoSuchProject(path)
264
if response.status == 200:
265
return json.loads(response.text)
266
raise InvalidHttpResponse(path, response.text)
268
def _get_repo_pulls(self, path, head=None, state=None):
272
params['head'] = head
273
if state is not None:
274
params['state'] = state
275
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
276
for k, v in params.items()])
277
response = self._api_request('GET', path)
278
if response.status == 404:
279
raise NoSuchProject(path)
280
if response.status == 200:
281
return json.loads(response.text)
282
raise InvalidHttpResponse(path, response.text)
284
def _create_pull(self, path, title, head, base, body=None, labels=None,
285
assignee=None, draft=False, maintainer_can_modify=False):
291
'maintainer_can_modify': maintainer_can_modify,
293
if labels is not None:
294
data['labels'] = labels
295
if assignee is not None:
296
data['assignee'] = assignee
300
response = self._api_request(
301
'POST', path, body=json.dumps(data).encode('utf-8'))
302
if response.status == 403:
303
raise PermissionDenied(path, response.text)
304
if response.status != 201:
305
raise InvalidHttpResponse(path, 'req is invalid %d %r: %r' % (response.status, data, response.text))
306
return json.loads(response.text)
308
def _get_user_by_email(self, email):
309
path = 'search/users?q=%s+in:email' % email
310
response = self._api_request('GET', path)
311
if response.status != 200:
312
raise InvalidHttpResponse(path, response.text)
313
ret = json.loads(response.text)
314
if ret['total_count'] == 0:
315
raise KeyError('no user with email %s' % email)
316
elif ret['total_count'] > 1:
317
raise ValueError('more than one result for email %s' % email)
318
return ret['items'][0]
320
def _get_user(self, username=None):
322
path = 'users/%s' % username
325
response = self._api_request('GET', path)
326
if response.status != 200:
327
raise InvalidHttpResponse(path, response.text)
328
return json.loads(response.text)
330
def _get_organization(self, name):
331
path = 'orgs/%s' % name
332
response = self._api_request('GET', path)
333
if response.status != 200:
334
raise InvalidHttpResponse(path, response.text)
335
return json.loads(response.text)
337
def _list_paged(self, path, parameters=None, per_page=None):
338
if parameters is None:
341
parameters = dict(parameters.items())
343
parameters['per_page'] = str(per_page)
347
parameters['page'] = str(page)
348
response = self._api_request(
350
';'.join(['%s=%s' % (k, urlutils.quote(v))
351
for (k, v) in parameters.items()]))
352
if response.status != 200:
353
raise InvalidHttpResponse(path, response.text)
354
data = json.loads(response.text)
355
for entry in data['items']:
358
if i >= data['total_count']:
362
def _search_issues(self, query):
363
path = 'search/issues'
364
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
366
def _create_fork(self, path, owner=None):
367
if owner and owner != self._current_user['login']:
368
path += '?organization=%s' % owner
369
response = self._api_request('POST', path)
370
if response.status != 202:
371
raise InvalidHttpResponse(path, 'status: %d, %r' % (response.status, response.text))
372
return json.loads(response.text)
376
return WEB_GITHUB_URL
378
def __init__(self, transport):
379
self._token = retrieve_github_token('https', GITHUB_HOST)
380
self.transport = transport
381
self._current_user = self._get_user()
383
def publish_derived(self, local_branch, base_branch, name, project=None,
384
owner=None, revision_id=None, overwrite=False,
385
allow_lossy=True, tag_selector=None):
386
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
387
base_repo = self._get_repo(base_owner, base_project)
389
owner = self._current_user['login']
391
project = base_repo['name']
393
remote_repo = self._get_repo(owner, project)
394
except NoSuchProject:
395
base_repo = self._get_repo(base_owner, base_project)
396
remote_repo = self._create_fork(base_repo['forks_url'], owner)
397
note(gettext('Forking new repository %s from %s') %
398
(remote_repo['html_url'], base_repo['html_url']))
400
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
401
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
403
push_result = remote_dir.push_branch(
404
local_branch, revision_id=revision_id, overwrite=overwrite,
405
name=name, tag_selector=tag_selector)
406
except errors.NoRoundtrippingSupport:
409
push_result = remote_dir.push_branch(
410
local_branch, revision_id=revision_id,
411
overwrite=overwrite, name=name, lossy=True,
412
tag_selector=tag_selector)
413
return push_result.target_branch, github_url_to_bzr_url(
414
remote_repo['html_url'], name)
416
def get_push_url(self, branch):
417
owner, project, branch_name = parse_github_branch_url(branch)
418
repo = self._get_repo(owner, project)
419
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
421
def get_derived_branch(self, base_branch, name, project=None, owner=None):
422
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
423
base_repo = self._get_repo(base_owner, base_project)
425
owner = self._current_user['login']
427
project = base_repo['name']
429
remote_repo = self._get_repo(owner, project)
430
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
431
return _mod_branch.Branch.open(full_url)
432
except NoSuchProject:
433
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
435
def get_proposer(self, source_branch, target_branch):
436
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
438
def iter_proposals(self, source_branch, target_branch, status='open'):
439
(source_owner, source_repo_name, source_branch_name) = (
440
parse_github_branch_url(source_branch))
441
(target_owner, target_repo_name, target_branch_name) = (
442
parse_github_branch_url(target_branch))
443
target_repo = self._get_repo(target_owner, target_repo_name)
449
pulls = self._get_repo_pulls(
450
strip_optional(target_repo['pulls_url']),
451
head=target_branch_name,
454
if (status == 'closed' and pull['merged'] or
455
status == 'merged' and not pull['merged']):
457
if pull['head']['ref'] != source_branch_name:
459
if pull['head']['repo'] is None:
460
# Repo has gone the way of the dodo
462
if (pull['head']['repo']['owner']['login'] != source_owner or
463
pull['head']['repo']['name'] != source_repo_name):
465
yield GitHubMergeProposal(self, pull)
467
def hosts(self, branch):
469
parse_github_branch_url(branch)
476
def probe_from_url(cls, url, possible_transports=None):
478
parse_github_url(url)
480
raise UnsupportedHoster(url)
481
transport = get_transport(
482
API_GITHUB_URL, possible_transports=possible_transports)
483
return cls(transport)
486
def iter_instances(cls):
487
yield cls(get_transport(API_GITHUB_URL))
489
def iter_my_proposals(self, status='open'):
492
query.append('is:open')
493
elif status == 'closed':
494
query.append('is:unmerged')
495
# Also use "is:closed" otherwise unmerged open pull requests are
497
query.append('is:closed')
498
elif status == 'merged':
499
query.append('is:merged')
500
query.append('author:%s' % self._current_user['login'])
501
for issue in self._search_issues(query=' '.join(query)):
502
url = issue['pull_request']['url']
503
response = self._api_request('GET', url)
504
if response.status != 200:
505
raise InvalidHttpResponse(url, response.text)
506
yield GitHubMergeProposal(self, json.loads(response.text))
508
def get_proposal_by_url(self, url):
509
raise UnsupportedHoster(url)
511
def iter_my_forks(self):
512
response = self._api_request('GET', '/user/repos')
513
if response.status != 200:
514
raise InvalidHttpResponse(url, response.text)
515
for project in json.loads(response.text):
516
if not project['fork']:
518
yield project['full_name']
520
def delete_project(self, path):
521
path = 'repos/' + path
522
response = self._api_request('DELETE', path)
523
if response.status == 404:
524
raise NoSuchProject(path)
525
if response.status == 204:
527
if response.status == 200:
528
return json.loads(response.text)
529
raise InvalidHttpResponse(path, response.text)
532
class GitHubMergeProposalBuilder(MergeProposalBuilder):
534
def __init__(self, gh, source_branch, target_branch):
536
self.source_branch = source_branch
537
self.target_branch = target_branch
538
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
539
parse_github_branch_url(self.target_branch))
540
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
541
parse_github_branch_url(self.source_branch))
543
def get_infotext(self):
544
"""Determine the initial comment for the merge proposal."""
546
info.append("Merge %s into %s:%s\n" % (
547
self.source_branch_name, self.target_owner,
548
self.target_branch_name))
549
info.append("Source: %s\n" % self.source_branch.user_url)
550
info.append("Target: %s\n" % self.target_branch.user_url)
553
def get_initial_body(self):
554
"""Get a body for the proposal for the user to modify.
556
:return: a str or None.
560
def create_proposal(self, description, reviewers=None, labels=None,
561
prerequisite_branch=None, commit_message=None,
562
work_in_progress=False, allow_collaboration=False):
563
"""Perform the submission."""
564
if prerequisite_branch is not None:
565
raise PrerequisiteBranchUnsupported(self)
566
# Note that commit_message is ignored, since github doesn't support it.
567
# TODO(jelmer): Probe for right repo name
568
if self.target_repo_name.endswith('.git'):
569
self.target_repo_name = self.target_repo_name[:-4]
570
# TODO(jelmer): Allow setting title explicitly?
571
title = determine_title(description)
572
target_repo = self.gh._get_repo(
573
self.target_owner, self.target_repo_name)
577
for reviewer in reviewers:
579
user = self.gh._get_user_by_email(reviewer)
581
user = self.gh._get_user(reviewer)
582
assignees.append(user['login'])
586
pull_request = self.gh._create_pull(
587
strip_optional(target_repo['pulls_url']),
588
title=title, body=description,
589
head="%s:%s" % (self.source_owner, self.source_branch_name),
590
base=self.target_branch_name,
591
labels=labels, assignee=assignees,
592
draft=work_in_progress,
593
maintainer_can_modify=allow_collaboration,
595
except ValidationFailed:
596
raise MergeProposalExists(self.source_branch.user_url)
597
return GitHubMergeProposal(self.gh, pull_request)