/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-02 02:35:46 UTC
  • mfrom: (7309 work)
  • mto: This revision was merged to the branch mainline in revision 7319.
  • Revision ID: jelmer@jelmer.uk-20190602023546-lqco868tnv26d8ow
merge trunk.

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 set_description(self, description):
 
126
        self._pr.edit(body=description, title=determine_title(description))
 
127
 
 
128
    def is_merged(self):
 
129
        return self._pr.merged
 
130
 
 
131
    def close(self):
 
132
        self._pr.edit(state='closed')
 
133
 
 
134
 
 
135
def parse_github_url(url):
 
136
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
137
        url)
 
138
    if host != 'github.com':
 
139
        raise NotGitHubUrl(url)
 
140
    (owner, repo_name) = path.strip('/').split('/')
 
141
    if repo_name.endswith('.git'):
 
142
        repo_name = repo_name[:-4]
 
143
    return owner, repo_name
 
144
 
 
145
 
 
146
def parse_github_branch_url(branch):
 
147
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
148
    owner, repo_name = parse_github_url(url)
 
149
    return owner, repo_name, branch.name
 
150
 
 
151
 
 
152
def github_url_to_bzr_url(url, branch_name):
 
153
    if not PY3:
 
154
        branch_name = branch_name.encode('utf-8')
 
155
    return urlutils.join_segment_parameters(
 
156
        git_url_to_bzr_url(url), {"branch": branch_name})
 
157
 
 
158
 
 
159
def convert_github_error(fn):
 
160
    def convert(self, *args, **kwargs):
 
161
        import github
 
162
        try:
 
163
            return fn(self, *args, **kwargs)
 
164
        except github.GithubException as e:
 
165
            if e.args[0] == 401:
 
166
                raise GitHubLoginRequired(self)
 
167
            raise
 
168
    return convert
 
169
 
 
170
 
 
171
class GitHub(Hoster):
 
172
 
 
173
    name = 'github'
 
174
 
 
175
    supports_merge_proposal_labels = True
 
176
 
 
177
    def __repr__(self):
 
178
        return "GitHub()"
 
179
 
 
180
    @property
 
181
    def base_url(self):
 
182
        # TODO(jelmer): Can we get the default URL from the Python API package
 
183
        # somehow?
 
184
        return "https://github.com"
 
185
 
 
186
    def __init__(self):
 
187
        self.gh = connect_github()
 
188
 
 
189
    @convert_github_error
 
190
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
191
                        owner=None, revision_id=None, overwrite=False,
 
192
                        allow_lossy=True):
 
193
        import github
 
194
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
195
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
196
        if owner is None:
 
197
            owner = self.gh.get_user().login
 
198
        if project is None:
 
199
            project = base_repo.name
 
200
        try:
 
201
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
202
            remote_repo.id
 
203
        except github.UnknownObjectException:
 
204
            base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
205
            if owner == self.gh.get_user().login:
 
206
                owner_obj = self.gh.get_user()
 
207
            else:
 
208
                owner_obj = self.gh.get_organization(owner)
 
209
            remote_repo = owner_obj.create_fork(base_repo)
 
210
            note(gettext('Forking new repository %s from %s') %
 
211
                 (remote_repo.html_url, base_repo.html_url))
 
212
        else:
 
213
            note(gettext('Reusing existing repository %s') % remote_repo.html_url)
 
214
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
 
215
        try:
 
216
            push_result = remote_dir.push_branch(
 
217
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
218
                name=name)
 
219
        except errors.NoRoundtrippingSupport:
 
220
            if not allow_lossy:
 
221
                raise
 
222
            push_result = remote_dir.push_branch(
 
223
                local_branch, revision_id=revision_id,
 
224
                overwrite=overwrite, name=name, lossy=True)
 
225
        return push_result.target_branch, github_url_to_bzr_url(
 
226
            remote_repo.html_url, name)
 
227
 
 
228
    @convert_github_error
 
229
    def get_push_url(self, branch):
 
230
        owner, project, branch_name = parse_github_branch_url(branch)
 
231
        repo = self.gh.get_repo('%s/%s' % (owner, project))
 
232
        return github_url_to_bzr_url(repo.ssh_url, branch_name)
 
233
 
 
234
    @convert_github_error
 
235
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
236
        import github
 
237
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
238
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
239
        if owner is None:
 
240
            owner = self.gh.get_user().login
 
241
        if project is None:
 
242
            project = base_repo.name
 
243
        try:
 
244
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
245
            full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
 
246
            return _mod_branch.Branch.open(full_url)
 
247
        except github.UnknownObjectException:
 
248
            raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
 
249
 
 
250
    @convert_github_error
 
251
    def get_proposer(self, source_branch, target_branch):
 
252
        return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
 
253
 
 
254
    @convert_github_error
 
255
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
256
        (source_owner, source_repo_name, source_branch_name) = (
 
257
            parse_github_branch_url(source_branch))
 
258
        (target_owner, target_repo_name, target_branch_name) = (
 
259
            parse_github_branch_url(target_branch))
 
260
        target_repo = self.gh.get_repo(
 
261
            "%s/%s" % (target_owner, target_repo_name))
 
262
        state = {
 
263
            'open': 'open',
 
264
            'merged': 'closed',
 
265
            'closed': 'closed',
 
266
            'all': 'all'}
 
267
        for pull in target_repo.get_pulls(
 
268
                head=target_branch_name,
 
269
                state=state[status]):
 
270
            if (status == 'closed' and pull.merged or
 
271
                    status == 'merged' and not pull.merged):
 
272
                continue
 
273
            if pull.head.ref != source_branch_name:
 
274
                continue
 
275
            if pull.head.repo is None:
 
276
                # Repo has gone the way of the dodo
 
277
                continue
 
278
            if (pull.head.repo.owner.login != source_owner or
 
279
                    pull.head.repo.name != source_repo_name):
 
280
                continue
 
281
            yield GitHubMergeProposal(pull)
 
282
 
 
283
    def hosts(self, branch):
 
284
        try:
 
285
            parse_github_branch_url(branch)
 
286
        except NotGitHubUrl:
 
287
            return False
 
288
        else:
 
289
            return True
 
290
 
 
291
    @classmethod
 
292
    def probe_from_url(cls, url):
 
293
        try:
 
294
            parse_github_url(url)
 
295
        except NotGitHubUrl:
 
296
            raise UnsupportedHoster(url)
 
297
        return cls()
 
298
 
 
299
    @classmethod
 
300
    def iter_instances(cls):
 
301
        yield cls()
 
302
 
 
303
    @convert_github_error
 
304
    def iter_my_proposals(self, status='open'):
 
305
        query = ['is:pr']
 
306
        if status == 'open':
 
307
            query.append('is:open')
 
308
        elif status == 'closed':
 
309
            query.append('is:unmerged')
 
310
            # Also use "is:closed" otherwise unmerged open pull requests are
 
311
            # also included.
 
312
            query.append('is:closed')
 
313
        elif status == 'merged':
 
314
            query.append('is:merged')
 
315
        query.append('author:%s' % self.gh.get_user().login)
 
316
        for issue in self.gh.search_issues(query=' '.join(query)):
 
317
            yield GitHubMergeProposal(issue.as_pull_request())
 
318
 
 
319
 
 
320
class GitHubMergeProposalBuilder(MergeProposalBuilder):
 
321
 
 
322
    def __init__(self, gh, source_branch, target_branch):
 
323
        self.gh = gh
 
324
        self.source_branch = source_branch
 
325
        self.target_branch = target_branch
 
326
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
 
327
            parse_github_branch_url(self.target_branch))
 
328
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
 
329
            parse_github_branch_url(self.source_branch))
 
330
 
 
331
    def get_infotext(self):
 
332
        """Determine the initial comment for the merge proposal."""
 
333
        info = []
 
334
        info.append("Merge %s into %s:%s\n" % (
 
335
            self.source_branch_name, self.target_owner,
 
336
            self.target_branch_name))
 
337
        info.append("Source: %s\n" % self.source_branch.user_url)
 
338
        info.append("Target: %s\n" % self.target_branch.user_url)
 
339
        return ''.join(info)
 
340
 
 
341
    def get_initial_body(self):
 
342
        """Get a body for the proposal for the user to modify.
 
343
 
 
344
        :return: a str or None.
 
345
        """
 
346
        return None
 
347
 
 
348
    def create_proposal(self, description, reviewers=None, labels=None,
 
349
                        prerequisite_branch=None):
 
350
        """Perform the submission."""
 
351
        if prerequisite_branch is not None:
 
352
            raise PrerequisiteBranchUnsupported(self)
 
353
        import github
 
354
        # TODO(jelmer): Probe for right repo name
 
355
        if self.target_repo_name.endswith('.git'):
 
356
            self.target_repo_name = self.target_repo_name[:-4]
 
357
        target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
 
358
        # TODO(jelmer): Allow setting title explicitly?
 
359
        title = determine_title(description)
 
360
        # TOOD(jelmer): Set maintainers_can_modify?
 
361
        try:
 
362
            pull_request = target_repo.create_pull(
 
363
                title=title, body=description,
 
364
                head="%s:%s" % (self.source_owner, self.source_branch_name),
 
365
                base=self.target_branch_name)
 
366
        except github.GithubException as e:
 
367
            if e.status == 422:
 
368
                raise MergeProposalExists(self.source_branch.user_url)
 
369
            raise
 
370
        if reviewers:
 
371
            for reviewer in reviewers:
 
372
                pull_request.assignees.append(
 
373
                    self.gh.get_user(reviewer))
 
374
        if labels:
 
375
            for label in labels:
 
376
                pull_request.issue.labels.append(label)
 
377
        return GitHubMergeProposal(pull_request)