/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: Martin
  • Date: 2019-06-16 19:53:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7349.
  • Revision ID: gzlist@googlemail.com-20190616195327-awvhgbjo9g6mkt57
Relocate the bzr log file out of $HOME

Now under $XDG_CACHE_HOME on nix and %LOCALAPPDATA% on windows.

Setting $BRZ_HOME will override the cache location, to simplify test
isolation, and $BRZ_LOG is still the final word.

Drive-by fix various docs around bzr/brz spelling.

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 os
 
22
 
 
23
from .propose import (
 
24
    Hoster,
 
25
    HosterLoginRequired,
 
26
    MergeProposal,
 
27
    MergeProposalBuilder,
 
28
    MergeProposalExists,
 
29
    NoSuchProject,
 
30
    PrerequisiteBranchUnsupported,
 
31
    UnsupportedHoster,
 
32
    )
 
33
 
 
34
from ... import (
 
35
    bedding,
 
36
    branch as _mod_branch,
 
37
    controldir,
 
38
    errors,
 
39
    hooks,
 
40
    urlutils,
 
41
    version_string as breezy_version,
 
42
    )
 
43
from ...config import AuthenticationConfig, GlobalStack
 
44
from ...errors import InvalidHttpResponse
 
45
from ...git.urls import git_url_to_bzr_url
 
46
from ...i18n import gettext
 
47
from ...sixish import PY3
 
48
from ...trace import note
 
49
from ...transport import get_transport
 
50
from ...transport.http import default_user_agent
 
51
 
 
52
 
 
53
GITHUB_HOST = 'github.com'
 
54
WEB_GITHUB_URL = 'https://github.com'
 
55
API_GITHUB_URL = 'https://api.github.com'
 
56
 
 
57
 
 
58
def store_github_token(scheme, host, token):
 
59
    with open(os.path.join(bedding.config_dir(), 'github.conf'), 'w') as f:
 
60
        f.write(token)
 
61
 
 
62
 
 
63
def retrieve_github_token(scheme, host):
 
64
    path = os.path.join(bedding.config_dir(), 'github.conf')
 
65
    if not os.path.exists(path):
 
66
        return None
 
67
    with open(path, 'r') as f:
 
68
        return f.read().strip()
 
69
 
 
70
 
 
71
def determine_title(description):
 
72
    return description.splitlines()[0]
 
73
 
 
74
 
 
75
class NotGitHubUrl(errors.BzrError):
 
76
 
 
77
    _fmt = "Not a GitHub URL: %(url)s"
 
78
 
 
79
    def __init__(self, url):
 
80
        errors.BzrError.__init__(self)
 
81
        self.url = url
 
82
 
 
83
 
 
84
class GitHubLoginRequired(HosterLoginRequired):
 
85
 
 
86
    _fmt = "Action requires GitHub login."
 
87
 
 
88
 
 
89
def connect_github():
 
90
    """Connect to GitHub.
 
91
    """
 
92
    user_agent = default_user_agent()
 
93
    auth = AuthenticationConfig()
 
94
 
 
95
    credentials = auth.get_credentials('https', GITHUB_HOST)
 
96
    if credentials is not None:
 
97
        return Github(credentials['user'], credentials['password'],
 
98
                      user_agent=user_agent)
 
99
 
 
100
    # TODO(jelmer): token = auth.get_token('https', GITHUB_HOST)
 
101
    if token is not None:
 
102
        return Github(token, user_agent=user_agent)
 
103
    else:
 
104
        note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
 
105
        return Github(user_agent=user_agent)
 
106
 
 
107
 
 
108
class GitHubMergeProposal(MergeProposal):
 
109
 
 
110
    def __init__(self, pr):
 
111
        self._pr = pr
 
112
 
 
113
    @property
 
114
    def url(self):
 
115
        return self._pr['html_url']
 
116
 
 
117
    def _branch_from_part(self, part):
 
118
        return github_url_to_bzr_url(part['repo']['html_url'], part['ref'])
 
119
 
 
120
    def get_source_branch_url(self):
 
121
        return self._branch_from_part(self._pr['head'])
 
122
 
 
123
    def get_target_branch_url(self):
 
124
        return self._branch_from_part(self._pr['base'])
 
125
 
 
126
    def get_description(self):
 
127
        return self._pr['body']
 
128
 
 
129
    def get_commit_message(self):
 
130
        return None
 
131
 
 
132
    def set_description(self, description):
 
133
        self._pr.edit(body=description, title=determine_title(description))
 
134
 
 
135
    def is_merged(self):
 
136
        return self._pr['merged']
 
137
 
 
138
    def close(self):
 
139
        self._pr.edit(state='closed')
 
140
 
 
141
    def merge(self, commit_message=None):
 
142
        # https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
 
143
        self._pr.merge(commit_message=commit_message)
 
144
 
 
145
 
 
146
def parse_github_url(url):
 
147
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
148
        url)
 
149
    if host != GITHUB_HOST:
 
150
        raise NotGitHubUrl(url)
 
151
    (owner, repo_name) = path.strip('/').split('/')
 
152
    if repo_name.endswith('.git'):
 
153
        repo_name = repo_name[:-4]
 
154
    return owner, repo_name
 
155
 
 
156
 
 
157
def parse_github_branch_url(branch):
 
158
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
159
    owner, repo_name = parse_github_url(url)
 
160
    return owner, repo_name, branch.name
 
161
 
 
162
 
 
163
def github_url_to_bzr_url(url, branch_name):
 
164
    if not PY3:
 
165
        branch_name = branch_name.encode('utf-8')
 
166
    return urlutils.join_segment_parameters(
 
167
        git_url_to_bzr_url(url), {"branch": branch_name})
 
168
 
 
169
 
 
170
class GitHub(Hoster):
 
171
 
 
172
    name = 'github'
 
173
 
 
174
    supports_merge_proposal_labels = True
 
175
    supports_merge_proposal_commit_message = False
 
176
 
 
177
    def __repr__(self):
 
178
        return "GitHub()"
 
179
 
 
180
    def _api_request(self, method, path):
 
181
        headers = {
 
182
            'Accept': 'application/vnd.github.v3+json'}
 
183
        if self._token:
 
184
            headers['Authorization'] = 'token %s' % self._token
 
185
        response = self.transport.request(
 
186
            method, urlutils.join(self.transport.base, path),
 
187
            headers=headers)
 
188
        if response.status == 401:
 
189
            raise GitHubLoginRequired(self)
 
190
        return response
 
191
 
 
192
    def _get_repo(self, path):
 
193
        path = 'repos/' + path
 
194
        response = self._api_request('GET', path)
 
195
        if response.status == 404:
 
196
            raise NoSuchProject(path)
 
197
        if response.status == 200:
 
198
            return response.json
 
199
        raise InvalidHttpResponse(path, response.text)
 
200
 
 
201
    def _get_user(self, username=None):
 
202
        if username:
 
203
            path = 'users/:%s' % username
 
204
        else:
 
205
            path = 'user'
 
206
        response = self._api_request('GET', path)
 
207
        if response.status != 200:
 
208
            raise InvalidHttpResponse(path, response.text)
 
209
        return response.json
 
210
 
 
211
    def _get_organization(self, name):
 
212
        path = 'orgs/:%s' % name
 
213
        response = self._api_request('GET', path)
 
214
        if response.status != 200:
 
215
            raise InvalidHttpResponse(path, response.text)
 
216
        return response.json
 
217
 
 
218
    def _search_issues(self, query):
 
219
        path = 'search/issues'
 
220
        response = self._api_request(
 
221
            'GET', path + '?q=' + urlutils.quote(query))
 
222
        if response.status != 200:
 
223
            raise InvalidHttpResponse(path, response.text)
 
224
        return response.json
 
225
 
 
226
    def _create_fork(self, repo, owner=None):
 
227
        (orig_owner, orig_repo) = repo.split('/')
 
228
        path = '/repos/:%s/:%s/forks' % (orig_owner, orig_repo)
 
229
        if owner:
 
230
            path += '?organization=%s' % owner
 
231
        response = self._api_request('POST', path)
 
232
        if response != 202:
 
233
            raise InvalidHttpResponse(path, response.text)
 
234
        return response.json
 
235
 
 
236
    @property
 
237
    def base_url(self):
 
238
        return WEB_GITHUB_URL
 
239
 
 
240
    def __init__(self, transport):
 
241
        self._token = retrieve_github_token('https', GITHUB_HOST)
 
242
        self.transport = transport
 
243
        self._current_user = self._get_user()
 
244
 
 
245
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
246
                        owner=None, revision_id=None, overwrite=False,
 
247
                        allow_lossy=True):
 
248
        import github
 
249
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
250
        base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
251
        if owner is None:
 
252
            owner = self._current_user['login']
 
253
        if project is None:
 
254
            project = base_repo['name']
 
255
        try:
 
256
            remote_repo = self._get_repo('%s/%s' % (owner, project))
 
257
        except github.UnknownObjectException:
 
258
            base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
259
            remote_repo = self._create_fork(base_repo, owner)
 
260
            note(gettext('Forking new repository %s from %s') %
 
261
                 (remote_repo['html_url'], base_repo['html_url']))
 
262
        else:
 
263
            note(gettext('Reusing existing repository %s') % remote_repo['html_url'])
 
264
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo['ssh_url']))
 
265
        try:
 
266
            push_result = remote_dir.push_branch(
 
267
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
268
                name=name)
 
269
        except errors.NoRoundtrippingSupport:
 
270
            if not allow_lossy:
 
271
                raise
 
272
            push_result = remote_dir.push_branch(
 
273
                local_branch, revision_id=revision_id,
 
274
                overwrite=overwrite, name=name, lossy=True)
 
275
        return push_result.target_branch, github_url_to_bzr_url(
 
276
            remote_repo['html_url'], name)
 
277
 
 
278
    def get_push_url(self, branch):
 
279
        owner, project, branch_name = parse_github_branch_url(branch)
 
280
        repo = self._get_repo('%s/%s' % (owner, project))
 
281
        return github_url_to_bzr_url(repo['ssh_url'], branch_name)
 
282
 
 
283
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
284
        import github
 
285
        base_owner, base_project, base_branch_name = parse_github_branch_url(base_branch)
 
286
        base_repo = self._get_repo('%s/%s' % (base_owner, base_project))
 
287
        if owner is None:
 
288
            owner = self._current_user['login']
 
289
        if project is None:
 
290
            project = base_repo['name']
 
291
        try:
 
292
            remote_repo = self._get_repo('%s/%s' % (owner, project))
 
293
            full_url = github_url_to_bzr_url(remote_repo['ssh_url'], name)
 
294
            return _mod_branch.Branch.open(full_url)
 
295
        except github.UnknownObjectException:
 
296
            raise errors.NotBranchError('%s/%s/%s' % (WEB_GITHUB_URL, owner, project))
 
297
 
 
298
    def get_proposer(self, source_branch, target_branch):
 
299
        return GitHubMergeProposalBuilder(self, source_branch, target_branch)
 
300
 
 
301
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
302
        (source_owner, source_repo_name, source_branch_name) = (
 
303
            parse_github_branch_url(source_branch))
 
304
        (target_owner, target_repo_name, target_branch_name) = (
 
305
            parse_github_branch_url(target_branch))
 
306
        target_repo = self._get_repo(
 
307
            "%s/%s" % (target_owner, target_repo_name))
 
308
        state = {
 
309
            'open': 'open',
 
310
            'merged': 'closed',
 
311
            'closed': 'closed',
 
312
            'all': 'all'}
 
313
        for pull in target_repo.get_pulls(
 
314
                head=target_branch_name,
 
315
                state=state[status]):
 
316
            if (status == 'closed' and pull.merged or
 
317
                    status == 'merged' and not pull.merged):
 
318
                continue
 
319
            if pull.head.ref != source_branch_name:
 
320
                continue
 
321
            if pull.head.repo is None:
 
322
                # Repo has gone the way of the dodo
 
323
                continue
 
324
            if (pull.head.repo.owner.login != source_owner or
 
325
                    pull.head.repo.name != source_repo_name):
 
326
                continue
 
327
            yield GitHubMergeProposal(pull)
 
328
 
 
329
    def hosts(self, branch):
 
330
        try:
 
331
            parse_github_branch_url(branch)
 
332
        except NotGitHubUrl:
 
333
            return False
 
334
        else:
 
335
            return True
 
336
 
 
337
    @classmethod
 
338
    def probe_from_url(cls, url, possible_transports=None):
 
339
        try:
 
340
            parse_github_url(url)
 
341
        except NotGitHubUrl:
 
342
            raise UnsupportedHoster(url)
 
343
        transport = get_transport(
 
344
            API_GITHUB_URL, possible_transports=possible_transports)
 
345
        return cls(transport)
 
346
 
 
347
    @classmethod
 
348
    def iter_instances(cls):
 
349
        yield cls(get_transport(API_GITHUB_URL))
 
350
 
 
351
    def iter_my_proposals(self, status='open'):
 
352
        query = ['is:pr']
 
353
        if status == 'open':
 
354
            query.append('is:open')
 
355
        elif status == 'closed':
 
356
            query.append('is:unmerged')
 
357
            # Also use "is:closed" otherwise unmerged open pull requests are
 
358
            # also included.
 
359
            query.append('is:closed')
 
360
        elif status == 'merged':
 
361
            query.append('is:merged')
 
362
        query.append('author:%s' % self._current_user['login'])
 
363
        for issue in self._search_issues(query=' '.join(query))['items']:
 
364
            yield GitHubMergeProposal(
 
365
                self.transport.request('GET', issue['pull_request']['url']).json)
 
366
 
 
367
    def get_proposal_by_url(self, url):
 
368
        raise UnsupportedHoster(url)
 
369
 
 
370
 
 
371
class GitHubMergeProposalBuilder(MergeProposalBuilder):
 
372
 
 
373
    def __init__(self, gh, source_branch, target_branch):
 
374
        self.gh = gh
 
375
        self.source_branch = source_branch
 
376
        self.target_branch = target_branch
 
377
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
 
378
            parse_github_branch_url(self.target_branch))
 
379
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
 
380
            parse_github_branch_url(self.source_branch))
 
381
 
 
382
    def get_infotext(self):
 
383
        """Determine the initial comment for the merge proposal."""
 
384
        info = []
 
385
        info.append("Merge %s into %s:%s\n" % (
 
386
            self.source_branch_name, self.target_owner,
 
387
            self.target_branch_name))
 
388
        info.append("Source: %s\n" % self.source_branch.user_url)
 
389
        info.append("Target: %s\n" % self.target_branch.user_url)
 
390
        return ''.join(info)
 
391
 
 
392
    def get_initial_body(self):
 
393
        """Get a body for the proposal for the user to modify.
 
394
 
 
395
        :return: a str or None.
 
396
        """
 
397
        return None
 
398
 
 
399
    def create_proposal(self, description, reviewers=None, labels=None,
 
400
                        prerequisite_branch=None, commit_message=None):
 
401
        """Perform the submission."""
 
402
        if prerequisite_branch is not None:
 
403
            raise PrerequisiteBranchUnsupported(self)
 
404
        # Note that commit_message is ignored, since github doesn't support it.
 
405
        import github
 
406
        # TODO(jelmer): Probe for right repo name
 
407
        if self.target_repo_name.endswith('.git'):
 
408
            self.target_repo_name = self.target_repo_name[:-4]
 
409
        target_repo = self.gh._get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
 
410
        # TODO(jelmer): Allow setting title explicitly?
 
411
        title = determine_title(description)
 
412
        # TOOD(jelmer): Set maintainers_can_modify?
 
413
        try:
 
414
            pull_request = target_repo.create_pull(
 
415
                title=title, body=description,
 
416
                head="%s:%s" % (self.source_owner, self.source_branch_name),
 
417
                base=self.target_branch_name)
 
418
        except github.GithubException as e:
 
419
            if e.status == 422:
 
420
                raise MergeProposalExists(self.source_branch.user_url)
 
421
            raise
 
422
        if reviewers:
 
423
            for reviewer in reviewers:
 
424
                pull_request.assignees.append(
 
425
                    self.gh._get_user(reviewer)['login'])
 
426
        if labels:
 
427
            for label in labels:
 
428
                pull_request.issue.labels.append(label)
 
429
        return GitHubMergeProposal(pull_request)