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."""
22
from ...propose import (
30
PrerequisiteBranchUnsupported,
37
branch as _mod_branch,
42
version_string as breezy_version,
44
from ...config import AuthenticationConfig, GlobalStack
45
from ...errors import InvalidHttpResponse, PermissionDenied
46
from ...git.urls import git_url_to_bzr_url
47
from ...i18n import gettext
48
from ...trace import note
49
from ...transport import get_transport
50
from ...transport.http import default_user_agent
53
GITHUB_HOST = 'github.com'
54
WEB_GITHUB_URL = 'https://github.com'
55
API_GITHUB_URL = 'https://api.github.com'
59
def store_github_token(scheme, host, token):
60
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
64
def retrieve_github_token(scheme, host):
65
path = os.path.join(bedding.config_dir(), 'github.conf')
66
if not os.path.exists(path):
68
with open(path, 'r') as f:
69
return f.read().strip()
72
class ValidationFailed(errors.BzrError):
74
_fmt = "GitHub validation failed: %(error)s"
76
def __init__(self, error):
77
errors.BzrError.__init__(self)
81
class NotGitHubUrl(errors.BzrError):
83
_fmt = "Not a GitHub URL: %(url)s"
85
def __init__(self, url):
86
errors.BzrError.__init__(self)
90
class GitHubLoginRequired(HosterLoginRequired):
92
_fmt = "Action requires GitHub login."
98
user_agent = default_user_agent()
99
auth = AuthenticationConfig()
101
credentials = auth.get_credentials('https', GITHUB_HOST)
102
if credentials is not None:
103
return Github(credentials['user'], credentials['password'],
104
user_agent=user_agent)
106
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
107
if token is not None:
108
return Github(token, user_agent=user_agent)
110
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
111
return Github(user_agent=user_agent)
114
class GitHubMergeProposal(MergeProposal):
116
def __init__(self, gh, pr):
121
return "<%s at %r>" % (type(self).__name__, self.url)
125
return self._pr['html_url']
127
def _branch_from_part(self, part):
128
if part['repo'] is None:
130
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
132
def get_source_branch_url(self):
133
return self._branch_from_part(self._pr['head'])
135
def get_target_branch_url(self):
136
return self._branch_from_part(self._pr['base'])
138
def get_source_project(self):
139
return self._pr['head']['repo']['full_name']
141
def get_target_project(self):
142
return self._pr['base']['repo']['full_name']
144
def get_description(self):
145
return self._pr['body']
147
def get_commit_message(self):
150
def set_commit_message(self, message):
151
raise errors.UnsupportedOperation(self.set_commit_message, self)
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)
190
def get_merged_by(self):
191
merged_by = self._pr.get('merged_by')
192
if merged_by is None:
194
return merged_by['login']
196
def get_merged_at(self):
197
merged_at = self._pr.get('merged_at')
198
if merged_at is None:
201
return iso8601.parse_date(merged_at)
204
def parse_github_url(url):
205
(scheme, user, password, host, port, path) = urlutils.parse_url(
207
if host != GITHUB_HOST:
208
raise NotGitHubUrl(url)
209
(owner, repo_name) = path.strip('/').split('/')
210
if repo_name.endswith('.git'):
211
repo_name = repo_name[:-4]
212
return owner, repo_name
215
def parse_github_branch_url(branch):
216
url = urlutils.strip_segment_parameters(branch.user_url)
217
owner, repo_name = parse_github_url(url)
218
return owner, repo_name, branch.name
221
def github_url_to_bzr_url(url, branch_name):
222
return git_url_to_bzr_url(url, branch_name)
225
def strip_optional(url):
226
return url.split('{')[0]
229
class GitHub(Hoster):
233
supports_merge_proposal_labels = True
234
supports_merge_proposal_commit_message = False
235
supports_allow_collaboration = True
236
merge_proposal_description_format = 'markdown'
241
def _api_request(self, method, path, body=None):
243
'Content-Type': 'application/json',
244
'Accept': 'application/vnd.github.v3+json'}
246
headers['Authorization'] = 'token %s' % self._token
247
response = self.transport.request(
248
method, urlutils.join(self.transport.base, path),
249
headers=headers, body=body, retries=3)
250
if response.status == 401:
251
raise GitHubLoginRequired(self)
254
def _get_repo(self, owner, repo):
255
path = 'repos/%s/%s' % (owner, repo)
256
response = self._api_request('GET', path)
257
if response.status == 404:
258
raise NoSuchProject(path)
259
if response.status == 200:
260
return json.loads(response.text)
261
raise InvalidHttpResponse(path, response.text)
263
def _get_repo_pulls(self, path, head=None, state=None):
267
params['head'] = head
268
if state is not None:
269
params['state'] = state
270
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
271
for k, v in params.items()])
272
response = self._api_request('GET', path)
273
if response.status == 404:
274
raise NoSuchProject(path)
275
if response.status == 200:
276
return json.loads(response.text)
277
raise InvalidHttpResponse(path, response.text)
279
def _create_pull(self, path, title, head, base, body=None, labels=None,
280
assignee=None, draft=False, maintainer_can_modify=False):
286
'maintainer_can_modify': maintainer_can_modify,
288
if labels is not None:
289
data['labels'] = labels
290
if assignee is not None:
291
data['assignee'] = assignee
295
response = self._api_request(
296
'POST', path, body=json.dumps(data).encode('utf-8'))
297
if response.status == 403:
298
raise PermissionDenied(path, response.text)
299
if response.status != 201:
300
raise InvalidHttpResponse(path, 'req is invalid %d %r: %r' % (response.status, data, response.text))
301
return json.loads(response.text)
303
def _get_user_by_email(self, email):
304
path = 'search/users?q=%s+in:email' % email
305
response = self._api_request('GET', path)
306
if response.status != 200:
307
raise InvalidHttpResponse(path, response.text)
308
ret = json.loads(response.text)
309
if ret['total_count'] == 0:
310
raise KeyError('no user with email %s' % email)
311
elif ret['total_count'] > 1:
312
raise ValueError('more than one result for email %s' % email)
313
return ret['items'][0]
315
def _get_user(self, username=None):
317
path = 'users/%s' % username
320
response = self._api_request('GET', path)
321
if response.status != 200:
322
raise InvalidHttpResponse(path, response.text)
323
return json.loads(response.text)
325
def _get_organization(self, name):
326
path = 'orgs/%s' % name
327
response = self._api_request('GET', path)
328
if response.status != 200:
329
raise InvalidHttpResponse(path, response.text)
330
return json.loads(response.text)
332
def _list_paged(self, path, parameters=None, per_page=None):
333
if parameters is None:
336
parameters = dict(parameters.items())
338
parameters['per_page'] = str(per_page)
342
parameters['page'] = str(page)
343
response = self._api_request(
345
';'.join(['%s=%s' % (k, urlutils.quote(v))
346
for (k, v) in parameters.items()]))
347
if response.status != 200:
348
raise InvalidHttpResponse(path, response.text)
349
data = json.loads(response.text)
350
for entry in data['items']:
353
if i >= data['total_count']:
357
def _search_issues(self, query):
358
path = 'search/issues'
359
return self._list_paged(path, {'q': query}, per_page=DEFAULT_PER_PAGE)
361
def _create_fork(self, path, owner=None):
362
if owner and owner != self._current_user['login']:
363
path += '?organization=%s' % owner
364
response = self._api_request('POST', path)
365
if response.status != 202:
366
raise InvalidHttpResponse(path, 'status: %d, %r' % (response.status, response.text))
367
return json.loads(response.text)
371
return WEB_GITHUB_URL
373
def __init__(self, transport):
374
self._token = retrieve_github_token('https', GITHUB_HOST)
375
self.transport = transport
376
self._current_user = self._get_user()
378
def publish_derived(self, local_branch, base_branch, name, project=None,
379
owner=None, revision_id=None, overwrite=False,
380
allow_lossy=True, tag_selector=None):
381
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
382
base_repo = self._get_repo(base_owner, base_project)
384
owner = self._current_user['login']
386
project = base_repo['name']
388
remote_repo = self._get_repo(owner, project)
389
except NoSuchProject:
390
base_repo = self._get_repo(base_owner, base_project)
391
remote_repo = self._create_fork(base_repo['forks_url'], owner)
392
note(gettext('Forking new repository %s from %s') %
393
(remote_repo['html_url'], base_repo['html_url']))
395
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
396
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
398
push_result = remote_dir.push_branch(
399
local_branch, revision_id=revision_id, overwrite=overwrite,
400
name=name, tag_selector=tag_selector)
401
except errors.NoRoundtrippingSupport:
404
push_result = remote_dir.push_branch(
405
local_branch, revision_id=revision_id,
406
overwrite=overwrite, name=name, lossy=True,
407
tag_selector=tag_selector)
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
work_in_progress=False, allow_collaboration=False):
558
"""Perform the submission."""
559
if prerequisite_branch is not None:
560
raise PrerequisiteBranchUnsupported(self)
561
# Note that commit_message is ignored, since github doesn't support it.
562
# TODO(jelmer): Probe for right repo name
563
if self.target_repo_name.endswith('.git'):
564
self.target_repo_name = self.target_repo_name[:-4]
565
# TODO(jelmer): Allow setting title explicitly?
566
title = determine_title(description)
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
draft=work_in_progress,
588
maintainer_can_modify=allow_collaboration,
590
except ValidationFailed:
591
raise MergeProposalExists(self.source_branch.user_url)
592
return GitHubMergeProposal(self.gh, pull_request)