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 (
31
PrerequisiteBranchUnsupported,
38
branch as _mod_branch,
43
version_string as breezy_version,
45
from ...config import AuthenticationConfig, GlobalStack
46
from ...errors import InvalidHttpResponse
47
from ...git.urls import git_url_to_bzr_url
48
from ...i18n import gettext
49
from ...sixish import PY3
50
from ...trace import note
51
from ...transport import get_transport
52
from ...transport.http import default_user_agent
55
GITHUB_HOST = 'github.com'
56
WEB_GITHUB_URL = 'https://github.com'
57
API_GITHUB_URL = 'https://api.github.com'
61
def store_github_token(scheme, host, token):
62
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
66
def retrieve_github_token(scheme, host):
67
path = os.path.join(bedding.config_dir(), 'github.conf')
68
if not os.path.exists(path):
70
with open(path, 'r') as f:
71
return f.read().strip()
74
def determine_title(description):
75
return description.splitlines()[0]
78
class ValidationFailed(errors.BzrError):
80
_fmt = "GitHub validation failed: %(error)s"
82
def __init__(self, error):
83
errors.BzrError.__init__(self)
87
class NotGitHubUrl(errors.BzrError):
89
_fmt = "Not a GitHub URL: %(url)s"
91
def __init__(self, url):
92
errors.BzrError.__init__(self)
96
class GitHubLoginRequired(HosterLoginRequired):
98
_fmt = "Action requires GitHub login."
101
def connect_github():
102
"""Connect to GitHub.
104
user_agent = default_user_agent()
105
auth = AuthenticationConfig()
107
credentials = auth.get_credentials('https', GITHUB_HOST)
108
if credentials is not None:
109
return Github(credentials['user'], credentials['password'],
110
user_agent=user_agent)
112
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
113
if token is not None:
114
return Github(token, user_agent=user_agent)
116
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
117
return Github(user_agent=user_agent)
120
class GitHubMergeProposal(MergeProposal):
122
def __init__(self, gh, pr):
127
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_target_branch_url(self):
142
return self._branch_from_part(self._pr['base'])
144
def get_description(self):
145
return self._pr['body']
147
def get_commit_message(self):
150
def set_commit_message(self, message):
151
self._patch({'title': message})
153
def _patch(self, data):
154
response = self._gh._api_request(
155
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
156
if response.status == 422:
157
raise ValidationFailed(json.loads(response.text))
158
if response.status != 200:
159
raise InvalidHttpResponse(self._pr['url'], response.text)
160
self._pr = json.loads(response.text)
162
def set_description(self, description):
165
'title': determine_title(description),
169
return bool(self._pr.get('merged_at'))
172
return self._pr['state'] == 'closed' and not bool(self._pr.get('merged_at'))
176
self._patch({'state': 'open'})
177
except ValidationFailed as e:
178
raise ReopenFailed(e.error['errors'][0]['message'])
181
self._patch({'state': 'closed'})
183
def can_be_merged(self):
184
return self._pr['mergeable']
186
def merge(self, commit_message=None):
187
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
188
self._pr.merge(commit_message=commit_message)
191
def parse_github_url(url):
192
(scheme, user, password, host, port, path) = urlutils.parse_url(
194
if host != GITHUB_HOST:
195
raise NotGitHubUrl(url)
196
(owner, repo_name) = path.strip('/').split('/')
197
if repo_name.endswith('.git'):
198
repo_name = repo_name[:-4]
199
return owner, repo_name
202
def parse_github_branch_url(branch):
203
url = urlutils.split_segment_parameters(branch.user_url)[0]
204
owner, repo_name = parse_github_url(url)
205
return owner, repo_name, branch.name
208
def github_url_to_bzr_url(url, branch_name):
210
branch_name = branch_name.encode('utf-8')
211
return git_url_to_bzr_url(url, branch_name)
214
def strip_optional(url):
215
return url.split('{')[0]
218
class GitHub(Hoster):
222
supports_merge_proposal_labels = True
223
supports_merge_proposal_commit_message = False
228
def _api_request(self, method, path, body=None):
230
'Accept': 'application/vnd.github.v3+json'}
232
headers['Authorization'] = 'token %s' % self._token
233
response = self.transport.request(
234
method, urlutils.join(self.transport.base, path),
235
headers=headers, body=body, retries=3)
236
if response.status == 401:
237
raise GitHubLoginRequired(self)
240
def _get_repo(self, owner, repo):
241
path = 'repos/%s/%s' % (owner, repo)
242
response = self._api_request('GET', path)
243
if response.status == 404:
244
raise NoSuchProject(path)
245
if response.status == 200:
246
return json.loads(response.text)
247
raise InvalidHttpResponse(path, response.text)
249
def _get_repo_pulls(self, path, head=None, state=None):
253
params['head'] = head
254
if state is not None:
255
params['state'] = state
256
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
257
for k, v in params.items()])
258
response = self._api_request('GET', path)
259
if response.status == 404:
260
raise NoSuchProject(path)
261
if response.status == 200:
262
return json.loads(response.text)
263
raise InvalidHttpResponse(path, response.text)
265
def _create_pull(self, path, title, head, base, body=None):
274
response = self._api_request(
275
'POST', path, body=json.dumps(data).encode('utf-8'))
276
if response.status != 201:
277
raise InvalidHttpResponse(path, response.text)
278
return json.loads(response.text)
280
def _get_user_by_email(self, email):
281
path = 'search/users?q=%s+in:email' % email
282
response = self._api_request('GET', path)
283
if response.status != 200:
284
raise InvalidHttpResponse(path, response.text)
285
ret = json.loads(response.text)
286
if ret['total_count'] == 0:
287
raise KeyError('no user with email %s' % email)
288
elif ret['total_count'] > 1:
289
raise ValueError('more than one result for email %s' % email)
290
return ret['items'][0]
292
def _get_user(self, username=None):
294
path = 'users/:%s' % username
297
response = self._api_request('GET', path)
298
if response.status != 200:
299
raise InvalidHttpResponse(path, response.text)
300
return json.loads(response.text)
302
def _get_organization(self, name):
303
path = 'orgs/:%s' % name
304
response = self._api_request('GET', path)
305
if response.status != 200:
306
raise InvalidHttpResponse(path, response.text)
307
return json.loads(response.text)
309
def _list_paged(self, path, parameters=None, per_page=None):
310
if parameters is None:
313
parameters = dict(parameters.items())
315
parameters['per_page'] = str(per_page)
319
parameters['page'] = str(page)
320
response = self._api_request(
322
';'.join(['%s=%s' % (k, urlutils.quote(v))
323
for (k, v) in parameters.items()]))
324
if response.status != 200:
325
raise InvalidHttpResponse(path, response.text)
326
data = json.loads(response.text)
327
for entry in data['items']:
330
if i >= data['total_count']:
334
def _search_issues(self, query):
335
path = 'search/issues'
336
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
338
def _create_fork(self, path, owner=None):
339
if owner and owner != self._current_user['login']:
340
path += '?organization=%s' % owner
341
response = self._api_request('POST', path)
342
if response.status != 202:
343
raise InvalidHttpResponse(path, 'status: %d, %r' % (response.status, response.text))
344
return json.loads(response.text)
348
return WEB_GITHUB_URL
350
def __init__(self, transport):
351
self._token = retrieve_github_token('https', GITHUB_HOST)
352
self.transport = transport
353
self._current_user = self._get_user()
355
def publish_derived(self, local_branch, base_branch, name, project=None,
356
owner=None, revision_id=None, overwrite=False,
358
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
359
base_repo = self._get_repo(base_owner, base_project)
361
owner = self._current_user['login']
363
project = base_repo['name']
365
remote_repo = self._get_repo(owner, project)
366
except NoSuchProject:
367
base_repo = self._get_repo(base_owner, base_project)
368
remote_repo = self._create_fork(base_repo['forks_url'], owner)
369
note(gettext('Forking new repository %s from %s') %
370
(remote_repo['html_url'], base_repo['html_url']))
372
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
373
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
375
push_result = remote_dir.push_branch(
376
local_branch, revision_id=revision_id, overwrite=overwrite,
378
except errors.NoRoundtrippingSupport:
381
push_result = remote_dir.push_branch(
382
local_branch, revision_id=revision_id,
383
overwrite=overwrite, name=name, lossy=True)
384
return push_result.target_branch, github_url_to_bzr_url(
385
remote_repo['html_url'], name)
387
def get_push_url(self, branch):
388
owner, project, branch_name = parse_github_branch_url(branch)
389
repo = self._get_repo(owner, project)
390
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
392
def get_derived_branch(self, base_branch, name, project=None, owner=None):
393
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
394
base_repo = self._get_repo(base_owner, base_project)
396
owner = self._current_user['login']
398
project = base_repo['name']
400
remote_repo = self._get_repo(owner, project)
401
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
402
return _mod_branch.Branch.open(full_url)
403
except NoSuchProject:
404
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
406
def get_proposer(self, source_branch, target_branch):
407
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
409
def iter_proposals(self, source_branch, target_branch, status='open'):
410
(source_owner, source_repo_name, source_branch_name) = (
411
parse_github_branch_url(source_branch))
412
(target_owner, target_repo_name, target_branch_name) = (
413
parse_github_branch_url(target_branch))
414
target_repo = self._get_repo(target_owner, target_repo_name)
420
pulls = self._get_repo_pulls(
421
strip_optional(target_repo['pulls_url']),
422
head=target_branch_name,
425
if (status == 'closed' and pull['merged'] or
426
status == 'merged' and not pull['merged']):
428
if pull['head']['ref'] != source_branch_name:
430
if pull['head']['repo'] is None:
431
# Repo has gone the way of the dodo
433
if (pull['head']['repo']['owner']['login'] != source_owner or
434
pull['head']['repo']['name'] != source_repo_name):
436
yield GitHubMergeProposal(self, pull)
438
def hosts(self, branch):
440
parse_github_branch_url(branch)
447
def probe_from_url(cls, url, possible_transports=None):
449
parse_github_url(url)
451
raise UnsupportedHoster(url)
452
transport = get_transport(
453
API_GITHUB_URL, possible_transports=possible_transports)
454
return cls(transport)
457
def iter_instances(cls):
458
yield cls(get_transport(API_GITHUB_URL))
460
def iter_my_proposals(self, status='open'):
463
query.append('is:open')
464
elif status == 'closed':
465
query.append('is:unmerged')
466
# Also use "is:closed" otherwise unmerged open pull requests are
468
query.append('is:closed')
469
elif status == 'merged':
470
query.append('is:merged')
471
query.append('author:%s' % self._current_user['login'])
472
for issue in self._search_issues(query=' '.join(query)):
473
url = issue['pull_request']['url']
474
response = self._api_request('GET', url)
475
if response.status != 200:
476
raise InvalidHttpResponse(url, response.text)
477
yield GitHubMergeProposal(self, json.loads(response.text))
479
def get_proposal_by_url(self, url):
480
raise UnsupportedHoster(url)
483
class GitHubMergeProposalBuilder(MergeProposalBuilder):
485
def __init__(self, gh, source_branch, target_branch):
487
self.source_branch = source_branch
488
self.target_branch = target_branch
489
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
490
parse_github_branch_url(self.target_branch))
491
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
492
parse_github_branch_url(self.source_branch))
494
def get_infotext(self):
495
"""Determine the initial comment for the merge proposal."""
497
info.append("Merge %s into %s:%s\n" % (
498
self.source_branch_name, self.target_owner,
499
self.target_branch_name))
500
info.append("Source: %s\n" % self.source_branch.user_url)
501
info.append("Target: %s\n" % self.target_branch.user_url)
504
def get_initial_body(self):
505
"""Get a body for the proposal for the user to modify.
507
:return: a str or None.
511
def create_proposal(self, description, reviewers=None, labels=None,
512
prerequisite_branch=None, commit_message=None):
513
"""Perform the submission."""
514
if prerequisite_branch is not None:
515
raise PrerequisiteBranchUnsupported(self)
516
# Note that commit_message is ignored, since github doesn't support it.
517
# TODO(jelmer): Probe for right repo name
518
if self.target_repo_name.endswith('.git'):
519
self.target_repo_name = self.target_repo_name[:-4]
520
# TODO(jelmer): Allow setting title explicitly?
521
title = determine_title(description)
522
# TODO(jelmer): Set maintainers_can_modify?
523
target_repo = self.gh._get_repo(
524
self.target_owner, self.target_repo_name)
526
pull_request = self.gh._create_pull(
527
strip_optional(target_repo['pulls_url']),
528
title=title, body=description,
529
head="%s:%s" % (self.source_owner, self.source_branch_name),
530
base=self.target_branch_name)
531
except ValidationFailed:
532
raise MergeProposalExists(self.source_branch.user_url)
535
for reviewer in reviewers:
537
user = self.gh._get_user_by_email(reviewer)
539
user = self.gh._get_user(reviewer)
540
assignees.append(user['login'])
541
if labels or assignees:
544
data['labels'] = labels
546
data['assignees'] = assignees
547
response = self.gh._api_request(
548
'PATCH', pull_request['issue_url'], body=json.dumps(data).encode('utf-8'))
549
if response.status == 422:
550
raise ValidationFailed(json.loads(response.text))
551
if response.status != 200:
552
raise InvalidHttpResponse(pull_request['issue_url'], response.text)
553
return GitHubMergeProposal(self.gh, pull_request)