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 (
29
PrerequisiteBranchUnsupported,
34
branch as _mod_branch,
39
version_string as breezy_version,
41
from ...config import AuthenticationConfig, GlobalStack, config_dir
42
from ...git.urls import git_url_to_bzr_url
43
from ...i18n import gettext
44
from ...sixish import PY3
45
from ...trace import note
46
from ...lazy_import import lazy_import
47
lazy_import(globals(), """
48
from github import Github
52
def store_github_token(scheme, host, token):
53
with open(os.path.join(config_dir(), 'github.conf'), 'w') as f:
57
def retrieve_github_token(scheme, host):
58
path = os.path.join(config_dir(), 'github.conf')
59
if not os.path.exists(path):
61
with open(path, 'r') as f:
62
return f.read().strip()
65
def determine_title(description):
66
return description.splitlines()[0]
69
class NotGitHubUrl(errors.BzrError):
71
_fmt = "Not a GitHub URL: %(url)s"
73
def __init__(self, url):
74
errors.BzrError.__init__(self)
78
class GitHubLoginRequired(HosterLoginRequired):
80
_fmt = "Action requires GitHub login."
86
user_agent = "Breezy/%s" % breezy_version
88
auth = AuthenticationConfig()
90
credentials = auth.get_credentials('https', 'github.com')
91
if credentials is not None:
92
return Github(credentials['user'], credentials['password'],
93
user_agent=user_agent)
95
# TODO(jelmer): token = auth.get_token('https', 'github.com')
96
token = retrieve_github_token('https', 'github.com')
98
return Github(token, user_agent=user_agent)
100
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
101
return Github(user_agent=user_agent)
104
class GitHubMergeProposal(MergeProposal):
106
def __init__(self, pr):
111
return self._pr.html_url
113
def _branch_from_part(self, part):
114
return github_url_to_bzr_url(part.repo.html_url, part.ref)
116
def get_source_branch_url(self):
117
return self._branch_from_part(self._pr.head)
119
def get_target_branch_url(self):
120
return self._branch_from_part(self._pr.base)
122
def get_description(self):
125
def set_description(self, description):
126
self._pr.edit(body=description, title=determine_title(description))
129
return self._pr.merged
132
self._pr.edit(state='closed')
135
def parse_github_url(branch):
136
url = urlutils.split_segment_parameters(branch.user_url)[0]
137
(scheme, user, password, host, port, path) = urlutils.parse_url(
139
if host != 'github.com':
140
raise NotGitHubUrl(url)
141
(owner, repo_name) = path.strip('/').split('/')
142
if repo_name.endswith('.git'):
143
repo_name = repo_name[:-4]
144
return owner, repo_name, branch.name
147
def github_url_to_bzr_url(url, branch_name):
149
branch_name = branch_name.encode('utf-8')
150
return urlutils.join_segment_parameters(
151
git_url_to_bzr_url(url), {"branch": branch_name})
154
def convert_github_error(fn):
155
def convert(self, *args, **kwargs):
158
return fn(self, *args, **kwargs)
159
except github.GithubException as e:
161
raise GitHubLoginRequired(self)
166
class GitHub(Hoster):
170
supports_merge_proposal_labels = True
177
# TODO(jelmer): Can we get the default URL from the Python API package
179
return "https://github.com"
182
self.gh = connect_github()
184
@convert_github_error
185
def publish_derived(self, local_branch, base_branch, name, project=None,
186
owner=None, revision_id=None, overwrite=False,
189
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
190
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
192
owner = self.gh.get_user().login
194
project = base_repo.name
196
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
198
except github.UnknownObjectException:
199
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
200
if owner == self.gh.get_user().login:
201
owner_obj = self.gh.get_user()
203
owner_obj = self.gh.get_organization(owner)
204
remote_repo = owner_obj.create_fork(base_repo)
205
note(gettext('Forking new repository %s from %s') %
206
(remote_repo.html_url, base_repo.html_url))
208
note(gettext('Reusing existing repository %s') % remote_repo.html_url)
209
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
211
push_result = remote_dir.push_branch(
212
local_branch, revision_id=revision_id, overwrite=overwrite,
214
except errors.NoRoundtrippingSupport:
217
push_result = remote_dir.push_branch(
218
local_branch, revision_id=revision_id,
219
overwrite=overwrite, name=name, lossy=True)
220
return push_result.target_branch, github_url_to_bzr_url(
221
remote_repo.html_url, name)
223
@convert_github_error
224
def get_push_url(self, branch):
225
owner, project, branch_name = parse_github_url(branch)
226
repo = self.gh.get_repo('%s/%s' % (owner, project))
227
return github_url_to_bzr_url(repo.ssh_url, branch_name)
229
@convert_github_error
230
def get_derived_branch(self, base_branch, name, project=None, owner=None):
232
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
233
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
235
owner = self.gh.get_user().login
237
project = base_repo.name
239
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
240
full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
241
return _mod_branch.Branch.open(full_url)
242
except github.UnknownObjectException:
243
raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
245
@convert_github_error
246
def get_proposer(self, source_branch, target_branch):
247
return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
249
@convert_github_error
250
def iter_proposals(self, source_branch, target_branch, status='open'):
251
(source_owner, source_repo_name, source_branch_name) = (
252
parse_github_url(source_branch))
253
(target_owner, target_repo_name, target_branch_name) = (
254
parse_github_url(target_branch))
255
target_repo = self.gh.get_repo(
256
"%s/%s" % (target_owner, target_repo_name))
262
for pull in target_repo.get_pulls(
263
head=target_branch_name,
264
state=state[status]):
265
if (status == 'closed' and pull.merged or
266
status == 'merged' and not pull.merged):
268
if pull.head.ref != source_branch_name:
270
if pull.head.repo is None:
271
# Repo has gone the way of the dodo
273
if (pull.head.repo.owner.login != source_owner or
274
pull.head.repo.name != source_repo_name):
276
yield GitHubMergeProposal(pull)
278
def hosts(self, branch):
280
parse_github_url(branch)
287
def probe(cls, branch):
289
parse_github_url(branch)
291
raise UnsupportedHoster(branch)
295
def iter_instances(cls):
298
@convert_github_error
299
def iter_my_proposals(self, status='open'):
302
query.append('is:open')
303
elif status == 'closed':
304
query.append('is:unmerged')
305
# Also use "is:closed" otherwise unmerged open pull requests are
307
query.append('is:closed')
308
elif status == 'merged':
309
query.append('is:merged')
310
query.append('author:%s' % self.gh.get_user().login)
311
for issue in self.gh.search_issues(query=' '.join(query)):
312
yield GitHubMergeProposal(issue.as_pull_request())
315
class GitHubMergeProposalBuilder(MergeProposalBuilder):
317
def __init__(self, gh, source_branch, target_branch):
319
self.source_branch = source_branch
320
self.target_branch = target_branch
321
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
322
parse_github_url(self.target_branch))
323
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
324
parse_github_url(self.source_branch))
326
def get_infotext(self):
327
"""Determine the initial comment for the merge proposal."""
329
info.append("Merge %s into %s:%s\n" % (
330
self.source_branch_name, self.target_owner,
331
self.target_branch_name))
332
info.append("Source: %s\n" % self.source_branch.user_url)
333
info.append("Target: %s\n" % self.target_branch.user_url)
336
def get_initial_body(self):
337
"""Get a body for the proposal for the user to modify.
339
:return: a str or None.
343
def create_proposal(self, description, reviewers=None, labels=None,
344
prerequisite_branch=None):
345
"""Perform the submission."""
346
if prerequisite_branch is not None:
347
raise PrerequisiteBranchUnsupported(self)
349
# TODO(jelmer): Probe for right repo name
350
if self.target_repo_name.endswith('.git'):
351
self.target_repo_name = self.target_repo_name[:-4]
352
target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
353
# TODO(jelmer): Allow setting title explicitly?
354
title = determine_title(description)
355
# TOOD(jelmer): Set maintainers_can_modify?
357
pull_request = target_repo.create_pull(
358
title=title, body=description,
359
head="%s:%s" % (self.source_owner, self.source_branch_name),
360
base=self.target_branch_name)
361
except github.GithubException as e:
363
raise MergeProposalExists(self.source_branch.user_url)
366
for reviewer in reviewers:
367
pull_request.assignees.append(
368
self.gh.get_user(reviewer))
371
pull_request.issue.labels.append(label)
372
return GitHubMergeProposal(pull_request)