/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
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
0.434.1 by Jelmer Vernooij
Use absolute_import.
17
"""Support for GitHub."""
18
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
19
from __future__ import absolute_import
20
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
21
import os
22
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
23
from .propose import (
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
24
    Hoster,
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
25
    MergeProposal,
0.432.2 by Jelmer Vernooij
Publish command sort of works.
26
    MergeProposalBuilder,
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
27
    MergeProposalExists,
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
28
    PrerequisiteBranchUnsupported,
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
29
    UnsupportedHoster,
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
30
    )
31
32
from ... import (
0.431.33 by Jelmer Vernooij
Fix URLs from gitlab.
33
    branch as _mod_branch,
0.432.3 by Jelmer Vernooij
Publish command works for github.
34
    controldir,
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
35
    errors,
36
    hooks,
37
    urlutils,
0.432.3 by Jelmer Vernooij
Publish command works for github.
38
    version_string as breezy_version,
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
39
    )
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
40
from ...config import AuthenticationConfig, GlobalStack, config_dir
0.431.32 by Jelmer Vernooij
Properly resolve git+ssh URLs.
41
from ...git.urls import git_url_to_bzr_url
0.432.3 by Jelmer Vernooij
Publish command works for github.
42
from ...i18n import gettext
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
43
from ...sixish import PY3
0.432.3 by Jelmer Vernooij
Publish command works for github.
44
from ...trace import note
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
45
from ...lazy_import import lazy_import
46
lazy_import(globals(), """
47
from github import Github
48
""")
49
50
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
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
0.435.1 by Jelmer Vernooij
Fix reading github credentials.
60
    with open(path, 'r') as f:
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
61
        return f.read().strip()
62
63
0.431.44 by Jelmer Vernooij
Support get/set description.
64
def determine_title(description):
65
    return description.splitlines()[0]
66
67
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
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():
7211.13.7 by Jelmer Vernooij
Fix formatting.
78
    """Connect to GitHub.
79
    """
80
    user_agent = "Breezy/%s" % breezy_version
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
81
82
    auth = AuthenticationConfig()
83
84
    credentials = auth.get_credentials('https', 'github.com')
85
    if credentials is not None:
0.432.3 by Jelmer Vernooij
Publish command works for github.
86
        return Github(credentials['user'], credentials['password'],
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
87
                      user_agent=user_agent)
88
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
89
    # TODO(jelmer): token = auth.get_token('https', 'github.com')
90
    token = retrieve_github_token('https', 'github.com')
91
    if token is not None:
0.431.61 by Jelmer Vernooij
Fix token login.
92
        return Github(token, user_agent=user_agent)
0.431.49 by Jelmer Vernooij
Store GitHub tokens in a magic file, for now.
93
    else:
94
        note('Accessing GitHub anonymously. To log in, run \'brz gh-login\'.')
95
        return Github(user_agent=user_agent)
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
96
97
0.431.44 by Jelmer Vernooij
Support get/set description.
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
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
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
0.431.44 by Jelmer Vernooij
Support get/set description.
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
0.431.46 by Jelmer Vernooij
Add MergeProposal.is_merged.
122
    def is_merged(self):
123
        return self._pr.merged
124
0.431.44 by Jelmer Vernooij
Support get/set description.
125
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
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('/')
0.432.12 by Jelmer Vernooij
Fix .git ends.
133
    if repo_name.endswith('.git'):
134
        repo_name = repo_name[:-4]
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
135
    return owner, repo_name, branch.name
136
137
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
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(
7211.13.7 by Jelmer Vernooij
Fix formatting.
142
        git_url_to_bzr_url(url), {"branch": branch_name})
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
143
144
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
145
class GitHub(Hoster):
146
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
147
    name = 'github'
148
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
149
    supports_merge_proposal_labels = True
150
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
151
    def __repr__(self):
152
        return "GitHub()"
153
7260.1.1 by Jelmer Vernooij
Add .base_url property to Hoster.
154
    @property
155
    def base_url(self):
156
        # TODO(jelmer): Can we get the default URL from the Python API package
157
        # somehow?
158
        return "https://github.com"
159
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
160
    def __init__(self):
161
        self.gh = connect_github()
162
0.431.20 by Jelmer Vernooij
publish -> publish_derived.
163
    def publish_derived(self, local_branch, base_branch, name, project=None,
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
164
                        owner=None, revision_id=None, overwrite=False,
165
                        allow_lossy=True):
0.432.12 by Jelmer Vernooij
Fix .git ends.
166
        import github
0.432.3 by Jelmer Vernooij
Publish command works for github.
167
        base_owner, base_project, base_branch_name = parse_github_url(base_branch)
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
168
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
0.432.3 by Jelmer Vernooij
Publish command works for github.
169
        if owner is None:
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
170
            owner = self.gh.get_user().login
0.432.3 by Jelmer Vernooij
Publish command works for github.
171
        if project is None:
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
172
            project = base_repo.name
0.432.3 by Jelmer Vernooij
Publish command works for github.
173
        try:
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
174
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
0.432.12 by Jelmer Vernooij
Fix .git ends.
175
            remote_repo.id
176
        except github.UnknownObjectException:
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
177
            base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
178
            if owner == self.gh.get_user().login:
179
                owner_obj = self.gh.get_user()
0.432.3 by Jelmer Vernooij
Publish command works for github.
180
            else:
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
181
                owner_obj = self.gh.get_organization(owner)
0.432.12 by Jelmer Vernooij
Fix .git ends.
182
            remote_repo = owner_obj.create_fork(base_repo)
0.432.3 by Jelmer Vernooij
Publish command works for github.
183
            note(gettext('Forking new repository %s from %s') %
7211.13.7 by Jelmer Vernooij
Fix formatting.
184
                 (remote_repo.html_url, base_repo.html_url))
0.432.3 by Jelmer Vernooij
Publish command works for github.
185
        else:
186
            note(gettext('Reusing existing repository %s') % remote_repo.html_url)
0.431.32 by Jelmer Vernooij
Properly resolve git+ssh URLs.
187
        remote_dir = controldir.ControlDir.open(git_url_to_bzr_url(remote_repo.ssh_url))
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
188
        try:
7211.13.7 by Jelmer Vernooij
Fix formatting.
189
            push_result = remote_dir.push_branch(
190
                local_branch, revision_id=revision_id, overwrite=overwrite,
191
                name=name)
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
192
        except errors.NoRoundtrippingSupport:
193
            if not allow_lossy:
194
                raise
7211.13.7 by Jelmer Vernooij
Fix formatting.
195
            push_result = remote_dir.push_branch(
196
                local_branch, revision_id=revision_id,
0.431.51 by Jelmer Vernooij
Allow fallback to lossy by default.
197
                overwrite=overwrite, name=name, lossy=True)
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
198
        return push_result.target_branch, github_url_to_bzr_url(
7211.13.7 by Jelmer Vernooij
Fix formatting.
199
            remote_repo.html_url, name)
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
200
0.431.28 by Jelmer Vernooij
Implement Hoster.get_push_url.
201
    def get_push_url(self, branch):
202
        owner, project, branch_name = parse_github_url(branch)
203
        repo = self.gh.get_repo('%s/%s' % (owner, project))
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
204
        return github_url_to_bzr_url(repo.ssh_url, branch_name)
0.431.28 by Jelmer Vernooij
Implement Hoster.get_push_url.
205
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
206
    def get_derived_branch(self, base_branch, name, project=None, owner=None):
207
        import github
208
        base_owner, base_project, base_branch_name = parse_github_url(base_branch)
209
        base_repo = self.gh.get_repo('%s/%s' % (base_owner, base_project))
210
        if owner is None:
211
            owner = self.gh.get_user().login
212
        if project is None:
213
            project = base_repo.name
214
        try:
215
            remote_repo = self.gh.get_repo('%s/%s' % (owner, project))
0.433.3 by Jelmer Vernooij
Some python 3 compatibility.
216
            full_url = github_url_to_bzr_url(remote_repo.ssh_url, name)
0.431.33 by Jelmer Vernooij
Fix URLs from gitlab.
217
            return _mod_branch.Branch.open(full_url)
0.431.22 by Jelmer Vernooij
Add Hoster.get_derived_branch.
218
        except github.UnknownObjectException:
219
            raise errors.NotBranchError('https://github.com/%s/%s' % (owner, project))
220
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
221
    def get_proposer(self, source_branch, target_branch):
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
222
        return GitHubMergeProposalBuilder(self.gh, source_branch, target_branch)
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
223
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
224
    def iter_proposals(self, source_branch, target_branch, status='open'):
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
225
        (source_owner, source_repo_name, source_branch_name) = (
7211.13.7 by Jelmer Vernooij
Fix formatting.
226
            parse_github_url(source_branch))
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
227
        (target_owner, target_repo_name, target_branch_name) = (
7211.13.7 by Jelmer Vernooij
Fix formatting.
228
            parse_github_url(target_branch))
0.431.67 by Jelmer Vernooij
Support multiple merge proposals per branch.
229
        target_repo = self.gh.get_repo(
230
            "%s/%s" % (target_owner, target_repo_name))
0.431.68 by Jelmer Vernooij
Add status to other Hosters.
231
        state = {
232
            'open': 'open',
233
            'merged': 'closed',
234
            'closed': 'closed',
235
            'all': 'all'}
236
        for pull in target_repo.get_pulls(
237
                head=target_branch_name,
238
                state=state[status]):
239
            if (status == 'closed' and pull.merged or
240
                    status == 'merged' and not pull.merged):
241
                continue
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
242
            if pull.head.ref != source_branch_name:
243
                continue
244
            if (pull.head.repo.owner.login != source_owner or
7211.13.7 by Jelmer Vernooij
Fix formatting.
245
                    pull.head.repo.name != source_repo_name):
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
246
                continue
0.431.67 by Jelmer Vernooij
Support multiple merge proposals per branch.
247
            yield GitHubMergeProposal(pull)
0.431.35 by Jelmer Vernooij
Add Hoster.get_proposal.
248
0.433.1 by Jelmer Vernooij
Add Hoster.hosts.
249
    def hosts(self, branch):
250
        try:
251
            parse_github_url(branch)
252
        except NotGitHubUrl:
253
            return False
254
        else:
255
            return True
256
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
257
    @classmethod
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
258
    def probe(cls, branch):
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
259
        try:
260
            parse_github_url(branch)
261
        except NotGitHubUrl:
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
262
            raise UnsupportedHoster(branch)
263
        return cls()
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
264
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
265
    @classmethod
266
    def iter_instances(cls):
267
        yield cls()
268
0.431.66 by Jelmer Vernooij
Add support for status argument.
269
    def iter_my_proposals(self, status='open'):
270
        query = ['is:pr']
271
        if status == 'open':
272
            query.append('is:open')
273
        elif status == 'closed':
274
            # Note that we don't use is:closed here, since that also includes
275
            # merged pull requests.
276
            query.append('is:unmerged')
277
        elif status == 'merged':
278
            query.append('is:merged')
279
        query.append('author:%s' % self.gh.get_user().login)
280
        for issue in self.gh.search_issues(query=' '.join(query)):
0.431.64 by Jelmer Vernooij
Add get_source_branch_url/get_target_branch_url methods.
281
            yield GitHubMergeProposal(issue.as_pull_request())
0.431.63 by Jelmer Vernooij
Add 'brz my-proposals' command.
282
0.432.1 by Jelmer Vernooij
Initial work on hoster support.
283
0.432.2 by Jelmer Vernooij
Publish command sort of works.
284
class GitHubMergeProposalBuilder(MergeProposalBuilder):
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
285
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
286
    def __init__(self, gh, source_branch, target_branch):
287
        self.gh = gh
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
288
        self.source_branch = source_branch
289
        self.target_branch = target_branch
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
290
        (self.target_owner, self.target_repo_name, self.target_branch_name) = (
7211.13.7 by Jelmer Vernooij
Fix formatting.
291
            parse_github_url(self.target_branch))
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
292
        (self.source_owner, self.source_repo_name, self.source_branch_name) = (
7211.13.7 by Jelmer Vernooij
Fix formatting.
293
            parse_github_url(self.source_branch))
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
294
295
    def get_infotext(self):
296
        """Determine the initial comment for the merge proposal."""
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
297
        info = []
298
        info.append("Merge %s into %s:%s\n" % (
299
            self.source_branch_name, self.target_owner,
300
            self.target_branch_name))
301
        info.append("Source: %s\n" % self.source_branch.user_url)
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
302
        info.append("Target: %s\n" % self.target_branch.user_url)
303
        return ''.join(info)
304
305
    def get_initial_body(self):
306
        """Get a body for the proposal for the user to modify.
307
308
        :return: a str or None.
309
        """
310
        return None
311
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
312
    def create_proposal(self, description, reviewers=None, labels=None,
313
                        prerequisite_branch=None):
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
314
        """Perform the submission."""
0.431.56 by Jelmer Vernooij
Add support for prerequisite branches.
315
        if prerequisite_branch is not None:
316
            raise PrerequisiteBranchUnsupported(self)
0.432.10 by Jelmer Vernooij
More test fixes.
317
        import github
0.432.7 by Jelmer Vernooij
propose works \o/
318
        # TODO(jelmer): Probe for right repo name
0.432.12 by Jelmer Vernooij
Fix .git ends.
319
        if self.target_repo_name.endswith('.git'):
320
            self.target_repo_name = self.target_repo_name[:-4]
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
321
        target_repo = self.gh.get_repo("%s/%s" % (self.target_owner, self.target_repo_name))
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
322
        # TODO(jelmer): Allow setting title explicitly?
0.431.44 by Jelmer Vernooij
Support get/set description.
323
        title = determine_title(description)
0.431.4 by Jelmer Vernooij
Add basic GitHub support.
324
        # TOOD(jelmer): Set maintainers_can_modify?
0.432.10 by Jelmer Vernooij
More test fixes.
325
        try:
326
            pull_request = target_repo.create_pull(
327
                title=title, body=description,
328
                head="%s:%s" % (self.source_owner, self.source_branch_name),
329
                base=self.target_branch_name)
330
        except github.GithubException as e:
331
            if e.status == 422:
332
                raise MergeProposalExists(self.source_branch.user_url)
333
            raise
0.431.6 by Jelmer Vernooij
Initial gitlab support works.
334
        if reviewers:
335
            for reviewer in reviewers:
336
                pull_request.assignees.append(
0.432.9 by Jelmer Vernooij
Drop is_compatible nonesense.
337
                    self.gh.get_user(reviewer))
0.431.13 by Jelmer Vernooij
Add support for labels on merge proposals.
338
        if labels:
339
            for label in labels:
340
                pull_request.issue.labels.append(label)
0.431.44 by Jelmer Vernooij
Support get/set description.
341
        return GitHubMergeProposal(pull_request)