/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-03 23:48:08 UTC
  • mfrom: (7316 work)
  • mto: This revision was merged to the branch mainline in revision 7328.
  • Revision ID: jelmer@jelmer.uk-20190603234808-15yk5c7054tj8e2b
Merge trunk.

Show diffs side-by-side

added added

removed removed

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