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'
60
def store_github_token(scheme, host, token):
61
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
65
def retrieve_github_token(scheme, host):
66
path = os.path.join(bedding.config_dir(), 'github.conf')
67
if not os.path.exists(path):
69
with open(path, 'r') as f:
70
return f.read().strip()
73
def determine_title(description):
74
return description.splitlines()[0]
77
class ValidationFailed(errors.BzrError):
79
_fmt = "GitHub validation failed: %(error)s"
81
def __init__(self, error):
82
errors.BzrError.__init__(self)
86
class NotGitHubUrl(errors.BzrError):
88
_fmt = "Not a GitHub URL: %(url)s"
90
def __init__(self, url):
91
errors.BzrError.__init__(self)
95
class GitHubLoginRequired(HosterLoginRequired):
97
_fmt = "Action requires GitHub login."
100
def connect_github():
101
"""Connect to GitHub.
103
user_agent = default_user_agent()
104
auth = AuthenticationConfig()
106
credentials = auth.get_credentials('https', GITHUB_HOST)
107
if credentials is not None:
108
return Github(credentials['user'], credentials['password'],
109
user_agent=user_agent)
111
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
112
if token is not None:
113
return Github(token, user_agent=user_agent)
115
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
116
return Github(user_agent=user_agent)
119
class GitHubMergeProposal(MergeProposal):
121
def __init__(self, gh, pr):
126
return "<%s at %r>" % (type(self).__name__, self.url)
130
return self._pr['html_url']
132
def _branch_from_part(self, part):
133
if part['repo'] is None:
135
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
137
def get_source_branch_url(self):
138
return self._branch_from_part(self._pr['head'])
140
def get_target_branch_url(self):
141
return self._branch_from_part(self._pr['base'])
143
def get_description(self):
144
return self._pr['body']
146
def get_commit_message(self):
149
def set_commit_message(self, message):
150
self._patch({'title': message})
152
def _patch(self, data):
153
response = self._gh._api_request(
154
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
155
if response.status == 422:
156
raise ValidationFailed(json.loads(response.text))
157
if response.status != 200:
158
raise InvalidHttpResponse(self._pr['url'], response.text)
159
self._pr = json.loads(response.text)
161
def set_description(self, description):
164
'title': determine_title(description),
168
return bool(self._pr.get('merged_at'))
171
return self._pr['state'] == 'closed' and not bool(self._pr.get('merged_at'))
175
self._patch({'state': 'open'})
176
except ValidationFailed as e:
177
raise ReopenFailed(e.error['errors'][0]['message'])
180
self._patch({'state': 'closed'})
182
def can_be_merged(self):
183
return self._pr['mergeable']
185
def merge(self, commit_message=None):
186
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
187
self._pr.merge(commit_message=commit_message)
190
def parse_github_url(url):
191
(scheme, user, password, host, port, path) = urlutils.parse_url(
193
if host != GITHUB_HOST:
194
raise NotGitHubUrl(url)
195
(owner, repo_name) = path.strip('/').split('/')
196
if repo_name.endswith('.git'):
197
repo_name = repo_name[:-4]
198
return owner, repo_name
201
def parse_github_branch_url(branch):
202
url = urlutils.split_segment_parameters(branch.user_url)[0]
203
owner, repo_name = parse_github_url(url)
204
return owner, repo_name, branch.name
207
def github_url_to_bzr_url(url, branch_name):
209
branch_name = branch_name.encode('utf-8')
210
return urlutils.join_segment_parameters(
211
git_url_to_bzr_url(url), {"branch": branch_name})
214
class GitHub(Hoster):
218
supports_merge_proposal_labels = True
219
supports_merge_proposal_commit_message = False
224
def _api_request(self, method, path, body=None):
226
'Accept': 'application/vnd.github.v3+json'}
228
headers['Authorization'] = 'token %s' % self._token
229
response = self.transport.request(
230
method, urlutils.join(self.transport.base, path),
231
headers=headers, body=body, retries=3)
232
if response.status == 401:
233
raise GitHubLoginRequired(self)
236
def _get_repo(self, path):
237
path = 'repos/' + path
238
response = self._api_request('GET', path)
239
if response.status == 404:
240
raise NoSuchProject(path)
241
if response.status == 200:
242
return json.loads(response.text)
243
raise InvalidHttpResponse(path, response.text)
245
def _get_repo_pulls(self, path, head=None, state=None):
246
path = 'repos/' + path + '/pulls?'
249
params['head'] = head
250
if state is not None:
251
params['state'] = state
252
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
253
for k, v in params.items()])
254
response = self._api_request('GET', path)
255
if response.status == 404:
256
raise NoSuchProject(path)
257
if response.status == 200:
258
return json.loads(response.text)
259
raise InvalidHttpResponse(path, response.text)
261
def _create_pull(self, path, title, head, base, body=None):
262
path = 'repos/' + path + '/pulls'
271
response = self._api_request(
272
'POST', path, body=json.dumps(data).encode('utf-8'))
273
if response.status != 201:
274
raise InvalidHttpResponse(path, response.text)
275
return json.loads(response.text)
277
def _get_user_by_email(self, email):
278
path = 'search/users?q=%s+in:email' % email
279
response = self._api_request('GET', path)
280
if response.status != 200:
281
raise InvalidHttpResponse(path, response.text)
282
ret = json.loads(response.text)
283
if ret['total_count'] == 0:
284
raise KeyError('no user with email %s' % email)
285
elif ret['total_count'] > 1:
286
raise ValueError('more than one result for email %s' % email)
287
return ret['items'][0]
289
def _get_user(self, username=None):
291
path = 'users/:%s' % username
294
response = self._api_request('GET', path)
295
if response.status != 200:
296
raise InvalidHttpResponse(path, response.text)
297
return json.loads(response.text)
299
def _get_organization(self, name):
300
path = 'orgs/:%s' % name
301
response = self._api_request('GET', path)
302
if response.status != 200:
303
raise InvalidHttpResponse(path, response.text)
304
return json.loads(response.text)
306
def _search_issues(self, query):
307
path = 'search/issues'
308
response = self._api_request(
309
'GET', path + '?q=' + urlutils.quote(query))
310
if response.status != 200:
311
raise InvalidHttpResponse(path, response.text)
312
return json.loads(response.text)
314
def _create_fork(self, repo, owner=None):
315
(orig_owner, orig_repo) = repo.split('/')
316
path = '/repos/:%s/:%s/forks' % (orig_owner, orig_repo)
318
path += '?organization=%s' % owner
319
response = self._api_request('POST', path)
320
if response.status != 202:
321
raise InvalidHttpResponse(path, response.text)
322
return json.loads(response.text)
326
return WEB_GITHUB_URL
328
def __init__(self, transport):
329
self._token = retrieve_github_token('https', GITHUB_HOST)
330
self.transport = transport
331
self._current_user = self._get_user()
333
def publish_derived(self, local_branch, base_branch, name, project=None,
334
owner=None, revision_id=None, overwrite=False,
337
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
338
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
340
owner = self._current_user['login']
342
project = base_repo['name']
344
remote_repo = self._get_repo('%s/%s' % (owner, project))
345
except github.UnknownObjectException:
346
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
347
remote_repo = self._create_fork(base_repo, owner)
348
note(gettext('Forking new repository %s from %s') %
349
(remote_repo['html_url'], base_repo['html_url']))
351
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
352
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
354
push_result = remote_dir.push_branch(
355
local_branch, revision_id=revision_id, overwrite=overwrite,
357
except errors.NoRoundtrippingSupport:
360
push_result = remote_dir.push_branch(
361
local_branch, revision_id=revision_id,
362
overwrite=overwrite, name=name, lossy=True)
363
return push_result.target_branch, github_url_to_bzr_url(
364
remote_repo['html_url'], name)
366
def get_push_url(self, branch):
367
owner, project, branch_name = parse_github_branch_url(branch)
368
repo = self._get_repo('%s/%s' % (owner, project))
369
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
371
def get_derived_branch(self, base_branch, name, project=None, owner=None):
373
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
374
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
376
owner = self._current_user['login']
378
project = base_repo['name']
380
remote_repo = self._get_repo('%s/%s' % (owner, project))
381
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
382
return _mod_branch.Branch.open(full_url)
383
except github.UnknownObjectException:
384
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
386
def get_proposer(self, source_branch, target_branch):
387
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
389
def iter_proposals(self, source_branch, target_branch, status='open'):
390
(source_owner, source_repo_name, source_branch_name) = (
391
parse_github_branch_url(source_branch))
392
(target_owner, target_repo_name, target_branch_name) = (
393
parse_github_branch_url(target_branch))
394
target_repo_path = "%s/%s" % (target_owner, target_repo_name)
395
target_repo = self._get_repo(target_repo_path)
401
pulls = self._get_repo_pulls(
403
head=target_branch_name,
406
if (status == 'closed' and pull['merged'] or
407
status == 'merged' and not pull['merged']):
409
if pull['head']['ref'] != source_branch_name:
411
if pull['head']['repo'] is None:
412
# Repo has gone the way of the dodo
414
if (pull['head']['repo']['owner']['login'] != source_owner or
415
pull['head']['repo']['name'] != source_repo_name):
417
yield GitHubMergeProposal(self, pull)
419
def hosts(self, branch):
421
parse_github_branch_url(branch)
428
def probe_from_url(cls, url, possible_transports=None):
430
parse_github_url(url)
432
raise UnsupportedHoster(url)
433
transport = get_transport(
434
API_GITHUB_URL, possible_transports=possible_transports)
435
return cls(transport)
438
def iter_instances(cls):
439
yield cls(get_transport(API_GITHUB_URL))
441
def iter_my_proposals(self, status='open'):
444
query.append('is:open')
445
elif status == 'closed':
446
query.append('is:unmerged')
447
# Also use "is:closed" otherwise unmerged open pull requests are
449
query.append('is:closed')
450
elif status == 'merged':
451
query.append('is:merged')
452
query.append('author:%s' % self._current_user['login'])
453
for issue in self._search_issues(query=' '.join(query))['items']:
454
url = issue['pull_request']['url']
455
response = self._api_request('GET', url)
456
if response.status != 200:
457
raise InvalidHttpResponse(url, response.text)
458
yield GitHubMergeProposal(self, json.loads(response.text))
460
def get_proposal_by_url(self, url):
461
raise UnsupportedHoster(url)
464
class GitHubMergeProposalBuilder(MergeProposalBuilder):
466
def __init__(self, gh, source_branch, target_branch):
468
self.source_branch = source_branch
469
self.target_branch = target_branch
470
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
471
parse_github_branch_url(self.target_branch))
472
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
473
parse_github_branch_url(self.source_branch))
475
def get_infotext(self):
476
"""Determine the initial comment for the merge proposal."""
478
info.append("Merge %s into %s:%s\n" % (
479
self.source_branch_name, self.target_owner,
480
self.target_branch_name))
481
info.append("Source: %s\n" % self.source_branch.user_url)
482
info.append("Target: %s\n" % self.target_branch.user_url)
485
def get_initial_body(self):
486
"""Get a body for the proposal for the user to modify.
488
:return: a str or None.
492
def create_proposal(self, description, reviewers=None, labels=None,
493
prerequisite_branch=None, commit_message=None):
494
"""Perform the submission."""
495
if prerequisite_branch is not None:
496
raise PrerequisiteBranchUnsupported(self)
497
# Note that commit_message is ignored, since github doesn't support it.
499
# TODO(jelmer): Probe for right repo name
500
if self.target_repo_name.endswith('.git'):
501
self.target_repo_name = self.target_repo_name[:-4]
502
# TODO(jelmer): Allow setting title explicitly?
503
title = determine_title(description)
504
# TODO(jelmer): Set maintainers_can_modify?
506
pull_request = self.gh._create_pull(
507
"%s/%s" % (self.target_owner, self.target_repo_name),
508
title=title, body=description,
509
head="%s:%s" % (self.source_owner, self.source_branch_name),
510
base=self.target_branch_name)
511
except ValidationFailed:
512
raise MergeProposalExists(self.source_branch.user_url)
514
for reviewer in reviewers:
516
user = self.gh._get_user_by_email(reviewer)
518
user = self.gh._get_user(reviewer)
519
pull_request.assignees.append(user['login'])
522
pull_request.issue.labels.append(label)
523
return GitHubMergeProposal(self.gh, pull_request)