/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-07-12 01:01:45 UTC
  • mto: This revision was merged to the branch mainline in revision 7375.
  • Revision ID: jelmer@jelmer.uk-20190712010145-m7224qumb8w068zw
Fix importing from remote git repositories.

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