/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
1
# Copyright (C) 2007-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
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
0.358.1 by Jelmer Vernooij
Fix FSF address.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
16
0.358.3 by Jelmer Vernooij
Enable absolute import.
17
"""Remote dirs, repositories and branches."""
18
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
19
from __future__ import absolute_import
20
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
21
from ... import (
0.200.596 by Jelmer Vernooij
Import RemoteGitBranch._get_config().
22
    config,
0.200.707 by Jelmer Vernooij
Add debug routines.
23
    debug,
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
24
    trace,
0.200.333 by Jelmer Vernooij
Support progress reporting when creating index.
25
    ui,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
26
    urlutils,
27
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
28
from ...errors import (
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
29
    AlreadyBranchError,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
30
    BzrError,
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
31
    InProcessTransport,
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
32
    InvalidRevisionId,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
33
    NoSuchFile,
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
34
    NoSuchRevision,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
35
    NoSuchTag,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
36
    NotBranchError,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
37
    NotLocalUrl,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
38
    UninitializableFormat,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
39
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
40
from ...transport import (
0.200.292 by Jelmer Vernooij
Fix formatting.
41
    Transport,
42
    )
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
43
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
44
from . import (
0.200.292 by Jelmer Vernooij
Fix formatting.
45
    lazy_check_versions,
46
    )
0.200.200 by Jelmer Vernooij
Register lazily where possible.
47
lazy_check_versions()
48
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
49
from .branch import (
0.200.292 by Jelmer Vernooij
Fix formatting.
50
    GitBranch,
0.295.1 by Jelmer Vernooij
Split up branch formats.
51
    GitBranchFormat,
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
52
    GitTags,
0.200.292 by Jelmer Vernooij
Fix formatting.
53
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
54
from .dir import (
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
55
    GitControlDirFormat,
56
    GitDir,
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
57
    BareLocalGitControlDirFormat,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
58
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
59
from .errors import (
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
60
    GitSmartRemoteNotSupported,
0.200.292 by Jelmer Vernooij
Fix formatting.
61
    NoSuchRef,
62
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
63
from .mapping import (
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
64
    mapping_registry,
65
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
66
from .repository import (
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
67
    GitRepository,
68
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
69
from .refs import (
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
70
    branch_name_to_ref,
0.200.1487 by Jelmer Vernooij
Use peeling.
71
    is_peeled,
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
72
    ref_to_tag_name,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
73
    tag_name_to_ref,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
74
    )
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
75
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
76
import dulwich
77
import dulwich.client
0.200.292 by Jelmer Vernooij
Fix formatting.
78
from dulwich.errors import (
79
    GitProtocolError,
80
    )
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
81
from dulwich.pack import (
82
    Pack,
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
83
    pack_objects_to_data,
0.200.289 by Jelmer Vernooij
Cope with new member variables in RepositoryFormat.
84
    )
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
85
from dulwich.refs import SYMREF
0.200.1487 by Jelmer Vernooij
Use peeling.
86
from dulwich.repo import DictRefsContainer
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
87
import os
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
88
import select
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
89
import tempfile
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
90
import urllib
91
import urlparse
0.200.1555 by Jelmer Vernooij
Remove segment parameters for http smart transports.
92
93
# urlparse only supports a limited number of schemes by default
94
0.200.741 by Jelmer Vernooij
Cope with older versions of Python by adding git and git+ssh to the list of known schemes.
95
urlparse.uses_netloc.extend(['git', 'git+ssh'])
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
96
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
97
from dulwich.pack import load_pack_index
0.200.306 by Jelmer Vernooij
Fix tests, split up InterGitNonGitRepository.
98
0.200.143 by Jelmer Vernooij
Reoncile InterGitRepository objects.
99
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
100
# Don't run any tests on GitSmartTransport as it is not intended to be
0.200.181 by Jelmer Vernooij
Support setting tags.
101
# a full implementation of Transport
102
def get_test_permutations():
103
    return []
104
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
105
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
106
def split_git_url(url):
0.200.709 by Jelmer Vernooij
When unpacking URLs, strip leftmost slash to match gits behaviour.
107
    """Split a Git URL.
108
109
    :param url: Git URL
110
    :return: Tuple with host, port, username, path.
111
    """
0.200.743 by Jelmer Vernooij
Fix URL parsing.
112
    (scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
113
    path = urllib.unquote(loc)
0.246.2 by Jelmer Vernooij
Improve the fix dealing with git repo's in home directories.
114
    if path.startswith("/~"):
0.200.709 by Jelmer Vernooij
When unpacking URLs, strip leftmost slash to match gits behaviour.
115
        path = path[1:]
0.200.743 by Jelmer Vernooij
Fix URL parsing.
116
    (username, hostport) = urllib.splituser(netloc)
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
117
    (host, port) = urllib.splitnport(hostport, None)
118
    return (host, port, username, path)
119
120
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
121
class RemoteGitError(BzrError):
122
0.290.1 by Jelmer Vernooij
Avoid 'message' argument in RemoteGitError; apparently it breaks some versions of Python.
123
    _fmt = "Remote server error: %(msg)s"
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
124
125
0.200.1275 by Jelmer Vernooij
recognize missing repositories
126
def parse_git_error(url, message):
127
    """Parse a remote git server error and return a bzr exception.
128
129
    :param url: URL of the remote repository
130
    :param message: Message sent by the remote git server
131
    """
132
    message = str(message).strip()
133
    if message.startswith("Could not find Repository "):
134
        return NotBranchError(url, message)
0.200.1563 by Jelmer Vernooij
Improve error message.
135
    if message == "HEAD failed to update":
136
        base_url, _ = urlutils.split_segment_parameters(url)
137
        raise BzrError(
138
            ("Unable to update remote HEAD branch. To update the master "
139
             "branch, specify the URL %s,branch=master.") % base_url)
0.200.1275 by Jelmer Vernooij
recognize missing repositories
140
    # Don't know, just return it to the user as-is
0.200.1562 by Jelmer Vernooij
Add separate exception for remote errors.
141
    return RemoteGitError(message)
0.200.1275 by Jelmer Vernooij
recognize missing repositories
142
143
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
144
class GitSmartTransport(Transport):
145
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
146
    def __init__(self, url, _client=None):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
147
        Transport.__init__(self, url)
0.200.708 by Jelmer Vernooij
Factor out URL parsing.
148
        (self._host, self._port, self._username, self._path) = \
149
            split_git_url(url)
0.200.707 by Jelmer Vernooij
Add debug routines.
150
        if 'transport' in debug.debug_flags:
151
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
152
                         self._host, self._username, self._port, self._path)
0.200.166 by Jelmer Vernooij
don't reuse client objects.
153
        self._client = _client
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
154
        self._stripped_path = self._path.rsplit(",", 1)[0]
0.200.166 by Jelmer Vernooij
don't reuse client objects.
155
0.200.543 by Jelmer Vernooij
Implement GitSmartTransport.external_url().
156
    def external_url(self):
157
        return self.base
158
0.200.238 by Jelmer Vernooij
Import Transport.has().
159
    def has(self, relpath):
160
        return False
161
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
162
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
163
        raise NotImplementedError(self._get_client)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
164
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
165
    def _get_path(self):
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
166
        return self._stripped_path
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
167
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
168
    def get(self, path):
169
        raise NoSuchFile(path)
170
0.200.160 by Jelmer Vernooij
Implement abspath.
171
    def abspath(self, relpath):
172
        return urlutils.join(self.base, relpath)
173
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
174
    def clone(self, offset=None):
175
        """See Transport.clone()."""
176
        if offset is None:
177
            newurl = self.base
178
        else:
179
            newurl = urlutils.join(self.base, offset)
180
0.200.307 by Jelmer Vernooij
Support git+ssh.
181
        return self.__class__(newurl, self._client)
182
183
184
class TCPGitSmartTransport(GitSmartTransport):
185
0.200.332 by Jelmer Vernooij
Support activity reporting.
186
    _scheme = 'git'
187
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
188
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
189
        if self._client is not None:
190
            ret = self._client
191
            self._client = None
192
            return ret
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
193
        if self._host == '':
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
194
            # return dulwich.client.LocalGitClient()
195
            return dulwich.client.SubprocessGitClient()
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
196
        return dulwich.client.TCPGitClient(self._host, self._port,
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
197
            report_activity=self._report_activity)
0.200.307 by Jelmer Vernooij
Support git+ssh.
198
199
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
200
class SSHSocketWrapper(object):
201
202
    def __init__(self, sock):
203
        self.sock = sock
204
205
    def read(self, len=None):
206
        return self.sock.recv(len)
207
208
    def write(self, data):
209
        return self.sock.write(data)
210
211
    def can_read(self):
212
        return len(select.select([self.sock.fileno()], [], [], 0)[0]) > 0
213
214
215
class DulwichSSHVendor(dulwich.client.SSHVendor):
216
217
    def __init__(self):
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
218
        from ...transport import ssh
0.200.1624 by Jelmer Vernooij
Add ssh vendor for dulwich that uses the bzr ssh vendor.
219
        self.bzr_ssh_vendor = ssh._get_ssh_vendor()
220
221
    def run_command(self, host, command, username=None, port=None):
222
        connection = self.bzr_ssh_vendor.connect_ssh(username=username,
223
            password=None, port=port, host=host, command=command)
224
        (kind, io_object) = connection.get_sock_or_pipes()
225
        if kind == 'socket':
226
            return SSHSocketWrapper(io_object)
227
        else:
228
            raise AssertionError("Unknown io object kind %r'" % kind)
229
230
231
#dulwich.client.get_ssh_vendor = DulwichSSHVendor
232
233
0.200.307 by Jelmer Vernooij
Support git+ssh.
234
class SSHGitSmartTransport(GitSmartTransport):
235
0.200.332 by Jelmer Vernooij
Support activity reporting.
236
    _scheme = 'git+ssh'
237
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
238
    def _get_path(self):
0.200.1464 by Jelmer Vernooij
Warn about ignoring path segment parameters when using bzr 2.4.
239
        path = self._stripped_path
0.200.1318 by Jelmer Vernooij
Strip segment parameters where necessary.
240
        if path.startswith("/~/"):
241
            return path[3:]
242
        return path
0.200.470 by Jelmer Vernooij
Properly parse username in URLs.
243
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
244
    def _get_client(self):
0.200.307 by Jelmer Vernooij
Support git+ssh.
245
        if self._client is not None:
246
            ret = self._client
247
            self._client = None
248
            return ret
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
249
        location_config = config.LocationConfig(self.base)
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
250
        client = dulwich.client.SSHGitClient(self._host, self._port, self._username,
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
251
            report_activity=self._report_activity)
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
252
        # Set up alternate pack program paths
253
        upload_pack = location_config.get_user_option('git_upload_pack')
254
        if upload_pack:
0.200.949 by Jelmer Vernooij
merge support for specifying alternative paths for git executables.
255
            client.alternative_paths["upload-pack"] = upload_pack
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
256
        receive_pack = location_config.get_user_option('git_receive_pack')
257
        if receive_pack:
0.200.949 by Jelmer Vernooij
merge support for specifying alternative paths for git executables.
258
            client.alternative_paths["receive-pack"] = receive_pack
0.253.1 by Ross Light
Added configuration options for git-upload-pack and git-receive-pack
259
        return client
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
260
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
261
0.295.1 by Jelmer Vernooij
Split up branch formats.
262
class RemoteGitBranchFormat(GitBranchFormat):
263
264
    def get_format_description(self):
265
        return 'Remote Git Branch'
266
267
    @property
268
    def _matchingcontroldir(self):
269
        return RemoteGitControlDirFormat()
270
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
271
    def initialize(self, a_controldir, name=None, repository=None,
272
                   append_revisions_only=None):
273
        raise UninitializableFormat(self)
274
0.295.1 by Jelmer Vernooij
Split up branch formats.
275
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
276
def default_report_progress(text):
277
    if text.startswith('error: '):
278
        trace.show_error('git: %s', text[len('error: '):])
279
    else:
280
        trace.mutter("git: %s" % text)
281
282
0.200.148 by Jelmer Vernooij
Share more infrastructure between LocalGitDir and RemoteGitDir.
283
class RemoteGitDir(GitDir):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
284
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
285
    def __init__(self, transport, format, client, client_path):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
286
        self._format = format
287
        self.root_transport = transport
288
        self.transport = transport
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
289
        self._mode_check_done = None
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
290
        self._client = client
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
291
        self._client_path = client_path
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
292
        self.base = self.root_transport.base
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
293
        self._refs = None
0.200.1335 by Jelmer Vernooij
Move _get_client.
294
0.322.1 by Jelmer Vernooij
Fix access of remote git branches.
295
    @property
296
    def _gitrepository_class(self):
297
        return RemoteGitRepository
298
0.200.1335 by Jelmer Vernooij
Move _get_client.
299
    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
300
        if progress is None:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
301
            progress = default_report_progress
0.200.1335 by Jelmer Vernooij
Move _get_client.
302
        try:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
303
            result = self._client.fetch_pack(self._client_path, determine_wants,
0.200.1335 by Jelmer Vernooij
Move _get_client.
304
                graph_walker, pack_data, progress)
0.376.1 by Jelmer Vernooij
Add tests for remote operations.
305
            if result.refs is None:
306
                result.refs = {}
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
307
            self._refs = remote_refs_dict_to_container(result.refs, result.symrefs)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
308
            return result
0.200.1335 by Jelmer Vernooij
Move _get_client.
309
        except GitProtocolError, e:
310
            raise parse_git_error(self.transport.external_url(), e)
311
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
312
    def send_pack(self, get_changed_refs, generate_pack_data, progress=None):
313
        if progress is None:
314
            progress = default_report_progress
315
0.200.1335 by Jelmer Vernooij
Move _get_client.
316
        try:
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
317
            return self._client.send_pack(self._client_path, get_changed_refs,
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
318
                generate_pack_data, progress)
0.200.1335 by Jelmer Vernooij
Move _get_client.
319
        except GitProtocolError, e:
320
            raise parse_git_error(self.transport.external_url(), e)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
321
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
322
    def create_branch(self, name=None, repository=None,
323
                      append_revisions_only=None, ref=None):
324
        refname = self._get_selected_ref(name, ref)
325
        if refname != b'HEAD' and refname in self.get_refs_container():
326
            raise AlreadyBranchError(self.user_url)
327
        if refname in self.get_refs_container():
328
            ref_chain, unused_sha = self.get_refs_container().follow(self._get_selected_ref(None))
329
            if ref_chain[0] == b'HEAD':
330
                refname = ref_chain[1]
331
        repo = self.open_repository()
332
        return RemoteGitBranch(self, repo, refname)
333
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
334
    def destroy_branch(self, name=None):
335
        refname = self._get_selected_ref(name)
336
        def get_changed_refs(old_refs):
337
            ret = dict(old_refs)
338
            if not refname in ret:
0.200.1395 by Jelmer Vernooij
Fix error reporting.
339
                raise NotBranchError(self.user_url)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
340
            ret[refname] = dulwich.client.ZERO_SHA
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
341
            return ret
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
342
        def generate_pack_data(have, want, ofs_delta=False):
343
            return pack_objects_to_data([])
344
        self.send_pack(get_changed_refs, generate_pack_data)
0.200.1393 by Jelmer Vernooij
Implement removal of remote branches.
345
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
346
    @property
347
    def user_url(self):
348
        return self.control_url
349
0.200.1314 by Jelmer Vernooij
Provide RemoteGitDir.user_transport.
350
    @property
351
    def user_transport(self):
352
        return self.root_transport
353
0.200.1395 by Jelmer Vernooij
Fix error reporting.
354
    @property
355
    def control_url(self):
356
        return self.control_transport.base
357
358
    @property
359
    def control_transport(self):
360
        return self.root_transport
361
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
362
    def open_repository(self):
0.200.1415 by Jelmer Vernooij
Fix lock files for remote directories.
363
        return RemoteGitRepository(self)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
364
0.200.1310 by Jelmer Vernooij
Add _get_selected_ref method.
365
    def open_branch(self, name=None, unsupported=False,
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
366
            ignore_fallbacks=False, ref=None, possible_transports=None,
367
            nascent_ok=False):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
368
        repo = self.open_repository()
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
369
        ref = self._get_selected_ref(name, ref)
370
        if not nascent_ok and ref not in self.get_refs_container():
371
            raise NotBranchError(self.root_transport.base,
372
                    controldir=self)
373
        ref_chain, unused_sha = self.get_refs_container().follow(ref)
374
        return RemoteGitBranch(self, repo, ref_chain[-1])
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
375
0.200.662 by Jelmer Vernooij
Deal with recommend_upgrade argument to open_workingtree.
376
    def open_workingtree(self, recommend_upgrade=False):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
377
        raise NotLocalUrl(self.transport.base)
378
0.310.4 by Jelmer Vernooij
Implement RemoteControlDir.has_workingtree.
379
    def has_workingtree(self):
380
        return False
381
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
382
    def get_peeled(self, name):
383
        return self.get_refs_container().get_peeled(name)
384
0.200.1487 by Jelmer Vernooij
Use peeling.
385
    def get_refs_container(self):
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
386
        if self._refs is not None:
387
            return self._refs
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
388
        result = self.fetch_pack(lambda x: None, None,
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
389
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
390
        self._refs = remote_refs_dict_to_container(
391
                result.refs, result.symrefs)
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
392
        return self._refs
393
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
394
0.225.2 by Jelmer Vernooij
Handle situation when repository is already up to date during pull.
395
class EmptyObjectStoreIterator(dict):
396
397
    def iterobjects(self):
398
        return []
399
400
0.200.218 by Jelmer Vernooij
Simplify TemporaryPack implementation.
401
class TemporaryPackIterator(Pack):
402
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
403
    def __init__(self, path, resolve_ext_ref):
0.279.1 by William Grant
Support thin packs in fetch_pack and send_pack, since dulwich now handles them properly.
404
        super(TemporaryPackIterator, self).__init__(
405
            path, resolve_ext_ref=resolve_ext_ref)
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
406
        self._idx_load = lambda: self._idx_load_or_generate(self._idx_path)
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
407
0.278.2 by William Grant
Also override _idx_load rather than index, to be a bit cleaner.
408
    def _idx_load_or_generate(self, path):
409
        if not os.path.exists(path):
410
            pb = ui.ui_factory.nested_progress_bar()
411
            try:
412
                def report_progress(cur, total):
413
                    pb.update("generating index", cur, total)
414
                self.data.create_index(path,
415
                    progress=report_progress)
416
            finally:
417
                pb.finished()
418
        return load_pack_index(path)
0.200.205 by Jelmer Vernooij
Fix remote fetching.
419
420
    def __del__(self):
0.200.611 by Jelmer Vernooij
Merge warning fix from Naoki.
421
        if self._idx is not None:
0.241.1 by Naoki INADA
Fix can't delete tempfile on Windows
422
            self._idx.close()
423
            os.remove(self._idx_path)
0.200.611 by Jelmer Vernooij
Merge warning fix from Naoki.
424
        if self._data is not None:
0.241.1 by Naoki INADA
Fix can't delete tempfile on Windows
425
            self._data.close()
426
            os.remove(self._data_path)
0.200.205 by Jelmer Vernooij
Fix remote fetching.
427
428
0.200.1337 by Jelmer Vernooij
Re-use http connection if possible.
429
class BzrGitHttpClient(dulwich.client.HttpGitClient):
430
431
    def __init__(self, transport, *args, **kwargs):
432
        self.transport = transport
433
        super(BzrGitHttpClient, self).__init__(transport.external_url(), *args, **kwargs)
434
        import urllib2
435
        self._http_perform = getattr(self.transport, "_perform", urllib2.urlopen)
436
437
    def _perform(self, req):
438
        req.accepted_errors = (200, 404)
439
        req.follow_redirections = True
440
        req.redirected_to = None
441
        return self._http_perform(req)
442
443
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
444
class RemoteGitControlDirFormat(GitControlDirFormat):
445
    """The .git directory control format."""
446
447
    supports_workingtrees = False
448
449
    @classmethod
450
    def _known_formats(self):
451
        return set([RemoteGitControlDirFormat()])
452
0.295.1 by Jelmer Vernooij
Split up branch formats.
453
    def get_branch_format(self):
454
        return RemoteGitBranchFormat()
455
0.200.1413 by Jelmer Vernooij
Fix is_initializable()
456
    def is_initializable(self):
457
        return False
458
459
    def is_supported(self):
460
        return True
461
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
462
    def open(self, transport, _found=None):
463
        """Open this directory.
464
465
        """
466
        # we dont grok readonly - git isn't integrated with transport.
467
        url = transport.base
468
        if url.startswith('readonly+'):
469
            url = url[len('readonly+'):]
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
470
        scheme = urlparse.urlsplit(transport.external_url())[0]
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
471
        if isinstance(transport, GitSmartTransport):
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
472
            client = transport._get_client()
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
473
            client_path = transport._get_path()
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
474
        elif scheme in ("http", "https"):
475
            client = BzrGitHttpClient(transport)
0.200.1555 by Jelmer Vernooij
Remove segment parameters for http smart transports.
476
            client_path, _ = urlutils.split_segment_parameters(transport._path)
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
477
        elif scheme == 'file':
478
            client = dulwich.client.LocalGitClient()
479
            client_path = transport.local_abspath('.')
0.200.1336 by Jelmer Vernooij
Support the git smart server http protocol.
480
        else:
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
481
            raise NotBranchError(transport.base)
0.344.1 by Jelmer Vernooij
Allow using local git executable by accessing git:///some/path.
482
        if not _found:
483
            pass # TODO(jelmer): Actually probe for something
484
        return RemoteGitDir(transport, self, client, client_path)
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
485
486
    def get_format_description(self):
487
        return "Remote Git Repository"
488
489
    def initialize_on_transport(self, transport):
490
        raise UninitializableFormat(self)
491
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
492
    def supports_transport(self, transport):
493
        try:
494
            external_url = transport.external_url()
495
        except InProcessTransport:
496
            raise NotBranchError(path=transport.base)
497
        return (external_url.startswith("http:") or
498
                external_url.startswith("https:") or
499
                external_url.startswith("git+") or
500
                external_url.startswith("git:"))
501
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
502
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
503
class RemoteGitRepository(GitRepository):
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
504
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
505
    @property
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
506
    def user_url(self):
507
        return self.control_url
508
0.200.1288 by Jelmer Vernooij
Properly raise GitRemoteNotSupported from RemoteGitRepository.
509
    def get_parent_map(self, revids):
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
510
        raise GitSmartRemoteNotSupported(self.get_parent_map, self)
0.200.319 by Jelmer Vernooij
Print proper error when trying unsupported operations against a git server.
511
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
512
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
0.200.155 by Jelmer Vernooij
Fix formatting, remove catch-all for exceptions when opening local repositories.
513
                   progress=None):
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
514
        return self.controldir.fetch_pack(determine_wants, graph_walker,
0.200.456 by Jelmer Vernooij
Fix git -> git fetching.
515
                                          pack_data, progress)
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
516
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
517
    def send_pack(self, get_changed_refs, generate_pack_data):
518
        return self.controldir.send_pack(get_changed_refs, generate_pack_data)
0.200.427 by Jelmer Vernooij
make send_pack accessible.
519
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
520
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
521
                      progress=None):
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
522
        fd, path = tempfile.mkstemp(suffix=".pack")
0.200.1299 by Jelmer Vernooij
Make sure file gets closed.
523
        try:
524
            self.fetch_pack(determine_wants, graph_walker,
525
                lambda x: os.write(fd, x), progress)
526
        finally:
527
            os.close(fd)
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
528
        if os.path.getsize(path) == 0:
0.225.2 by Jelmer Vernooij
Handle situation when repository is already up to date during pull.
529
            return EmptyObjectStoreIterator()
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
530
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
0.200.167 by Jelmer Vernooij
Implement fetch_objects properly.
531
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
532
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
0.200.415 by Jelmer Vernooij
make 'bzr pull --revision' work for remote repositories.
533
        # This won't work for any round-tripped bzr revisions, but it's a start..
534
        try:
535
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
536
        except InvalidRevisionId:
537
            raise NoSuchRevision(self, bzr_revid)
538
0.252.48 by Jelmer Vernooij
Implement lookup_foreign_revision for remote branches.
539
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
540
        """Lookup a revision id.
541
542
        """
543
        if mapping is None:
544
            mapping = self.get_mapping()
545
        # Not really an easy way to parse foreign revids here..
546
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
547
0.200.1446 by Jelmer Vernooij
Add stub for RemoteGitRepository.revision_tree.
548
    def revision_tree(self, revid):
549
        raise GitSmartRemoteNotSupported(self.revision_tree, self)
550
0.200.1481 by Jelmer Vernooij
'Implement' RemoteGitRepository.get_revisions.
551
    def get_revisions(self, revids):
552
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
553
0.200.1557 by Jelmer Vernooij
Implement RemoteGitRepository.has_revisions.
554
    def has_revisions(self, revids):
555
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
556
0.200.138 by Jelmer Vernooij
Add initial infrastructure for accessing remote git repositories.
557
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
558
class RemoteGitTagDict(GitTags):
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
559
560
    def set_tag(self, name, revid):
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
561
        sha = self.branch.lookup_bzr_revision_id(revid)[0]
562
        self._set_ref(name, sha)
563
564
    def delete_tag(self, name):
565
        self._set_ref(name, dulwich.client.ZERO_SHA)
566
567
    def _set_ref(self, name, sha):
568
        ref = tag_name_to_ref(name)
569
        def get_changed_refs(old_refs):
570
            ret = dict(old_refs)
571
            if sha == dulwich.client.ZERO_SHA and ref not in ret:
572
                raise NoSuchTag(name)
573
            ret[ref] = sha
574
            return ret
575
        def generate_pack_data(have, want, ofs_delta=False):
576
            return pack_objects_to_data([])
577
        self.repository.send_pack(get_changed_refs, generate_pack_data)
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
578
579
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
580
class RemoteGitBranch(GitBranch):
581
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
582
    def __init__(self, controldir, repository, name):
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
583
        self._sha = None
0.295.1 by Jelmer Vernooij
Split up branch formats.
584
        super(RemoteGitBranch, self).__init__(controldir, repository, name,
585
                RemoteGitBranchFormat())
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
586
0.200.1317 by Jelmer Vernooij
Avoid NotImplementedError.
587
    def last_revision_info(self):
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
588
        raise GitSmartRemoteNotSupported(self.last_revision_info, self)
0.200.1317 by Jelmer Vernooij
Avoid NotImplementedError.
589
0.200.1068 by Jelmer Vernooij
Implement user_url/control_url.
590
    @property
591
    def user_url(self):
592
        return self.control_url
593
594
    @property
595
    def control_url(self):
596
        return self.base
597
0.200.1436 by Jelmer Vernooij
Raise UnsupportedOperation for `Branch.revision_id_to_dotted_revno`,
598
    def revision_id_to_revno(self, revision_id):
599
        raise GitSmartRemoteNotSupported(self.revision_id_to_revno, self)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
600
601
    def last_revision(self):
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
602
        return self.lookup_foreign_revision_id(self.head)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
603
604
    @property
605
    def head(self):
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
606
        if self._sha is not None:
607
            return self._sha
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
608
        refs = self.controldir.get_refs_container()
0.200.1561 by Jelmer Vernooij
Some fixes for colocated branch handling.
609
        name = branch_name_to_ref(self.name)
0.200.1386 by Jelmer Vernooij
Friendlier message if HEAD is not found.
610
        try:
611
            self._sha = refs[name]
612
        except KeyError:
613
            raise NoSuchRef(name, self.repository.user_url, refs)
0.200.919 by Jelmer Vernooij
Simplify ref handling in remote.py.
614
        return self._sha
0.200.141 by Jelmer Vernooij
Separate out local and remote fetching.
615
0.200.169 by Jelmer Vernooij
Fix branch cloning.
616
    def _synchronize_history(self, destination, revision_id):
617
        """See Branch._synchronize_history()."""
618
        destination.generate_revision_history(self.last_revision())
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
619
0.289.1 by Jelmer Vernooij
No parent location for remote repos.
620
    def _get_parent_location(self):
621
        return None
622
0.200.499 by Jelmer Vernooij
Implement RemoteBranch.{get,set}_push_location.
623
    def get_push_location(self):
624
        return None
625
626
    def set_push_location(self, url):
627
        pass
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
628
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
629
    def _iter_tag_refs(self):
630
        """Iterate over the tag refs.
631
632
        :param refs: Refs dictionary (name -> git sha1)
633
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
634
        """
635
        refs = self.controldir.get_refs_container()
636
        for ref_name, unpeeled in refs.as_dict().iteritems():
637
            try:
638
                tag_name = ref_to_tag_name(ref_name)
639
            except (ValueError, UnicodeDecodeError):
640
                continue
641
            peeled = refs.get_peeled(ref_name)
642
            if peeled is None:
643
                try:
644
                    peeled = refs.peel_sha(unpeeled).id
645
                except KeyError:
646
                    # Let's just hope it's a commit
647
                    peeled = unpeeled
648
            if type(tag_name) is not unicode:
649
                raise TypeError(tag_name)
650
            yield (ref_name, tag_name, peeled, unpeeled)
651
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
652
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
653
def remote_refs_dict_to_container(refs_dict, symrefs_dict={}):
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
654
    base = {}
655
    peeled = {}
656
    for k, v in refs_dict.iteritems():
657
        if is_peeled(k):
658
            peeled[k[:-3]] = v
659
        else:
660
            base[k] = v
661
            peeled[k] = v
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
662
    for name, target in symrefs_dict.iteritems():
663
        base[name] = SYMREF + target
0.200.1488 by Jelmer Vernooij
Factor out remote_refs_dict_to_container.
664
    ret = DictRefsContainer(base)
665
    ret._peeled = peeled
666
    return ret