/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: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2019-01-28 23:51:14 UTC
  • mfrom: (7251.1.1 skip-crypto-deprecation)
  • Revision ID: breezy.the.bot@gmail.com-20190128235114-wurthh67hpldlyip
Ignore UserWarning on travis.

Merged from https://code.launchpad.net/~jelmer/brz/skip-crypto-deprecation/+merge/362227

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
    MergeProposal,
 
26
    MergeProposalBuilder,
 
27
    MergeProposalExists,
 
28
    PrerequisiteBranchUnsupported,
 
29
    UnsupportedHoster,
 
30
    )
 
31
 
 
32
from ... import (
 
33
    branch as _mod_branch,
 
34
    controldir,
 
35
    errors,
 
36
    hooks,
 
37
    urlutils,
 
38
    version_string as breezy_version,
 
39
    )
 
40
from ...config import AuthenticationConfig, GlobalStack, config_dir
 
41
from ...git.urls import git_url_to_bzr_url
 
42
from ...i18n import gettext
 
43
from ...sixish import PY3
 
44
from ...trace import note
 
45
from ...lazy_import import lazy_import
 
46
lazy_import(globals(), """
 
47
from github import Github
 
48
""")
 
49
 
 
50
 
 
51
def store_github_token(scheme, host, token):
 
52
    with open(os.path.join(config_dir(), 'github.conf'), 'w') as f:
 
53
        f.write(token)
 
54
 
 
55
 
 
56
def retrieve_github_token(scheme, host):
 
57
    path = os.path.join(config_dir(), 'github.conf')
 
58
    if not os.path.exists(path):
 
59
        return None
 
60
    with open(path, 'r') as f:
 
61
        return f.read().strip()
 
62
 
 
63
 
 
64
def determine_title(description):
 
65
    return description.splitlines()[0]
 
66
 
 
67
 
 
68
class NotGitHubUrl(errors.BzrError):
 
69
 
 
70
    _fmt = "Not a GitHub URL: %(url)s"
 
71
 
 
72
    def __init__(self, url):
 
73
        errors.BzrError.__init__(self)
 
74
        self.url = url
 
75
 
 
76
 
 
77
def connect_github():
 
78
    """Connect to GitHub.
 
79
    """
 
80
    user_agent = "Breezy/%s" % breezy_version
 
81
 
 
82
    auth = AuthenticationConfig()
 
83
 
 
84
    credentials = auth.get_credentials('https', 'github.com')
 
85
    if credentials is not None:
 
86
        return Github(credentials['user'], credentials['password'],
 
87
                      user_agent=user_agent)
 
88
 
 
89
    # TODO(jelmer): token = auth.get_token('https', 'github.com')
 
90
    token = retrieve_github_token('https', 'github.com')
 
91
    if token is not None:
 
92
        return Github(token, user_agent=user_agent)
 
93
    else:
 
94
        note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
 
95
        return Github(user_agent=user_agent)
 
96
 
 
97
 
 
98
class GitHubMergeProposal(MergeProposal):
 
99
 
 
100
    def __init__(self, pr):
 
101
        self._pr = pr
 
102
 
 
103
    @property
 
104
    def url(self):
 
105
        return self._pr.html_url
 
106
 
 
107
    def _branch_from_part(self, part):
 
108
        return github_url_to_bzr_url(part.repo.html_url, part.ref)
 
109
 
 
110
    def get_source_branch_url(self):
 
111
        return self._branch_from_part(self._pr.head)
 
112
 
 
113
    def get_target_branch_url(self):
 
114
        return self._branch_from_part(self._pr.base)
 
115
 
 
116
    def get_description(self):
 
117
        return self._pr.body
 
118
 
 
119
    def set_description(self, description):
 
120
        self._pr.edit(body=description, title=determine_title(description))
 
121
 
 
122
    def is_merged(self):
 
123
        return self._pr.merged
 
124
 
 
125
 
 
126
def parse_github_url(branch):
 
127
    url = urlutils.split_segment_parameters(branch.user_url)[0]
 
128
    (scheme, user, password, host, port, path) = urlutils.parse_url(
 
129
        url)
 
130
    if host != 'github.com':
 
131
        raise NotGitHubUrl(url)
 
132
    (owner, repo_name) = path.strip('/').split('/')
 
133
    if repo_name.endswith('.git'):
 
134
        repo_name = repo_name[:-4]
 
135
    return owner, repo_name, branch.name
 
136
 
 
137
 
 
138
def github_url_to_bzr_url(url, branch_name):
 
139
    if not PY3:
 
140
        branch_name = branch_name.encode('utf-8')
 
141
    return urlutils.join_segment_parameters(
 
142
        git_url_to_bzr_url(url), {"branch": branch_name})
 
143
 
 
144
 
 
145
class GitHub(Hoster):
 
146
 
 
147
    name = 'github'
 
148
 
 
149
    supports_merge_proposal_labels = True
 
150
 
 
151
    def __repr__(self):
 
152
        return "GitHub()"
 
153
 
 
154
    def __init__(self):
 
155
        self.gh = connect_github()
 
156
 
 
157
    def publish_derived(self, local_branch, base_branch, name, project=None,
 
158
                        owner=None, revision_id=None, overwrite=False,
 
159
                        allow_lossy=True):
 
160
        import github
 
161
        base_owner, base_project, base_branch_name = parse_github_url(base_branch)
 
162
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
163
        if owner is None:
 
164
            owner = self.gh.get_user().login
 
165
        if project is None:
 
166
            project = base_repo.name
 
167
        try:
 
168
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
169
            remote_repo.id
 
170
        except github.UnknownObjectException:
 
171
            base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
172
            if owner == self.gh.get_user().login:
 
173
                owner_obj = self.gh.get_user()
 
174
            else:
 
175
                owner_obj = self.gh.get_organization(owner)
 
176
            remote_repo = owner_obj.create_fork(base_repo)
 
177
            note(gettext('Forking new repository %s from %s') %
 
178
                 (remote_repo.html_url, base_repo.html_url))
 
179
        else:
 
180
            note(gettext('Reusing existing repository %s') % remote_repo.html_url)
 
181
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
 
182
        try:
 
183
            push_result = remote_dir.push_branch(
 
184
                local_branch, revision_id=revision_id, overwrite=overwrite,
 
185
                name=name)
 
186
        except errors.NoRoundtrippingSupport:
 
187
            if not allow_lossy:
 
188
                raise
 
189
            push_result = remote_dir.push_branch(
 
190
                local_branch, revision_id=revision_id,
 
191
                overwrite=overwrite, name=name, lossy=True)
 
192
        return push_result.target_branch, github_url_to_bzr_url(
 
193
            remote_repo.html_url, name)
 
194
 
 
195
    def get_push_url(self, branch):
 
196
        owner, project, branch_name = parse_github_url(branch)
 
197
        repo = self.gh.get_repo('%s/%s' % (owner, project))
 
198
        return github_url_to_bzr_url(repo.ssh_url, branch_name)
 
199
 
 
200
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
 
201
        import github
 
202
        base_owner, base_project, base_branch_name = parse_github_url(base_branch)
 
203
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
 
204
        if owner is None:
 
205
            owner = self.gh.get_user().login
 
206
        if project is None:
 
207
            project = base_repo.name
 
208
        try:
 
209
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
 
210
            full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
 
211
            return _mod_branch.Branch.open(full_url)
 
212
        except github.UnknownObjectException:
 
213
            raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
 
214
 
 
215
    def get_proposer(self, source_branch, target_branch):
 
216
        return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
 
217
 
 
218
    def iter_proposals(self, source_branch, target_branch, status='open'):
 
219
        (source_owner, source_repo_name, source_branch_name) = (
 
220
            parse_github_url(source_branch))
 
221
        (target_owner, target_repo_name, target_branch_name) = (
 
222
            parse_github_url(target_branch))
 
223
        target_repo = self.gh.get_repo(
 
224
            "%s/%s" % (target_owner, target_repo_name))
 
225
        state = {
 
226
            'open': 'open',
 
227
            'merged': 'closed',
 
228
            'closed': 'closed',
 
229
            'all': 'all'}
 
230
        for pull in target_repo.get_pulls(
 
231
                head=target_branch_name,
 
232
                state=state[status]):
 
233
            if (status == 'closed' and pull.merged or
 
234
                    status == 'merged' and not pull.merged):
 
235
                continue
 
236
            if pull.head.ref != source_branch_name:
 
237
                continue
 
238
            if (pull.head.repo.owner.login != source_owner or
 
239
                    pull.head.repo.name != source_repo_name):
 
240
                continue
 
241
            yield GitHubMergeProposal(pull)
 
242
 
 
243
    def hosts(self, branch):
 
244
        try:
 
245
            parse_github_url(branch)
 
246
        except NotGitHubUrl:
 
247
            return False
 
248
        else:
 
249
            return True
 
250
 
 
251
    @classmethod
 
252
    def probe(cls, branch):
 
253
        try:
 
254
            parse_github_url(branch)
 
255
        except NotGitHubUrl:
 
256
            raise UnsupportedHoster(branch)
 
257
        return cls()
 
258
 
 
259
    @classmethod
 
260
    def iter_instances(cls):
 
261
        yield cls()
 
262
 
 
263
    def iter_my_proposals(self, status='open'):
 
264
        query = ['is:pr']
 
265
        if status == 'open':
 
266
            query.append('is:open')
 
267
        elif status == 'closed':
 
268
            # Note that we don't use is:closed here, since that also includes
 
269
            # merged pull requests.
 
270
            query.append('is:unmerged')
 
271
        elif status == 'merged':
 
272
            query.append('is:merged')
 
273
        query.append('author:%s' % self.gh.get_user().login)
 
274
        for issue in self.gh.search_issues(query=' '.join(query)):
 
275
            yield GitHubMergeProposal(issue.as_pull_request())
 
276
 
 
277
 
 
278
class GitHubMergeProposalBuilder(MergeProposalBuilder):
 
279
 
 
280
    def __init__(self, gh, source_branch, target_branch):
 
281
        self.gh = gh
 
282
        self.source_branch = source_branch
 
283
        self.target_branch = target_branch
 
284
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
 
285
            parse_github_url(self.target_branch))
 
286
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
 
287
            parse_github_url(self.source_branch))
 
288
 
 
289
    def get_infotext(self):
 
290
        """Determine the initial comment for the merge proposal."""
 
291
        info = []
 
292
        info.append("Merge %s into %s:%s\n" % (
 
293
            self.source_branch_name, self.target_owner,
 
294
            self.target_branch_name))
 
295
        info.append("Source: %s\n" % self.source_branch.user_url)
 
296
        info.append("Target: %s\n" % self.target_branch.user_url)
 
297
        return ''.join(info)
 
298
 
 
299
    def get_initial_body(self):
 
300
        """Get a body for the proposal for the user to modify.
 
301
 
 
302
        :return: a str or None.
 
303
        """
 
304
        return None
 
305
 
 
306
    def create_proposal(self, description, reviewers=None, labels=None,
 
307
                        prerequisite_branch=None):
 
308
        """Perform the submission."""
 
309
        if prerequisite_branch is not None:
 
310
            raise PrerequisiteBranchUnsupported(self)
 
311
        import github
 
312
        # TODO(jelmer): Probe for right repo name
 
313
        if self.target_repo_name.endswith('.git'):
 
314
            self.target_repo_name = self.target_repo_name[:-4]
 
315
        target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
 
316
        # TODO(jelmer): Allow setting title explicitly?
 
317
        title = determine_title(description)
 
318
        # TOOD(jelmer): Set maintainers_can_modify?
 
319
        try:
 
320
            pull_request = target_repo.create_pull(
 
321
                title=title, body=description,
 
322
                head="%s:%s" % (self.source_owner, self.source_branch_name),
 
323
                base=self.target_branch_name)
 
324
        except github.GithubException as e:
 
325
            if e.status == 422:
 
326
                raise MergeProposalExists(self.source_branch.user_url)
 
327
            raise
 
328
        if reviewers:
 
329
            for reviewer in reviewers:
 
330
                pull_request.assignees.append(
 
331
                    self.gh.get_user(reviewer))
 
332
        if labels:
 
333
            for label in labels:
 
334
                pull_request.issue.labels.append(label)
 
335
        return GitHubMergeProposal(pull_request)