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
merge_proposal_description_format = 'markdown'
245
def _api_request(self, method, path, body=None):
247
'Content-Type': 'application/json',
248
'Accept': 'application/vnd.github.v3+json'}
250
headers['Authorization'] = 'token %s' % self._token
251
response = self.transport.request(
252
method, urlutils.join(self.transport.base, path),
253
headers=headers, body=body, retries=3)
254
if response.status == 401:
255
raise GitHubLoginRequired(self)
258
def _get_repo(self, owner, repo):
259
path = 'repos/%s/%s' % (owner, repo)
260
response = self._api_request('GET', path)
261
if response.status == 404:
262
raise NoSuchProject(path)
263
if response.status == 200:
264
return json.loads(response.text)
265
raise InvalidHttpResponse(path, response.text)
267
def _get_repo_pulls(self, path, head=None, state=None):
271
params['head'] = head
272
if state is not None:
273
params['state'] = state
274
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
275
for k, v in params.items()])
276
response = self._api_request('GET', path)
277
if response.status == 404:
278
raise NoSuchProject(path)
279
if response.status == 200:
280
return json.loads(response.text)
281
raise InvalidHttpResponse(path, response.text)
283
def _create_pull(self, path, title, head, base, body=None, labels=None, assignee=None):
289
if labels is not None:
290
data['labels'] = labels
291
if assignee is not None:
292
data['assignee'] = assignee
296
response = self._api_request(
297
'POST', path, body=json.dumps(data).encode('utf-8'))
298
if response.status == 403:
299
raise PermissionDenied(path, response.text)
300
if response.status != 201:
301
raise InvalidHttpResponse(path, 'req is invalid %d %r: %r' % (response.status, data, response.text))
302
return json.loads(response.text)
304
def _get_user_by_email(self, email):
305
path = 'search/users?q=%s+in:email' % email
306
response = self._api_request('GET', path)
307
if response.status != 200:
308
raise InvalidHttpResponse(path, response.text)
309
ret = json.loads(response.text)
310
if ret['total_count'] == 0:
311
raise KeyError('no user with email %s' % email)
312
elif ret['total_count'] > 1:
313
raise ValueError('more than one result for email %s' % email)
314
return ret['items'][0]
316
def _get_user(self, username=None):
318
path = 'users/%s' % username
321
response = self._api_request('GET', path)
322
if response.status != 200:
323
raise InvalidHttpResponse(path, response.text)
324
return json.loads(response.text)
326
def _get_organization(self, name):
327
path = 'orgs/%s' % name
328
response = self._api_request('GET', path)
329
if response.status != 200:
330
raise InvalidHttpResponse(path, response.text)
331
return json.loads(response.text)
333
def _list_paged(self, path, parameters=None, per_page=None):
334
if parameters is None:
337
parameters = dict(parameters.items())
339
parameters['per_page'] = str(per_page)
343
parameters['page'] = str(page)
344
response = self._api_request(
346
';'.join(['%s=%s' % (k, urlutils.quote(v))
347
for (k, v) in parameters.items()]))
348
if response.status != 200:
349
raise InvalidHttpResponse(path, response.text)
350
data = json.loads(response.text)
351
for entry in data['items']:
354
if i >= data['total_count']:
358
def _search_issues(self, query):
359
path = 'search/issues'
360
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
362
def _create_fork(self, path, owner=None):
363
if owner and owner != self._current_user['login']:
364
path += '?organization=%s' % owner
365
response = self._api_request('POST', path)
366
if response.status != 202:
367
raise InvalidHttpResponse(path, 'status: %d, %r' % (response.status, response.text))
368
return json.loads(response.text)
372
return WEB_GITHUB_URL
374
def __init__(self, transport):
375
self._token = retrieve_github_token('https', GITHUB_HOST)
376
self.transport = transport
377
self._current_user = self._get_user()
379
def publish_derived(self, local_branch, base_branch, name, project=None,
380
owner=None, revision_id=None, overwrite=False,
382
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
383
base_repo = self._get_repo(base_owner, base_project)
385
owner = self._current_user['login']
387
project = base_repo['name']
389
remote_repo = self._get_repo(owner, project)
390
except NoSuchProject:
391
base_repo = self._get_repo(base_owner, base_project)
392
remote_repo = self._create_fork(base_repo['forks_url'], owner)
393
note(gettext('Forking new repository %s from %s') %
394
(remote_repo['html_url'], base_repo['html_url']))
396
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
397
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
399
push_result = remote_dir.push_branch(
400
local_branch, revision_id=revision_id, overwrite=overwrite,
402
except errors.NoRoundtrippingSupport:
405
push_result = remote_dir.push_branch(
406
local_branch, revision_id=revision_id,
407
overwrite=overwrite, name=name, lossy=True)
408
return push_result.target_branch, github_url_to_bzr_url(
409
remote_repo['html_url'], name)
411
def get_push_url(self, branch):
412
owner, project, branch_name = parse_github_branch_url(branch)
413
repo = self._get_repo(owner, project)
414
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
416
def get_derived_branch(self, base_branch, name, project=None, owner=None):
417
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
418
base_repo = self._get_repo(base_owner, base_project)
420
owner = self._current_user['login']
422
project = base_repo['name']
424
remote_repo = self._get_repo(owner, project)
425
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
426
return _mod_branch.Branch.open(full_url)
427
except NoSuchProject:
428
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
430
def get_proposer(self, source_branch, target_branch):
431
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
433
def iter_proposals(self, source_branch, target_branch, status='open'):
434
(source_owner, source_repo_name, source_branch_name) = (
435
parse_github_branch_url(source_branch))
436
(target_owner, target_repo_name, target_branch_name) = (
437
parse_github_branch_url(target_branch))
438
target_repo = self._get_repo(target_owner, target_repo_name)
444
pulls = self._get_repo_pulls(
445
strip_optional(target_repo['pulls_url']),
446
head=target_branch_name,
449
if (status == 'closed' and pull['merged'] or
450
status == 'merged' and not pull['merged']):
452
if pull['head']['ref'] != source_branch_name:
454
if pull['head']['repo'] is None:
455
# Repo has gone the way of the dodo
457
if (pull['head']['repo']['owner']['login'] != source_owner or
458
pull['head']['repo']['name'] != source_repo_name):
460
yield GitHubMergeProposal(self, pull)
462
def hosts(self, branch):
464
parse_github_branch_url(branch)
471
def probe_from_url(cls, url, possible_transports=None):
473
parse_github_url(url)
475
raise UnsupportedHoster(url)
476
transport = get_transport(
477
API_GITHUB_URL, possible_transports=possible_transports)
478
return cls(transport)
481
def iter_instances(cls):
482
yield cls(get_transport(API_GITHUB_URL))
484
def iter_my_proposals(self, status='open'):
487
query.append('is:open')
488
elif status == 'closed':
489
query.append('is:unmerged')
490
# Also use "is:closed" otherwise unmerged open pull requests are
492
query.append('is:closed')
493
elif status == 'merged':
494
query.append('is:merged')
495
query.append('author:%s' % self._current_user['login'])
496
for issue in self._search_issues(query=' '.join(query)):
497
url = issue['pull_request']['url']
498
response = self._api_request('GET', url)
499
if response.status != 200:
500
raise InvalidHttpResponse(url, response.text)
501
yield GitHubMergeProposal(self, json.loads(response.text))
503
def get_proposal_by_url(self, url):
504
raise UnsupportedHoster(url)
506
def iter_my_forks(self):
507
response = self._api_request('GET', '/user/repos')
508
if response.status != 200:
509
raise InvalidHttpResponse(url, response.text)
510
for project in json.loads(response.text):
511
if not project['fork']:
513
yield project['full_name']
515
def delete_project(self, path):
516
path = 'repos/' + path
517
response = self._api_request('DELETE', path)
518
if response.status == 404:
519
raise NoSuchProject(path)
520
if response.status == 204:
522
if response.status == 200:
523
return json.loads(response.text)
524
raise InvalidHttpResponse(path, response.text)
527
class GitHubMergeProposalBuilder(MergeProposalBuilder):
529
def __init__(self, gh, source_branch, target_branch):
531
self.source_branch = source_branch
532
self.target_branch = target_branch
533
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
534
parse_github_branch_url(self.target_branch))
535
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
536
parse_github_branch_url(self.source_branch))
538
def get_infotext(self):
539
"""Determine the initial comment for the merge proposal."""
541
info.append("Merge %s into %s:%s\n" % (
542
self.source_branch_name, self.target_owner,
543
self.target_branch_name))
544
info.append("Source: %s\n" % self.source_branch.user_url)
545
info.append("Target: %s\n" % self.target_branch.user_url)
548
def get_initial_body(self):
549
"""Get a body for the proposal for the user to modify.
551
:return: a str or None.
555
def create_proposal(self, description, reviewers=None, labels=None,
556
prerequisite_branch=None, commit_message=None):
557
"""Perform the submission."""
558
if prerequisite_branch is not None:
559
raise PrerequisiteBranchUnsupported(self)
560
# Note that commit_message is ignored, since github doesn't support it.
561
# TODO(jelmer): Probe for right repo name
562
if self.target_repo_name.endswith('.git'):
563
self.target_repo_name = self.target_repo_name[:-4]
564
# TODO(jelmer): Allow setting title explicitly?
565
title = determine_title(description)
566
# TODO(jelmer): Set maintainers_can_modify?
567
target_repo = self.gh._get_repo(
568
self.target_owner, self.target_repo_name)
572
for reviewer in reviewers:
574
user = self.gh._get_user_by_email(reviewer)
576
user = self.gh._get_user(reviewer)
577
assignees.append(user['login'])
581
pull_request = self.gh._create_pull(
582
strip_optional(target_repo['pulls_url']),
583
title=title, body=description,
584
head="%s:%s" % (self.source_owner, self.source_branch_name),
585
base=self.target_branch_name,
586
labels=labels, assignee=assignees)
587
except ValidationFailed:
588
raise MergeProposalExists(self.source_branch.user_url)
589
return GitHubMergeProposal(self.gh, pull_request)