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 (
28
PrerequisiteBranchUnsupported,
33
branch as _mod_branch,
38
version_string as breezy_version,
40
from ...config import AuthenticationConfig, GlobalStack, config_dir
41
from ...git.urls import git_url_to_bzr_url
42
from ...i18n import gettext
43
from ...sixish import PY3
44
from ...trace import note
45
from ...lazy_import import lazy_import
46
lazy_import(globals(), """
47
from github import Github
51
def store_github_token(scheme, host, token):
52
with open(os.path.join(config_dir(), 'github.conf'), 'w') as f:
56
def retrieve_github_token(scheme, host):
57
path = os.path.join(config_dir(), 'github.conf')
58
if not os.path.exists(path):
60
with open(path, 'r') as f:
61
return f.read().strip()
64
def determine_title(description):
65
return description.splitlines()[0]
68
class NotGitHubUrl(errors.BzrError):
70
_fmt = "Not a GitHub URL: %(url)s"
72
def __init__(self, url):
73
errors.BzrError.__init__(self)
80
user_agent = "Breezy/%s" % breezy_version
82
auth = AuthenticationConfig()
84
credentials = auth.get_credentials('https', 'github.com')
85
if credentials is not None:
86
return Github(credentials['user'], credentials['password'],
87
user_agent=user_agent)
89
# TODO(jelmer): token = auth.get_token('https', 'github.com')
90
token = retrieve_github_token('https', 'github.com')
92
return Github(token, user_agent=user_agent)
94
note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
95
return Github(user_agent=user_agent)
98
class GitHubMergeProposal(MergeProposal):
100
def __init__(self, pr):
105
return self._pr.html_url
107
def _branch_from_part(self, part):
108
return github_url_to_bzr_url(part.repo.html_url, part.ref)
110
def get_source_branch_url(self):
111
return self._branch_from_part(self._pr.head)
113
def get_target_branch_url(self):
114
return self._branch_from_part(self._pr.base)
116
def get_description(self):
119
def set_description(self, description):
120
self._pr.edit(body=description, title=determine_title(description))
123
return self._pr.merged
126
self._pr.edit(state='closed')
129
def parse_github_url(branch):
130
url = urlutils.split_segment_parameters(branch.user_url)[0]
131
(scheme, user, password, host, port, path) = urlutils.parse_url(
133
if host != 'github.com':
134
raise NotGitHubUrl(url)
135
(owner, repo_name) = path.strip('/').split('/')
136
if repo_name.endswith('.git'):
137
repo_name = repo_name[:-4]
138
return owner, repo_name, branch.name
141
def github_url_to_bzr_url(url, branch_name):
143
branch_name = branch_name.encode('utf-8')
144
return urlutils.join_segment_parameters(
145
git_url_to_bzr_url(url), {"branch": branch_name})
148
class GitHub(Hoster):
152
supports_merge_proposal_labels = True
159
# TODO(jelmer): Can we get the default URL from the Python API package
161
return "https://github.com"
164
self.gh = connect_github()
166
def publish_derived(self, local_branch, base_branch, name, project=None,
167
owner=None, revision_id=None, overwrite=False,
170
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
171
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
173
owner = self.gh.get_user().login
175
project = base_repo.name
177
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
179
except github.UnknownObjectException:
180
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
181
if owner == self.gh.get_user().login:
182
owner_obj = self.gh.get_user()
184
owner_obj = self.gh.get_organization(owner)
185
remote_repo = owner_obj.create_fork(base_repo)
186
note(gettext('Forking new repository %s from %s') %
187
(remote_repo.html_url, base_repo.html_url))
189
note(gettext('Reusing existing repository %s') % remote_repo.html_url)
190
remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
192
push_result = remote_dir.push_branch(
193
local_branch, revision_id=revision_id, overwrite=overwrite,
195
except errors.NoRoundtrippingSupport:
198
push_result = remote_dir.push_branch(
199
local_branch, revision_id=revision_id,
200
overwrite=overwrite, name=name, lossy=True)
201
return push_result.target_branch, github_url_to_bzr_url(
202
remote_repo.html_url, name)
204
def get_push_url(self, branch):
205
owner, project, branch_name = parse_github_url(branch)
206
repo = self.gh.get_repo('%s/%s' % (owner, project))
207
return github_url_to_bzr_url(repo.ssh_url, branch_name)
209
def get_derived_branch(self, base_branch, name, project=None, owner=None):
211
base_owner, base_project, base_branch_name = parse_github_url(base_branch)
212
base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
214
owner = self.gh.get_user().login
216
project = base_repo.name
218
remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
219
full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
220
return _mod_branch.Branch.open(full_url)
221
except github.UnknownObjectException:
222
raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
224
def get_proposer(self, source_branch, target_branch):
225
return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
227
def iter_proposals(self, source_branch, target_branch, status='open'):
228
(source_owner, source_repo_name, source_branch_name) = (
229
parse_github_url(source_branch))
230
(target_owner, target_repo_name, target_branch_name) = (
231
parse_github_url(target_branch))
232
target_repo = self.gh.get_repo(
233
"%s/%s" % (target_owner, target_repo_name))
239
for pull in target_repo.get_pulls(
240
head=target_branch_name,
241
state=state[status]):
242
if (status == 'closed' and pull.merged or
243
status == 'merged' and not pull.merged):
245
if pull.head.ref != source_branch_name:
247
if (pull.head.repo.owner.login != source_owner or
248
pull.head.repo.name != source_repo_name):
250
yield GitHubMergeProposal(pull)
252
def hosts(self, branch):
254
parse_github_url(branch)
261
def probe(cls, branch):
263
parse_github_url(branch)
265
raise UnsupportedHoster(branch)
269
def iter_instances(cls):
272
def iter_my_proposals(self, status='open'):
275
query.append('is:open')
276
elif status == 'closed':
277
# Note that we don't use is:closed here, since that also includes
278
# merged pull requests.
279
query.append('is:unmerged')
280
elif status == 'merged':
281
query.append('is:merged')
282
query.append('author:%s' % self.gh.get_user().login)
283
for issue in self.gh.search_issues(query=' '.join(query)):
284
yield GitHubMergeProposal(issue.as_pull_request())
287
class GitHubMergeProposalBuilder(MergeProposalBuilder):
289
def __init__(self, gh, source_branch, target_branch):
291
self.source_branch = source_branch
292
self.target_branch = target_branch
293
(self.target_owner, self.target_repo_name, self.target_branch_name) = (
294
parse_github_url(self.target_branch))
295
(self.source_owner, self.source_repo_name, self.source_branch_name) = (
296
parse_github_url(self.source_branch))
298
def get_infotext(self):
299
"""Determine the initial comment for the merge proposal."""
301
info.append("Merge %s into %s:%s\n" % (
302
self.source_branch_name, self.target_owner,
303
self.target_branch_name))
304
info.append("Source: %s\n" % self.source_branch.user_url)
305
info.append("Target: %s\n" % self.target_branch.user_url)
308
def get_initial_body(self):
309
"""Get a body for the proposal for the user to modify.
311
:return: a str or None.
315
def create_proposal(self, description, reviewers=None, labels=None,
316
prerequisite_branch=None):
317
"""Perform the submission."""
318
if prerequisite_branch is not None:
319
raise PrerequisiteBranchUnsupported(self)
321
# TODO(jelmer): Probe for right repo name
322
if self.target_repo_name.endswith('.git'):
323
self.target_repo_name = self.target_repo_name[:-4]
324
target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
325
# TODO(jelmer): Allow setting title explicitly?
326
title = determine_title(description)
327
# TOOD(jelmer): Set maintainers_can_modify?
329
pull_request = target_repo.create_pull(
330
title=title, body=description,
331
head="%s:%s" % (self.source_owner, self.source_branch_name),
332
base=self.target_branch_name)
333
except github.GithubException as e:
335
raise MergeProposalExists(self.source_branch.user_url)
338
for reviewer in reviewers:
339
pull_request.assignees.append(
340
self.gh.get_user(reviewer))
343
pull_request.issue.labels.append(label)
344
return GitHubMergeProposal(pull_request)