/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/github/hoster.py

  • Committer: Jelmer Vernooij
  • Date: 2020-07-15 21:51:27 UTC
  • mto: (7490.40.58 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200715215127-3hn9ktbg3f1xikjj
More fixes for hg probing.

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