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,
37
branch as _mod_branch,
42
version_string as breezy_version,
44
from ...config import AuthenticationConfig, GlobalStack
45
from ...errors import InvalidHttpResponse
46
from ...git.urls import git_url_to_bzr_url
47
from ...i18n import gettext
48
from ...sixish import PY3
49
from ...trace import note
50
from ...transport import get_transport
51
from ...transport.http import default_user_agent
54
GITHUB_HOST = 'github.com'
55
WEB_GITHUB_URL = 'https://github.com'
56
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
def determine_title(description):
73
return description.splitlines()[0]
76
class NotGitHubUrl(errors.BzrError):
78
_fmt = "Not a GitHub URL: %(url)s"
80
def __init__(self, url):
81
errors.BzrError.__init__(self)
85
class GitHubLoginRequired(HosterLoginRequired):
87
_fmt = "Action requires GitHub login."
93
user_agent = default_user_agent()
94
auth = AuthenticationConfig()
96
credentials = auth.get_credentials('https', GITHUB_HOST)
97
if credentials is not None:
98
return Github(credentials['user'], credentials['password'],
99
user_agent=user_agent)
101
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
102
if token is not None:
103
return Github(token, user_agent=user_agent)
105
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
106
return Github(user_agent=user_agent)
109
class GitHubMergeProposal(MergeProposal):
111
def __init__(self, gh, pr):
117
return self._pr['html_url']
119
def _branch_from_part(self, part):
120
if part['repo'] is None:
122
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
124
def get_source_branch_url(self):
125
return self._branch_from_part(self._pr['head'])
127
def get_target_branch_url(self):
128
return self._branch_from_part(self._pr['base'])
130
def get_description(self):
131
return self._pr['body']
133
def get_commit_message(self):
136
def set_commit_message(self, message):
137
self._patch({'title': message})
139
def _patch(self, data):
140
response = self._gh._api_request(
141
'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
142
if response.status != 200:
143
raise InvalidHttpResponse(self._pr['url'], response.text)
144
self._pr = json.loads(response.text)
146
def set_description(self, description):
149
'title': determine_title(description),
153
return self._pr['state'] == 'merged'
156
self._patch({'state': 'closed'})
158
def can_be_merged(self):
159
return self._pr['mergeable']
161
def merge(self, commit_message=None):
162
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
163
self._pr.merge(commit_message=commit_message)
166
def parse_github_url(url):
167
(scheme, user, password, host, port, path) = urlutils.parse_url(
169
if host != GITHUB_HOST:
170
raise NotGitHubUrl(url)
171
(owner, repo_name) = path.strip('/').split('/')
172
if repo_name.endswith('.git'):
173
repo_name = repo_name[:-4]
174
return owner, repo_name
177
def parse_github_branch_url(branch):
178
url = urlutils.split_segment_parameters(branch.user_url)[0]
179
owner, repo_name = parse_github_url(url)
180
return owner, repo_name, branch.name
183
def github_url_to_bzr_url(url, branch_name):
185
branch_name = branch_name.encode('utf-8')
186
return urlutils.join_segment_parameters(
187
git_url_to_bzr_url(url), {"branch": branch_name})
190
class GitHub(Hoster):
194
supports_merge_proposal_labels = True
195
supports_merge_proposal_commit_message = False
200
def _api_request(self, method, path, body=None):
202
'Accept': 'application/vnd.github.v3+json'}
204
headers['Authorization'] = 'token %s' % self._token
205
response = self.transport.request(
206
method, urlutils.join(self.transport.base, path),
207
headers=headers, body=body, retries=3)
208
if response.status == 401:
209
raise GitHubLoginRequired(self)
212
def _get_repo(self, path):
213
path = 'repos/' + path
214
response = self._api_request('GET', path)
215
if response.status == 404:
216
raise NoSuchProject(path)
217
if response.status == 200:
218
return json.loads(response.text)
219
raise InvalidHttpResponse(path, response.text)
221
def _get_repo_pulls(self, path, head=None, state=None):
222
path = 'repos/' + path + '/pulls?'
225
params['head'] = head
226
if state is not None:
227
params['state'] = state
228
path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
229
for k, v in params.items()])
230
response = self._api_request('GET', path)
231
if response.status == 404:
232
raise NoSuchProject(path)
233
if response.status == 200:
234
return json.loads(response.text)
235
raise InvalidHttpResponse(path, response.text)
237
def _get_user(self, username=None):
239
path = 'users/:%s' % username
242
response = self._api_request('GET', path)
243
if response.status != 200:
244
raise InvalidHttpResponse(path, response.text)
245
return json.loads(response.text)
247
def _get_organization(self, name):
248
path = 'orgs/:%s' % name
249
response = self._api_request('GET', path)
250
if response.status != 200:
251
raise InvalidHttpResponse(path, response.text)
252
return json.loads(response.text)
254
def _search_issues(self, query):
255
path = 'search/issues'
256
response = self._api_request(
257
'GET', path + '?q=' + urlutils.quote(query))
258
if response.status != 200:
259
raise InvalidHttpResponse(path, response.text)
260
return json.loads(response.text)
262
def _create_fork(self, repo, owner=None):
263
(orig_owner, orig_repo) = repo.split('/')
264
path = '/repos/:%s/:%s/forks' % (orig_owner, orig_repo)
266
path += '?organization=%s' % owner
267
response = self._api_request('POST', path)
269
raise InvalidHttpResponse(path, response.text)
270
return json.loads(response.text)
274
return WEB_GITHUB_URL
276
def __init__(self, transport):
277
self._token = retrieve_github_token('https', GITHUB_HOST)
278
self.transport = transport
279
self._current_user = self._get_user()
281
def publish_derived(self, local_branch, base_branch, name, project=None,
282
owner=None, revision_id=None, overwrite=False,
285
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
286
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
288
owner = self._current_user['login']
290
project = base_repo['name']
292
remote_repo = self._get_repo('%s/%s' % (owner, project))
293
except github.UnknownObjectException:
294
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
295
remote_repo = self._create_fork(base_repo, owner)
296
note(gettext('Forking new repository %s from %s') %
297
(remote_repo['html_url'], base_repo['html_url']))
299
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
300
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
302
push_result = remote_dir.push_branch(
303
local_branch, revision_id=revision_id, overwrite=overwrite,
305
except errors.NoRoundtrippingSupport:
308
push_result = remote_dir.push_branch(
309
local_branch, revision_id=revision_id,
310
overwrite=overwrite, name=name, lossy=True)
311
return push_result.target_branch, github_url_to_bzr_url(
312
remote_repo['html_url'], name)
314
def get_push_url(self, branch):
315
owner, project, branch_name = parse_github_branch_url(branch)
316
repo = self._get_repo('%s/%s' % (owner, project))
317
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
319
def get_derived_branch(self, base_branch, name, project=None, owner=None):
321
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
322
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
324
owner = self._current_user['login']
326
project = base_repo['name']
328
remote_repo = self._get_repo('%s/%s' % (owner, project))
329
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
330
return _mod_branch.Branch.open(full_url)
331
except github.UnknownObjectException:
332
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
334
def get_proposer(self, source_branch, target_branch):
335
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
337
def iter_proposals(self, source_branch, target_branch, status='open'):
338
(source_owner, source_repo_name, source_branch_name) = (
339
parse_github_branch_url(source_branch))
340
(target_owner, target_repo_name, target_branch_name) = (
341
parse_github_branch_url(target_branch))
342
target_repo_path = "%s/%s" % (target_owner, target_repo_name)
343
target_repo = self._get_repo(target_repo_path)
349
pulls = self._get_repo_pulls(
351
head=target_branch_name,
354
if (status == 'closed' and pull['merged'] or
355
status == 'merged' and not pull['merged']):
357
if pull['head']['ref'] != source_branch_name:
359
if pull['head']['repo'] is None:
360
# Repo has gone the way of the dodo
362
if (pull['head']['repo']['owner']['login'] != source_owner or
363
pull['head']['repo']['name'] != source_repo_name):
365
yield GitHubMergeProposal(self, pull)
367
def hosts(self, branch):
369
parse_github_branch_url(branch)
376
def probe_from_url(cls, url, possible_transports=None):
378
parse_github_url(url)
380
raise UnsupportedHoster(url)
381
transport = get_transport(
382
API_GITHUB_URL, possible_transports=possible_transports)
383
return cls(transport)
386
def iter_instances(cls):
387
yield cls(get_transport(API_GITHUB_URL))
389
def iter_my_proposals(self, status='open'):
392
query.append('is:open')
393
elif status == 'closed':
394
query.append('is:unmerged')
395
# Also use "is:closed" otherwise unmerged open pull requests are
397
query.append('is:closed')
398
elif status == 'merged':
399
query.append('is:merged')
400
query.append('author:%s' % self._current_user['login'])
401
for issue in self._search_issues(query=' '.join(query))['items']:
402
url = issue['pull_request']['url']
403
response = self._api_request('GET', url)
404
if response.status != 200:
405
raise InvalidHttpResponse(url, response.text)
406
yield GitHubMergeProposal(self, json.loads(response.text))
408
def get_proposal_by_url(self, url):
409
raise UnsupportedHoster(url)
412
class GitHubMergeProposalBuilder(MergeProposalBuilder):
414
def __init__(self, gh, source_branch, target_branch):
416
self.source_branch = source_branch
417
self.target_branch = target_branch
418
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
419
parse_github_branch_url(self.target_branch))
420
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
421
parse_github_branch_url(self.source_branch))
423
def get_infotext(self):
424
"""Determine the initial comment for the merge proposal."""
426
info.append("Merge %s into %s:%s\n" % (
427
self.source_branch_name, self.target_owner,
428
self.target_branch_name))
429
info.append("Source: %s\n" % self.source_branch.user_url)
430
info.append("Target: %s\n" % self.target_branch.user_url)
433
def get_initial_body(self):
434
"""Get a body for the proposal for the user to modify.
436
:return: a str or None.
440
def create_proposal(self, description, reviewers=None, labels=None,
441
prerequisite_branch=None, commit_message=None):
442
"""Perform the submission."""
443
if prerequisite_branch is not None:
444
raise PrerequisiteBranchUnsupported(self)
445
# Note that commit_message is ignored, since github doesn't support it.
447
# TODO(jelmer): Probe for right repo name
448
if self.target_repo_name.endswith('.git'):
449
self.target_repo_name = self.target_repo_name[:-4]
450
target_repo = self.gh._get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
451
# TODO(jelmer): Allow setting title explicitly?
452
title = determine_title(description)
453
# TOOD(jelmer): Set maintainers_can_modify?
455
pull_request = target_repo.create_pull(
456
title=title, body=description,
457
head="%s:%s" % (self.source_owner, self.source_branch_name),
458
base=self.target_branch_name)
459
except github.GithubException as e:
461
raise MergeProposalExists(self.source_branch.user_url)
464
for reviewer in reviewers:
465
pull_request.assignees.append(
466
self.gh._get_user(reviewer)['login'])
469
pull_request.issue.labels.append(label)
470
return GitHubMergeProposal(self.gh, pull_request)