/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-10-28 01:38:39 UTC
  • mto: This revision was merged to the branch mainline in revision 7412.
  • Revision ID: jelmer@jelmer.uk-20191028013839-q63zzm4yr0id9b3o
Allow unknown extras in git commits when just inspecting revisions, rather than importing.

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