/brz/remove-bazaar

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