/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-03-05 07:32:38 UTC
  • mto: (7290.1.21 work)
  • mto: This revision was merged to the branch mainline in revision 7311.
  • Revision ID: jelmer@jelmer.uk-20190305073238-zlqn981opwnqsmzi
Add appveyor configuration.

Show diffs side-by-side

added added

removed removed

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