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
23
from .propose import (
30
PrerequisiteBranchUnsupported,
36
branch as _mod_branch,
41
version_string as breezy_version,
43
from ...config import AuthenticationConfig, GlobalStack
44
from ...errors import InvalidHttpResponse
45
from ...git.urls import git_url_to_bzr_url
46
from ...i18n import gettext
47
from ...sixish import PY3
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'
58
def store_github_token(scheme, host, token):
59
with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
63
def retrieve_github_token(scheme, host):
64
path = os.path.join(bedding.config_dir(), 'github.conf')
65
if not os.path.exists(path):
67
with open(path, 'r') as f:
68
return f.read().strip()
71
def determine_title(description):
72
return description.splitlines()[0]
75
class NotGitHubUrl(errors.BzrError):
77
_fmt = "Not a GitHub URL: %(url)s"
79
def __init__(self, url):
80
errors.BzrError.__init__(self)
84
class GitHubLoginRequired(HosterLoginRequired):
86
_fmt = "Action requires GitHub login."
92
user_agent = default_user_agent()
93
auth = AuthenticationConfig()
95
credentials = auth.get_credentials('https', GITHUB_HOST)
96
if credentials is not None:
97
return Github(credentials['user'], credentials['password'],
98
user_agent=user_agent)
100
# TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
101
if token is not None:
102
return Github(token, user_agent=user_agent)
104
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
105
return Github(user_agent=user_agent)
108
class GitHubMergeProposal(MergeProposal):
110
def __init__(self, pr):
115
return self._pr['html_url']
117
def _branch_from_part(self, part):
118
return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
120
def get_source_branch_url(self):
121
return self._branch_from_part(self._pr['head'])
123
def get_target_branch_url(self):
124
return self._branch_from_part(self._pr['base'])
126
def get_description(self):
127
return self._pr['body']
129
def get_commit_message(self):
132
def set_description(self, description):
133
self._pr.edit(body=description, title=determine_title(description))
136
return self._pr['merged']
139
self._pr.edit(state='closed')
141
def merge(self, commit_message=None):
142
# https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
143
self._pr.merge(commit_message=commit_message)
146
def parse_github_url(url):
147
(scheme, user, password, host, port, path) = urlutils.parse_url(
149
if host != GITHUB_HOST:
150
raise NotGitHubUrl(url)
151
(owner, repo_name) = path.strip('/').split('/')
152
if repo_name.endswith('.git'):
153
repo_name = repo_name[:-4]
154
return owner, repo_name
157
def parse_github_branch_url(branch):
158
url = urlutils.split_segment_parameters(branch.user_url)[0]
159
owner, repo_name = parse_github_url(url)
160
return owner, repo_name, branch.name
163
def github_url_to_bzr_url(url, branch_name):
165
branch_name = branch_name.encode('utf-8')
166
return urlutils.join_segment_parameters(
167
git_url_to_bzr_url(url), {"branch": branch_name})
170
class GitHub(Hoster):
174
supports_merge_proposal_labels = True
175
supports_merge_proposal_commit_message = False
180
def _api_request(self, method, path):
182
'Accept': 'application/vnd.github.v3+json'}
184
headers['Authorization'] = 'token %s' % self._token
185
response = self.transport.request(
186
method, urlutils.join(self.transport.base, path),
188
if response.status == 401:
189
raise GitHubLoginRequired(self)
192
def _get_repo(self, path):
193
path = 'repos/' + path
194
response = self._api_request('GET', path)
195
if response.status == 404:
196
raise NoSuchProject(path)
197
if response.status == 200:
199
raise InvalidHttpResponse(path, response.text)
201
def _get_user(self, username=None):
203
path = 'users/:%s' % username
206
response = self._api_request('GET', path)
207
if response.status != 200:
208
raise InvalidHttpResponse(path, response.text)
211
def _get_organization(self, name):
212
path = 'orgs/:%s' % name
213
response = self._api_request('GET', path)
214
if response.status != 200:
215
raise InvalidHttpResponse(path, response.text)
218
def _search_issues(self, query):
219
path = 'search/issues'
220
response = self._api_request(
221
'GET', path + '?q=' + urlutils.quote(query))
222
if response.status != 200:
223
raise InvalidHttpResponse(path, response.text)
226
def _create_fork(self, repo, owner=None):
227
(orig_owner, orig_repo) = repo.split('/')
228
path = '/repos/:%s/:%s/forks' % (orig_owner, orig_repo)
230
path += '?organization=%s' % owner
231
response = self._api_request('POST', path)
233
raise InvalidHttpResponse(path, response.text)
238
return WEB_GITHUB_URL
240
def __init__(self, transport):
241
self._token = retrieve_github_token('https', GITHUB_HOST)
242
self.transport = transport
243
self._current_user = self._get_user()
245
def publish_derived(self, local_branch, base_branch, name, project=None,
246
owner=None, revision_id=None, overwrite=False,
249
base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
250
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
252
owner = self._current_user['login']
254
project = base_repo['name']
256
remote_repo = self._get_repo('%s/%s' % (owner, project))
257
except github.UnknownObjectException:
258
base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
259
remote_repo = self._create_fork(base_repo, owner)
260
note(gettext('Forking new repository %s from %s') %
261
(remote_repo['html_url'], base_repo['html_url']))
263
note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
264
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
266
push_result = remote_dir.push_branch(
267
local_branch, revision_id=revision_id, overwrite=overwrite,
269
except errors.NoRoundtrippingSupport:
272
push_result = remote_dir.push_branch(
273
local_branch, revision_id=revision_id,
274
overwrite=overwrite, name=name, lossy=True)
275
return push_result.target_branch, github_url_to_bzr_url(
276
remote_repo['html_url'], name)
278
def get_push_url(self, branch):
279
owner, project, branch_name = parse_github_branch_url(branch)
280
repo = self._get_repo('%s/%s' % (owner, project))
281
return github_url_to_bzr_url(repo['ssh_url'], branch_name)
283
def get_derived_branch(self, base_branch, name, project=None, owner=None):
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
full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
294
return _mod_branch.Branch.open(full_url)
295
except github.UnknownObjectException:
296
raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
298
def get_proposer(self, source_branch, target_branch):
299
return GitHubMergeProposalBuilder(self, source_branch, target_branch)
301
def iter_proposals(self, source_branch, target_branch, status='open'):
302
(source_owner, source_repo_name, source_branch_name) = (
303
parse_github_branch_url(source_branch))
304
(target_owner, target_repo_name, target_branch_name) = (
305
parse_github_branch_url(target_branch))
306
target_repo = self._get_repo(
307
"%s/%s" % (target_owner, target_repo_name))
313
for pull in target_repo.get_pulls(
314
head=target_branch_name,
315
state=state[status]):
316
if (status == 'closed' and pull.merged or
317
status == 'merged' and not pull.merged):
319
if pull.head.ref != source_branch_name:
321
if pull.head.repo is None:
322
# Repo has gone the way of the dodo
324
if (pull.head.repo.owner.login != source_owner or
325
pull.head.repo.name != source_repo_name):
327
yield GitHubMergeProposal(pull)
329
def hosts(self, branch):
331
parse_github_branch_url(branch)
338
def probe_from_url(cls, url, possible_transports=None):
340
parse_github_url(url)
342
raise UnsupportedHoster(url)
343
transport = get_transport(
344
API_GITHUB_URL, possible_transports=possible_transports)
345
return cls(transport)
348
def iter_instances(cls):
349
yield cls(get_transport(API_GITHUB_URL))
351
def iter_my_proposals(self, status='open'):
354
query.append('is:open')
355
elif status == 'closed':
356
query.append('is:unmerged')
357
# Also use "is:closed" otherwise unmerged open pull requests are
359
query.append('is:closed')
360
elif status == 'merged':
361
query.append('is:merged')
362
query.append('author:%s' % self._current_user['login'])
363
for issue in self._search_issues(query=' '.join(query))['items']:
364
yield GitHubMergeProposal(
365
self.transport.request('GET', issue['pull_request']['url']).json)
367
def get_proposal_by_url(self, url):
368
raise UnsupportedHoster(url)
371
class GitHubMergeProposalBuilder(MergeProposalBuilder):
373
def __init__(self, gh, source_branch, target_branch):
375
self.source_branch = source_branch
376
self.target_branch = target_branch
377
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
378
parse_github_branch_url(self.target_branch))
379
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
380
parse_github_branch_url(self.source_branch))
382
def get_infotext(self):
383
"""Determine the initial comment for the merge proposal."""
385
info.append("Merge %s into %s:%s\n" % (
386
self.source_branch_name, self.target_owner,
387
self.target_branch_name))
388
info.append("Source: %s\n" % self.source_branch.user_url)
389
info.append("Target: %s\n" % self.target_branch.user_url)
392
def get_initial_body(self):
393
"""Get a body for the proposal for the user to modify.
395
:return: a str or None.
399
def create_proposal(self, description, reviewers=None, labels=None,
400
prerequisite_branch=None, commit_message=None):
401
"""Perform the submission."""
402
if prerequisite_branch is not None:
403
raise PrerequisiteBranchUnsupported(self)
404
# Note that commit_message is ignored, since github doesn't support it.
406
# TODO(jelmer): Probe for right repo name
407
if self.target_repo_name.endswith('.git'):
408
self.target_repo_name = self.target_repo_name[:-4]
409
target_repo = self.gh._get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
410
# TODO(jelmer): Allow setting title explicitly?
411
title = determine_title(description)
412
# TOOD(jelmer): Set maintainers_can_modify?
414
pull_request = target_repo.create_pull(
415
title=title, body=description,
416
head="%s:%s" % (self.source_owner, self.source_branch_name),
417
base=self.target_branch_name)
418
except github.GithubException as e:
420
raise MergeProposalExists(self.source_branch.user_url)
423
for reviewer in reviewers:
424
pull_request.assignees.append(
425
self.gh._get_user(reviewer)['login'])
428
pull_request.issue.labels.append(label)
429
return GitHubMergeProposal(pull_request)