/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/plugins/propose/github.py

  • Committer: Jelmer Vernooij
  • Date: 2019-06-15 13:39:46 UTC
  • mto: This revision was merged to the branch mainline in revision 7342.
  • Revision ID: jelmer@jelmer.uk-20190615133946-uywh9ix0lfpqw0hy
Install quilt.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2018 Breezy Developers
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Support for GitHub."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
import os
 
22
 
 
23
from .propose import (
 
24
    Hoster,
 
25
    HosterLoginRequired,
 
26
    MergeProposal,
 
27
    MergeProposalBuilder,
 
28
    MergeProposalExists,
 
29
    PrerequisiteBranchUnsupported,
 
30
    UnsupportedHoster,
 
31
    )
 
32
 
 
33
from ... import (
 
34
    branch as _mod_branch,
 
35
    controldir,
 
36
    errors,
 
37
    hooks,
 
38
    urlutils,
 
39
    version_string as breezy_version,
 
40
    )
 
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
 
49
""")
 
50
 
 
51
 
 
52
def store_github_token(scheme, host, token):
 
53
    with open(os.path.join(config_dir(), 'github.conf'), 'w') as f:
 
54
        f.write(token)
 
55
 
 
56
 
 
57
def retrieve_github_token(scheme, host):
 
58
    path = os.path.join(config_dir(), 'github.conf')
 
59
    if not os.path.exists(path):
 
60
        return None
 
61
    with open(path, 'r') as f:
 
62
        return f.read().strip()
 
63
 
 
64
 
 
65
def determine_title(description):
 
66
    return description.splitlines()[0]
 
67
 
 
68
 
 
69
class NotGitHubUrl(errors.BzrError):
 
70
 
 
71
    _fmt = "Not a GitHub URL: %(url)s"
 
72
 
 
73
    def __init__(self, url):
 
74
        errors.BzrError.__init__(self)
 
75
        self.url = url
 
76
 
 
77
 
 
78
class GitHubLoginRequired(HosterLoginRequired):
 
79
 
 
80
    _fmt = "Action requires GitHub login."
 
81
 
 
82
 
 
83
def connect_github():
 
84
    """Connect to GitHub.
 
85
    """
 
86
    user_agent = "Breezy/%s" % breezy_version
 
87
 
 
88
    auth = AuthenticationConfig()
 
89
 
 
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)
 
94
 
 
95
    # TODO(jelmer): token = auth.get_token('https', 'github.com')
 
96
    token = retrieve_github_token('https', 'github.com')
 
97
    if token is not None:
 
98
        return Github(token, user_agent=user_agent)
 
99
    else:
 
100
        note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
 
101
        return Github(user_agent=user_agent)
 
102
 
 
103
 
 
104
class GitHubMergeProposal(MergeProposal):
 
105
 
 
106
    def __init__(self, pr):
 
107
        self._pr = pr
 
108
 
 
109
    @property
 
110
    def url(self):
 
111
        return self._pr.html_url
 
112
 
 
113
    def _branch_from_part(self, part):
 
114
        return github_url_to_bzr_url(part.repo.html_url, part.ref)
 
115
 
 
116
    def get_source_branch_url(self):
 
117
        return self._branch_from_part(self._pr.head)
 
118
 
 
119
    def get_target_branch_url(self):
 
120
        return self._branch_from_part(self._pr.base)
 
121
 
 
122
    def get_description(self):
 
123
        return self._pr.body
 
124
 
 
125
    def get_commit_message(self):
 
126
        return None
 
127
 
 
128
    def set_description(self, description):
 
129
        self._pr.edit(body=description, title=determine_title(description))
 
130
 
 
131
    def is_merged(self):
 
132
        return self._pr.merged
 
133
 
 
134
    def close(self):
 
135
        self._pr.edit(state='closed')
 
136
 
 
137
    def merge(self, commit_message=None):
 
138
        # https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
 
139
        self._pr.merge(commit_message=commit_message)
 
140
 
 
141
 
 
142
def parse_github_url(url):
 
143
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
144
        url)
 
145
    if host != 'github.com':
 
146
        raise NotGitHubUrl(url)
 
147
    (owner, repo_name) = path.strip('/').split('/')
 
148
    if repo_name.endswith('.git'):
 
149
        repo_name = repo_name[:-4]
 
150
    return owner, repo_name
 
151
 
 
152
 
 
153
def parse_github_branch_url(branch):
 
154
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
155
    owner, repo_name = parse_github_url(url)
 
156
    return owner, repo_name, branch.name
 
157
 
 
158
 
 
159
def github_url_to_bzr_url(url, branch_name):
 
160
    if not PY3:
 
161
        branch_name = branch_name.encode('utf-8')
 
162
    return urlutils.join_segment_parameters(
 
163
        git_url_to_bzr_url(url), {"branch": branch_name})
 
164
 
 
165
 
 
166
def convert_github_error(fn):
 
167
    def convert(self, *args, **kwargs):
 
168
        import github
 
169
        try:
 
170
            return fn(self, *args, **kwargs)
 
171
        except github.GithubException as e:
 
172
            if e.args[0] == 401:
 
173
                raise GitHubLoginRequired(self)
 
174
            raise
 
175
    return convert
 
176
 
 
177
 
 
178
class GitHub(Hoster):
 
179
 
 
180
    name = 'github'
 
181
 
 
182
    supports_merge_proposal_labels = True
 
183
    supports_merge_proposal_commit_message = False
 
184
 
 
185
    def __repr__(self):
 
186
        return "GitHub()"
 
187
 
 
188
    @property
 
189
    def base_url(self):
 
190
        # TODO(jelmer): Can we get the default URL from the Python API package
 
191
        # somehow?
 
192
        return "https://github.com"
 
193
 
 
194
    def __init__(self):
 
195
        self.gh = connect_github()
 
196
 
 
197
    @convert_github_error
 
198
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
199
                        owner=None, revision_id=None, overwrite=False,
 
200
                        allow_lossy=True):
 
201
        import github
 
202
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
203
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
204
        if owner is None:
 
205
            owner = self.gh.get_user().login
 
206
        if project is None:
 
207
            project = base_repo.name
 
208
        try:
 
209
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
210
            remote_repo.id
 
211
        except github.UnknownObjectException:
 
212
            base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
213
            if owner == self.gh.get_user().login:
 
214
                owner_obj = self.gh.get_user()
 
215
            else:
 
216
                owner_obj = self.gh.get_organization(owner)
 
217
            remote_repo = owner_obj.create_fork(base_repo)
 
218
            note(gettext('Forking new repository %s from %s') %
 
219
                 (remote_repo.html_url, base_repo.html_url))
 
220
        else:
 
221
            note(gettext('Reusing existing repository %s') % remote_repo.html_url)
 
222
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
 
223
        try:
 
224
            push_result = remote_dir.push_branch(
 
225
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
226
                name=name)
 
227
        except errors.NoRoundtrippingSupport:
 
228
            if not allow_lossy:
 
229
                raise
 
230
            push_result = remote_dir.push_branch(
 
231
                local_branch, revision_id=revision_id,
 
232
                overwrite=overwrite, name=name, lossy=True)
 
233
        return push_result.target_branch, github_url_to_bzr_url(
 
234
            remote_repo.html_url, name)
 
235
 
 
236
    @convert_github_error
 
237
    def get_push_url(self, branch):
 
238
        owner, project, branch_name = parse_github_branch_url(branch)
 
239
        repo = self.gh.get_repo('%s/%s' % (owner, project))
 
240
        return github_url_to_bzr_url(repo.ssh_url, branch_name)
 
241
 
 
242
    @convert_github_error
 
243
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
244
        import github
 
245
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
246
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
247
        if owner is None:
 
248
            owner = self.gh.get_user().login
 
249
        if project is None:
 
250
            project = base_repo.name
 
251
        try:
 
252
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
253
            full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
 
254
            return _mod_branch.Branch.open(full_url)
 
255
        except github.UnknownObjectException:
 
256
            raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
 
257
 
 
258
    @convert_github_error
 
259
    def get_proposer(self, source_branch, target_branch):
 
260
        return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
 
261
 
 
262
    @convert_github_error
 
263
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
264
        (source_owner, source_repo_name, source_branch_name) = (
 
265
            parse_github_branch_url(source_branch))
 
266
        (target_owner, target_repo_name, target_branch_name) = (
 
267
            parse_github_branch_url(target_branch))
 
268
        target_repo = self.gh.get_repo(
 
269
            "%s/%s" % (target_owner, target_repo_name))
 
270
        state = {
 
271
            'open': 'open',
 
272
            'merged': 'closed',
 
273
            'closed': 'closed',
 
274
            'all': 'all'}
 
275
        for pull in target_repo.get_pulls(
 
276
                head=target_branch_name,
 
277
                state=state[status]):
 
278
            if (status == 'closed' and pull.merged or
 
279
                    status == 'merged' and not pull.merged):
 
280
                continue
 
281
            if pull.head.ref != source_branch_name:
 
282
                continue
 
283
            if pull.head.repo is None:
 
284
                # Repo has gone the way of the dodo
 
285
                continue
 
286
            if (pull.head.repo.owner.login != source_owner or
 
287
                    pull.head.repo.name != source_repo_name):
 
288
                continue
 
289
            yield GitHubMergeProposal(pull)
 
290
 
 
291
    def hosts(self, branch):
 
292
        try:
 
293
            parse_github_branch_url(branch)
 
294
        except NotGitHubUrl:
 
295
            return False
 
296
        else:
 
297
            return True
 
298
 
 
299
    @classmethod
 
300
    def probe_from_url(cls, url):
 
301
        try:
 
302
            parse_github_url(url)
 
303
        except NotGitHubUrl:
 
304
            raise UnsupportedHoster(url)
 
305
        return cls()
 
306
 
 
307
    @classmethod
 
308
    def iter_instances(cls):
 
309
        yield cls()
 
310
 
 
311
    @convert_github_error
 
312
    def iter_my_proposals(self, status='open'):
 
313
        query = ['is:pr']
 
314
        if status == 'open':
 
315
            query.append('is:open')
 
316
        elif status == 'closed':
 
317
            query.append('is:unmerged')
 
318
            # Also use "is:closed" otherwise unmerged open pull requests are
 
319
            # also included.
 
320
            query.append('is:closed')
 
321
        elif status == 'merged':
 
322
            query.append('is:merged')
 
323
        query.append('author:%s' % self.gh.get_user().login)
 
324
        for issue in self.gh.search_issues(query=' '.join(query)):
 
325
            yield GitHubMergeProposal(issue.as_pull_request())
 
326
 
 
327
    @convert_github_error
 
328
    def get_proposal_by_url(self, url):
 
329
        raise UnsupportedHoster(url)
 
330
 
 
331
 
 
332
class GitHubMergeProposalBuilder(MergeProposalBuilder):
 
333
 
 
334
    def __init__(self, gh, source_branch, target_branch):
 
335
        self.gh = gh
 
336
        self.source_branch = source_branch
 
337
        self.target_branch = target_branch
 
338
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
 
339
            parse_github_branch_url(self.target_branch))
 
340
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
 
341
            parse_github_branch_url(self.source_branch))
 
342
 
 
343
    def get_infotext(self):
 
344
        """Determine the initial comment for the merge proposal."""
 
345
        info = []
 
346
        info.append("Merge %s into %s:%s\n" % (
 
347
            self.source_branch_name, self.target_owner,
 
348
            self.target_branch_name))
 
349
        info.append("Source: %s\n" % self.source_branch.user_url)
 
350
        info.append("Target: %s\n" % self.target_branch.user_url)
 
351
        return ''.join(info)
 
352
 
 
353
    def get_initial_body(self):
 
354
        """Get a body for the proposal for the user to modify.
 
355
 
 
356
        :return: a str or None.
 
357
        """
 
358
        return None
 
359
 
 
360
    def create_proposal(self, description, reviewers=None, labels=None,
 
361
                        prerequisite_branch=None, commit_message=None):
 
362
        """Perform the submission."""
 
363
        if prerequisite_branch is not None:
 
364
            raise PrerequisiteBranchUnsupported(self)
 
365
        # Note that commit_message is ignored, since github doesn't support it.
 
366
        import github
 
367
        # TODO(jelmer): Probe for right repo name
 
368
        if self.target_repo_name.endswith('.git'):
 
369
            self.target_repo_name = self.target_repo_name[:-4]
 
370
        target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
 
371
        # TODO(jelmer): Allow setting title explicitly?
 
372
        title = determine_title(description)
 
373
        # TOOD(jelmer): Set maintainers_can_modify?
 
374
        try:
 
375
            pull_request = target_repo.create_pull(
 
376
                title=title, body=description,
 
377
                head="%s:%s" % (self.source_owner, self.source_branch_name),
 
378
                base=self.target_branch_name)
 
379
        except github.GithubException as e:
 
380
            if e.status == 422:
 
381
                raise MergeProposalExists(self.source_branch.user_url)
 
382
            raise
 
383
        if reviewers:
 
384
            for reviewer in reviewers:
 
385
                pull_request.assignees.append(
 
386
                    self.gh.get_user(reviewer))
 
387
        if labels:
 
388
            for label in labels:
 
389
                pull_request.issue.labels.append(label)
 
390
        return GitHubMergeProposal(pull_request)