/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-08-06 07:11:09 UTC
  • mto: This revision was merged to the branch mainline in revision 7380.
  • Revision ID: jelmer@jelmer.uk-20190806071109-9hpyx668kg0bsv9k
Handle invalid repository name on GitHub.

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, gh, pr):
 
112
        self._gh = gh
 
113
        self._pr = pr
 
114
 
 
115
    @property
 
116
    def url(self):
 
117
        return self._pr['html_url']
 
118
 
 
119
    def _branch_from_part(self, part):
 
120
        return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
 
121
 
 
122
    def get_source_branch_url(self):
 
123
        return self._branch_from_part(self._pr['head'])
 
124
 
 
125
    def get_target_branch_url(self):
 
126
        return self._branch_from_part(self._pr['base'])
 
127
 
 
128
    def get_description(self):
 
129
        return self._pr['body']
 
130
 
 
131
    def get_commit_message(self):
 
132
        return None
 
133
 
 
134
    def set_commit_message(self, message):
 
135
        self._patch({'title': message})
 
136
 
 
137
    def _patch(self, data):
 
138
        response = self._gh._api_request(
 
139
            'PATCH', self._pr['url'], body=json.dumps(data).encode('utf-8'))
 
140
        if response != 200:
 
141
            raise InvalidHttpResponse(self._pr['url'], response.text)
 
142
        self._pr = json.loads(response.text)
 
143
 
 
144
    def set_description(self, description):
 
145
        self._patch({
 
146
            'body': description,
 
147
            'title': determine_title(description),
 
148
            })
 
149
 
 
150
    def is_merged(self):
 
151
        return self._pr['state'] == 'merged'
 
152
 
 
153
    def close(self):
 
154
        self._patch({'state': 'closed'})
 
155
 
 
156
    def merge(self, commit_message=None):
 
157
        # https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
 
158
        self._pr.merge(commit_message=commit_message)
 
159
 
 
160
 
 
161
def parse_github_url(url):
 
162
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
163
        url)
 
164
    if host != GITHUB_HOST:
 
165
        raise NotGitHubUrl(url)
 
166
    (owner, repo_name) = path.strip('/').split('/')
 
167
    if repo_name.endswith('.git'):
 
168
        repo_name = repo_name[:-4]
 
169
    return owner, repo_name
 
170
 
 
171
 
 
172
def parse_github_branch_url(branch):
 
173
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
174
    owner, repo_name = parse_github_url(url)
 
175
    return owner, repo_name, branch.name
 
176
 
 
177
 
 
178
def github_url_to_bzr_url(url, branch_name):
 
179
    if not PY3:
 
180
        branch_name = branch_name.encode('utf-8')
 
181
    return urlutils.join_segment_parameters(
 
182
        git_url_to_bzr_url(url), {"branch": branch_name})
 
183
 
 
184
 
 
185
class GitHub(Hoster):
 
186
 
 
187
    name = 'github'
 
188
 
 
189
    supports_merge_proposal_labels = True
 
190
    supports_merge_proposal_commit_message = False
 
191
 
 
192
    def __repr__(self):
 
193
        return "GitHub()"
 
194
 
 
195
    def _api_request(self, method, path, body=None):
 
196
        headers = {
 
197
            'Accept': 'application/vnd.github.v3+json'}
 
198
        if self._token:
 
199
            headers['Authorization'] = 'token %s' % self._token
 
200
        response = self.transport.request(
 
201
            method, urlutils.join(self.transport.base, path),
 
202
            headers=headers, body=body)
 
203
        if response.status == 401:
 
204
            raise GitHubLoginRequired(self)
 
205
        return response
 
206
 
 
207
    def _get_repo(self, path):
 
208
        path = 'repos/' + path
 
209
        response = self._api_request('GET', path)
 
210
        if response.status == 404:
 
211
            raise NoSuchProject(path)
 
212
        if response.status == 200:
 
213
            return json.loads(response.text)
 
214
        raise InvalidHttpResponse(path, response.text)
 
215
 
 
216
    def _get_repo_pulls(self, path, head=None, state=None):
 
217
        path = 'repos/' + path + '/pulls?'
 
218
        params = {}
 
219
        if head is not None:
 
220
            params['head'] = head
 
221
        if state is not None:
 
222
            params['state'] = state
 
223
        path += ';'.join(['%s=%s' % (k, urlutils.quote(v))
 
224
                         for k, v in params.items()])
 
225
        response = self._api_request('GET', path)
 
226
        if response.status == 404:
 
227
            raise NoSuchProject(path)
 
228
        if response.status == 200:
 
229
            return json.loads(response.text)
 
230
        raise InvalidHttpResponse(path, response.text)
 
231
 
 
232
    def _get_user(self, username=None):
 
233
        if username:
 
234
            path = 'users/:%s' % username
 
235
        else:
 
236
            path = 'user'
 
237
        response = self._api_request('GET', path)
 
238
        if response.status != 200:
 
239
            raise InvalidHttpResponse(path, response.text)
 
240
        return json.loads(response.text)
 
241
 
 
242
    def _get_organization(self, name):
 
243
        path = 'orgs/:%s' % name
 
244
        response = self._api_request('GET', path)
 
245
        if response.status != 200:
 
246
            raise InvalidHttpResponse(path, response.text)
 
247
        return json.loads(response.text)
 
248
 
 
249
    def _search_issues(self, query):
 
250
        path = 'search/issues'
 
251
        response = self._api_request(
 
252
            'GET', path + '?q=' + urlutils.quote(query))
 
253
        if response.status != 200:
 
254
            raise InvalidHttpResponse(path, response.text)
 
255
        return json.loads(response.text)
 
256
 
 
257
    def _create_fork(self, repo, owner=None):
 
258
        (orig_owner, orig_repo) = repo.split('/')
 
259
        path = '/repos/:%s/:%s/forks' % (orig_owner, orig_repo)
 
260
        if owner:
 
261
            path += '?organization=%s' % owner
 
262
        response = self._api_request('POST', path)
 
263
        if response != 202:
 
264
            raise InvalidHttpResponse(path, response.text)
 
265
        return json.loads(response.text)
 
266
 
 
267
    @property
 
268
    def base_url(self):
 
269
        return WEB_GITHUB_URL
 
270
 
 
271
    def __init__(self, transport):
 
272
        self._token = retrieve_github_token('https', GITHUB_HOST)
 
273
        self.transport = transport
 
274
        self._current_user = self._get_user()
 
275
 
 
276
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
277
                        owner=None, revision_id=None, overwrite=False,
 
278
                        allow_lossy=True):
 
279
        import github
 
280
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
281
        base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
282
        if owner is None:
 
283
            owner = self._current_user['login']
 
284
        if project is None:
 
285
            project = base_repo['name']
 
286
        try:
 
287
            remote_repo = self._get_repo('%s/%s' % (owner, project))
 
288
        except github.UnknownObjectException:
 
289
            base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
290
            remote_repo = self._create_fork(base_repo, owner)
 
291
            note(gettext('Forking new repository %s from %s') %
 
292
                 (remote_repo['html_url'], base_repo['html_url']))
 
293
        else:
 
294
            note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
 
295
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
 
296
        try:
 
297
            push_result = remote_dir.push_branch(
 
298
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
299
                name=name)
 
300
        except errors.NoRoundtrippingSupport:
 
301
            if not allow_lossy:
 
302
                raise
 
303
            push_result = remote_dir.push_branch(
 
304
                local_branch, revision_id=revision_id,
 
305
                overwrite=overwrite, name=name, lossy=True)
 
306
        return push_result.target_branch, github_url_to_bzr_url(
 
307
            remote_repo['html_url'], name)
 
308
 
 
309
    def get_push_url(self, branch):
 
310
        owner, project, branch_name = parse_github_branch_url(branch)
 
311
        repo = self._get_repo('%s/%s' % (owner, project))
 
312
        return github_url_to_bzr_url(repo['ssh_url'], branch_name)
 
313
 
 
314
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
315
        import github
 
316
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
317
        base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
318
        if owner is None:
 
319
            owner = self._current_user['login']
 
320
        if project is None:
 
321
            project = base_repo['name']
 
322
        try:
 
323
            remote_repo = self._get_repo('%s/%s' % (owner, project))
 
324
            full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
 
325
            return _mod_branch.Branch.open(full_url)
 
326
        except github.UnknownObjectException:
 
327
            raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
 
328
 
 
329
    def get_proposer(self, source_branch, target_branch):
 
330
        return GitHubMergeProposalBuilder(self, source_branch, target_branch)
 
331
 
 
332
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
333
        (source_owner, source_repo_name, source_branch_name) = (
 
334
            parse_github_branch_url(source_branch))
 
335
        (target_owner, target_repo_name, target_branch_name) = (
 
336
            parse_github_branch_url(target_branch))
 
337
        target_repo_path = "%s/%s" % (target_owner, target_repo_name)
 
338
        target_repo = self._get_repo(target_repo_path)
 
339
        state = {
 
340
            'open': 'open',
 
341
            'merged': 'closed',
 
342
            'closed': 'closed',
 
343
            'all': 'all'}
 
344
        pulls = self._get_repo_pulls(
 
345
            target_repo_path,
 
346
            head=target_branch_name,
 
347
            state=state[status])
 
348
        for pull in pulls:
 
349
            if (status == 'closed' and pull['merged'] or
 
350
                    status == 'merged' and not pull['merged']):
 
351
                continue
 
352
            if pull['head']['ref'] != source_branch_name:
 
353
                continue
 
354
            if pull['head']['repo'] is None:
 
355
                # Repo has gone the way of the dodo
 
356
                continue
 
357
            if (pull['head']['repo']['owner']['login'] != source_owner or
 
358
                    pull['head']['repo']['name'] != source_repo_name):
 
359
                continue
 
360
            yield GitHubMergeProposal(self, pull)
 
361
 
 
362
    def hosts(self, branch):
 
363
        try:
 
364
            parse_github_branch_url(branch)
 
365
        except NotGitHubUrl:
 
366
            return False
 
367
        else:
 
368
            return True
 
369
 
 
370
    @classmethod
 
371
    def probe_from_url(cls, url, possible_transports=None):
 
372
        try:
 
373
            parse_github_url(url)
 
374
        except NotGitHubUrl:
 
375
            raise UnsupportedHoster(url)
 
376
        transport = get_transport(
 
377
            API_GITHUB_URL, possible_transports=possible_transports)
 
378
        return cls(transport)
 
379
 
 
380
    @classmethod
 
381
    def iter_instances(cls):
 
382
        yield cls(get_transport(API_GITHUB_URL))
 
383
 
 
384
    def iter_my_proposals(self, status='open'):
 
385
        query = ['is:pr']
 
386
        if status == 'open':
 
387
            query.append('is:open')
 
388
        elif status == 'closed':
 
389
            query.append('is:unmerged')
 
390
            # Also use "is:closed" otherwise unmerged open pull requests are
 
391
            # also included.
 
392
            query.append('is:closed')
 
393
        elif status == 'merged':
 
394
            query.append('is:merged')
 
395
        query.append('author:%s' % self._current_user['login'])
 
396
        for issue in self._search_issues(query=' '.join(query))['items']:
 
397
            url = issue['pull_request']['url']
 
398
            response = self._api_request('GET', url)
 
399
            if response.status != 200:
 
400
                raise InvalidHttpResponse(url, response.text)
 
401
            yield GitHubMergeProposal(self, json.loads(response.text))
 
402
 
 
403
    def get_proposal_by_url(self, url):
 
404
        raise UnsupportedHoster(url)
 
405
 
 
406
 
 
407
class GitHubMergeProposalBuilder(MergeProposalBuilder):
 
408
 
 
409
    def __init__(self, gh, source_branch, target_branch):
 
410
        self.gh = gh
 
411
        self.source_branch = source_branch
 
412
        self.target_branch = target_branch
 
413
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
 
414
            parse_github_branch_url(self.target_branch))
 
415
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
 
416
            parse_github_branch_url(self.source_branch))
 
417
 
 
418
    def get_infotext(self):
 
419
        """Determine the initial comment for the merge proposal."""
 
420
        info = []
 
421
        info.append("Merge %s into %s:%s\n" % (
 
422
            self.source_branch_name, self.target_owner,
 
423
            self.target_branch_name))
 
424
        info.append("Source: %s\n" % self.source_branch.user_url)
 
425
        info.append("Target: %s\n" % self.target_branch.user_url)
 
426
        return ''.join(info)
 
427
 
 
428
    def get_initial_body(self):
 
429
        """Get a body for the proposal for the user to modify.
 
430
 
 
431
        :return: a str or None.
 
432
        """
 
433
        return None
 
434
 
 
435
    def create_proposal(self, description, reviewers=None, labels=None,
 
436
                        prerequisite_branch=None, commit_message=None):
 
437
        """Perform the submission."""
 
438
        if prerequisite_branch is not None:
 
439
            raise PrerequisiteBranchUnsupported(self)
 
440
        # Note that commit_message is ignored, since github doesn't support it.
 
441
        import github
 
442
        # TODO(jelmer): Probe for right repo name
 
443
        if self.target_repo_name.endswith('.git'):
 
444
            self.target_repo_name = self.target_repo_name[:-4]
 
445
        target_repo = self.gh._get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
 
446
        # TODO(jelmer): Allow setting title explicitly?
 
447
        title = determine_title(description)
 
448
        # TOOD(jelmer): Set maintainers_can_modify?
 
449
        try:
 
450
            pull_request = target_repo.create_pull(
 
451
                title=title, body=description,
 
452
                head="%s:%s" % (self.source_owner, self.source_branch_name),
 
453
                base=self.target_branch_name)
 
454
        except github.GithubException as e:
 
455
            if e.status == 422:
 
456
                raise MergeProposalExists(self.source_branch.user_url)
 
457
            raise
 
458
        if reviewers:
 
459
            for reviewer in reviewers:
 
460
                pull_request.assignees.append(
 
461
                    self.gh._get_user(reviewer)['login'])
 
462
        if labels:
 
463
            for label in labels:
 
464
                pull_request.issue.labels.append(label)
 
465
        return GitHubMergeProposal(self.gh, pull_request)