/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to remote.py

Fix two mistakes in 'bzr help git'.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007-2010 Jelmer Vernooij <jelmer@samba.org>
 
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
 
 
17
from bzrlib import (
 
18
    config,
 
19
    debug,
 
20
    trace,
 
21
    ui,
 
22
    urlutils,
 
23
    )
 
24
from bzrlib.errors import (
 
25
    BzrError,
 
26
    InvalidRevisionId,
 
27
    NoSuchFile,
 
28
    NoSuchRevision,
 
29
    NotBranchError,
 
30
    NotLocalUrl,
 
31
    UninitializableFormat,
 
32
    )
 
33
from bzrlib.transport import (
 
34
    Transport,
 
35
    )
 
36
 
 
37
from bzrlib.plugins.git import (
 
38
    lazy_check_versions,
 
39
    )
 
40
lazy_check_versions()
 
41
 
 
42
from bzrlib.plugins.git.branch import (
 
43
    GitBranch,
 
44
    GitTags,
 
45
    )
 
46
from bzrlib.plugins.git.dir import (
 
47
    GitControlDirFormat,
 
48
    GitDir,
 
49
    GitLockableFiles,
 
50
    GitLock,
 
51
    )
 
52
from bzrlib.plugins.git.errors import (
 
53
    GitSmartRemoteNotSupported,
 
54
    NoSuchRef,
 
55
    )
 
56
from bzrlib.plugins.git.mapping import (
 
57
    mapping_registry,
 
58
    )
 
59
from bzrlib.plugins.git.repository import (
 
60
    GitRepository,
 
61
    )
 
62
from bzrlib.plugins.git.refs import (
 
63
    extract_tags,
 
64
    branch_name_to_ref,
 
65
    )
 
66
 
 
67
import dulwich.client
 
68
from dulwich.errors import (
 
69
    GitProtocolError,
 
70
    )
 
71
from dulwich.pack import (
 
72
    Pack,
 
73
    ThinPackData,
 
74
    )
 
75
from dulwich.protocol import Protocol
 
76
import os
 
77
import tempfile
 
78
import urllib
 
79
import urlparse
 
80
urlparse.uses_netloc.extend(['git', 'git+ssh'])
 
81
 
 
82
from dulwich.pack import load_pack_index
 
83
 
 
84
 
 
85
# Don't run any tests on GitSmartTransport as it is not intended to be
 
86
# a full implementation of Transport
 
87
def get_test_permutations():
 
88
    return []
 
89
 
 
90
 
 
91
def split_git_url(url):
 
92
    """Split a Git URL.
 
93
 
 
94
    :param url: Git URL
 
95
    :return: Tuple with host, port, username, path.
 
96
    """
 
97
    (scheme, netloc, loc, _, _) = urlparse.urlsplit(url)
 
98
    path = urllib.unquote(loc)
 
99
    if path.startswith("/~"):
 
100
        path = path[1:]
 
101
    (username, hostport) = urllib.splituser(netloc)
 
102
    (host, port) = urllib.splitnport(hostport, None)
 
103
    return (host, port, username, path)
 
104
 
 
105
 
 
106
class GitSmartTransport(Transport):
 
107
 
 
108
    def __init__(self, url, _client=None):
 
109
        Transport.__init__(self, url)
 
110
        (self._host, self._port, self._username, self._path) = \
 
111
            split_git_url(url)
 
112
        if 'transport' in debug.debug_flags:
 
113
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
 
114
                         self._host, self._username, self._port, self._path)
 
115
        self._client = _client
 
116
 
 
117
    def external_url(self):
 
118
        return self.base
 
119
 
 
120
    def has(self, relpath):
 
121
        return False
 
122
 
 
123
    def _get_client(self, thin_packs):
 
124
        raise NotImplementedError(self._get_client)
 
125
 
 
126
    def _get_path(self):
 
127
        return self._path
 
128
 
 
129
    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
 
130
        if progress is None:
 
131
            def progress(text):
 
132
                trace.info("git: %s" % text)
 
133
        client = self._get_client(thin_packs=False)
 
134
        try:
 
135
            return client.fetch_pack(self._get_path(), determine_wants,
 
136
                graph_walker, pack_data, progress)
 
137
        except GitProtocolError, e:
 
138
            raise BzrError(e)
 
139
 
 
140
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
141
        client = self._get_client(thin_packs=False)
 
142
        try:
 
143
            return client.send_pack(self._get_path(), get_changed_refs,
 
144
                generate_pack_contents)
 
145
        except GitProtocolError, e:
 
146
            raise BzrError(e)
 
147
 
 
148
    def get(self, path):
 
149
        raise NoSuchFile(path)
 
150
 
 
151
    def abspath(self, relpath):
 
152
        return urlutils.join(self.base, relpath)
 
153
 
 
154
    def clone(self, offset=None):
 
155
        """See Transport.clone()."""
 
156
        if offset is None:
 
157
            newurl = self.base
 
158
        else:
 
159
            newurl = urlutils.join(self.base, offset)
 
160
 
 
161
        return self.__class__(newurl, self._client)
 
162
 
 
163
 
 
164
class TCPGitSmartTransport(GitSmartTransport):
 
165
 
 
166
    _scheme = 'git'
 
167
 
 
168
    def _get_client(self, thin_packs):
 
169
        if self._client is not None:
 
170
            ret = self._client
 
171
            self._client = None
 
172
            return ret
 
173
        return dulwich.client.TCPGitClient(self._host, self._port,
 
174
            thin_packs=thin_packs, report_activity=self._report_activity)
 
175
 
 
176
 
 
177
class BzrGitSSHGitClient(dulwich.client.SSHGitClient):
 
178
 
 
179
    def __init__(self, *args, **kwargs):
 
180
        super(BzrGitSSHGitClient, self).__init__(*args, **kwargs)
 
181
        self._read_buffer = ""
 
182
 
 
183
    def _can_read(self):
 
184
        if self._read_buffer != "":
 
185
            return True
 
186
        self._read_buffer = self._read(1)
 
187
        return (self._read_buffer != "")
 
188
 
 
189
    def _read(self, count):
 
190
        ret = self._read_buffer[:count]
 
191
        self._read_buffer = self._read_buffer[len(ret):]
 
192
        while len(ret) < count:
 
193
            if self._io_kind == "socket":
 
194
                ret += self._io_object.recv(count - len(ret))
 
195
            else:
 
196
                ret += self._io_object[0].read(count - len(ret))
 
197
        return ret
 
198
 
 
199
    def _write(self, data):
 
200
        if self._io_kind == "socket":
 
201
            self._io_object.send(data)
 
202
        else:
 
203
            self._io_object[1].write(data)
 
204
 
 
205
    def _connect(self, cmd, path):
 
206
        from bzrlib.transport import ssh as _mod_ssh
 
207
        vendor = _mod_ssh._get_ssh_vendor()
 
208
        self._ssh_connection = vendor.connect_ssh(self.username, None,
 
209
            self.host, self.port, command=[self._get_cmd_path(cmd), path])
 
210
        self._io_kind, self._io_object = self._ssh_connection.get_sock_or_pipes()
 
211
        if self._io_kind not in ("socket", "pipes"):
 
212
            raise AssertionError(
 
213
                "Unexpected io_kind %r from %r"
 
214
                % (self._io_kind, self._ssh_connection))
 
215
        return (Protocol(self._read, self._write,
 
216
            report_activity=self._report_activity), self._can_read)
 
217
 
 
218
 
 
219
class SSHGitSmartTransport(GitSmartTransport):
 
220
 
 
221
    _scheme = 'git+ssh'
 
222
 
 
223
    def _get_path(self):
 
224
        if self._path.startswith("/~/"):
 
225
            return self._path[3:]
 
226
        return self._path
 
227
 
 
228
    def _get_client(self, thin_packs):
 
229
        if self._client is not None:
 
230
            ret = self._client
 
231
            self._client = None
 
232
            return ret
 
233
        location_config = config.LocationConfig(self.base)
 
234
        client = BzrGitSSHGitClient(self._host, self._port, self._username,
 
235
            thin_packs=thin_packs, report_activity=self._report_activity)
 
236
        # Set up alternate pack program paths
 
237
        upload_pack = location_config.get_user_option('git_upload_pack')
 
238
        if upload_pack:
 
239
            client.alternative_paths["upload-pack"] = upload_pack
 
240
        receive_pack = location_config.get_user_option('git_receive_pack')
 
241
        if receive_pack:
 
242
            client.alternative_paths["receive-pack"] = receive_pack
 
243
        return client
 
244
 
 
245
 
 
246
class RemoteGitDir(GitDir):
 
247
 
 
248
    def __init__(self, transport, lockfiles, format):
 
249
        self._format = format
 
250
        self.root_transport = transport
 
251
        self.transport = transport
 
252
        self._lockfiles = lockfiles
 
253
        self._mode_check_done = None
 
254
 
 
255
    @property
 
256
    def user_url(self):
 
257
        return self.control_url
 
258
 
 
259
    def _branch_name_to_ref(self, name, default=None):
 
260
        return branch_name_to_ref(name, default=default)
 
261
 
 
262
    def open_repository(self):
 
263
        return RemoteGitRepository(self, self._lockfiles)
 
264
 
 
265
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=False):
 
266
        repo = self.open_repository()
 
267
        refname = self._branch_name_to_ref(name)
 
268
        return RemoteGitBranch(self, repo, refname, self._lockfiles)
 
269
 
 
270
    def open_workingtree(self, recommend_upgrade=False):
 
271
        raise NotLocalUrl(self.transport.base)
 
272
 
 
273
 
 
274
class EmptyObjectStoreIterator(dict):
 
275
 
 
276
    def iterobjects(self):
 
277
        return []
 
278
 
 
279
 
 
280
class TemporaryPackIterator(Pack):
 
281
 
 
282
    def __init__(self, path, resolve_ext_ref):
 
283
        super(TemporaryPackIterator, self).__init__(path)
 
284
        self.resolve_ext_ref = resolve_ext_ref
 
285
 
 
286
    @property
 
287
    def data(self):
 
288
        if self._data is None:
 
289
            self._data = ThinPackData(self.resolve_ext_ref, self._data_path)
 
290
        return self._data
 
291
 
 
292
    @property
 
293
    def index(self):
 
294
        if self._idx is None:
 
295
            if not os.path.exists(self._idx_path):
 
296
                pb = ui.ui_factory.nested_progress_bar()
 
297
                try:
 
298
                    def report_progress(cur, total):
 
299
                        pb.update("generating index", cur, total)
 
300
                    self.data.create_index(self._idx_path, 
 
301
                        progress=report_progress)
 
302
                finally:
 
303
                    pb.finished()
 
304
            self._idx = load_pack_index(self._idx_path)
 
305
        return self._idx
 
306
 
 
307
    def __del__(self):
 
308
        if self._idx is not None:
 
309
            self._idx.close()
 
310
            os.remove(self._idx_path)
 
311
        if self._data is not None:
 
312
            self._data.close()
 
313
            os.remove(self._data_path)
 
314
 
 
315
 
 
316
class RemoteGitControlDirFormat(GitControlDirFormat):
 
317
    """The .git directory control format."""
 
318
 
 
319
    supports_workingtrees = False
 
320
 
 
321
    @classmethod
 
322
    def _known_formats(self):
 
323
        return set([RemoteGitControlDirFormat()])
 
324
 
 
325
    def open(self, transport, _found=None):
 
326
        """Open this directory.
 
327
 
 
328
        """
 
329
        # we dont grok readonly - git isn't integrated with transport.
 
330
        url = transport.base
 
331
        if url.startswith('readonly+'):
 
332
            url = url[len('readonly+'):]
 
333
        if (not url.startswith("git://") and not url.startswith("git+")):
 
334
            raise NotBranchError(transport.base)
 
335
        if not isinstance(transport, GitSmartTransport):
 
336
            raise NotBranchError(transport.base)
 
337
        lockfiles = GitLockableFiles(transport, GitLock())
 
338
        return RemoteGitDir(transport, lockfiles, self)
 
339
 
 
340
    def get_format_description(self):
 
341
        return "Remote Git Repository"
 
342
 
 
343
    def initialize_on_transport(self, transport):
 
344
        raise UninitializableFormat(self)
 
345
 
 
346
 
 
347
class RemoteGitRepository(GitRepository):
 
348
 
 
349
    def __init__(self, gitdir, lockfiles):
 
350
        GitRepository.__init__(self, gitdir, lockfiles)
 
351
        self._refs = None
 
352
 
 
353
    @property
 
354
    def user_url(self):
 
355
        return self.control_url
 
356
 
 
357
    @property
 
358
    def inventories(self):
 
359
        raise GitSmartRemoteNotSupported()
 
360
 
 
361
    @property
 
362
    def revisions(self):
 
363
        raise GitSmartRemoteNotSupported()
 
364
 
 
365
    @property
 
366
    def texts(self):
 
367
        raise GitSmartRemoteNotSupported()
 
368
 
 
369
    def get_refs(self):
 
370
        if self._refs is not None:
 
371
            return self._refs
 
372
        self._refs = self.bzrdir.root_transport.fetch_pack(lambda x: [], None,
 
373
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
 
374
        return self._refs
 
375
 
 
376
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
 
377
                   progress=None):
 
378
        return self._transport.fetch_pack(determine_wants, graph_walker,
 
379
                                          pack_data, progress)
 
380
 
 
381
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
382
        return self._transport.send_pack(get_changed_refs, generate_pack_contents)
 
383
 
 
384
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
385
                      progress=None):
 
386
        fd, path = tempfile.mkstemp(suffix=".pack")
 
387
        self.fetch_pack(determine_wants, graph_walker,
 
388
            lambda x: os.write(fd, x), progress)
 
389
        os.close(fd)
 
390
        if os.path.getsize(path) == 0:
 
391
            return EmptyObjectStoreIterator()
 
392
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
 
393
 
 
394
    def lookup_bzr_revision_id(self, bzr_revid):
 
395
        # This won't work for any round-tripped bzr revisions, but it's a start..
 
396
        try:
 
397
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
398
        except InvalidRevisionId:
 
399
            raise NoSuchRevision(self, bzr_revid)
 
400
 
 
401
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
402
        """Lookup a revision id.
 
403
 
 
404
        """
 
405
        if mapping is None:
 
406
            mapping = self.get_mapping()
 
407
        # Not really an easy way to parse foreign revids here..
 
408
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
 
409
 
 
410
 
 
411
class RemoteGitTagDict(GitTags):
 
412
 
 
413
    def get_refs(self):
 
414
        return self.repository.get_refs()
 
415
 
 
416
    def _iter_tag_refs(self, refs):
 
417
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
418
            yield (k, peeled, unpeeled,
 
419
                  self.branch.mapping.revision_id_foreign_to_bzr(peeled))
 
420
 
 
421
    def set_tag(self, name, revid):
 
422
        # FIXME: Not supported yet, should do a push of a new ref
 
423
        raise NotImplementedError(self.set_tag)
 
424
 
 
425
 
 
426
class RemoteGitBranch(GitBranch):
 
427
 
 
428
    def __init__(self, bzrdir, repository, name, lockfiles):
 
429
        self._sha = None
 
430
        super(RemoteGitBranch, self).__init__(bzrdir, repository, name,
 
431
                lockfiles)
 
432
 
 
433
    @property
 
434
    def user_url(self):
 
435
        return self.control_url
 
436
 
 
437
    @property
 
438
    def control_url(self):
 
439
        return self.base
 
440
 
 
441
    def revision_history(self):
 
442
        raise GitSmartRemoteNotSupported()
 
443
 
 
444
    def last_revision(self):
 
445
        return self.lookup_foreign_revision_id(self.head)
 
446
 
 
447
    def _get_config(self):
 
448
        class EmptyConfig(object):
 
449
 
 
450
            def _get_configobj(self):
 
451
                return config.ConfigObj()
 
452
 
 
453
        return EmptyConfig()
 
454
 
 
455
    @property
 
456
    def head(self):
 
457
        if self._sha is not None:
 
458
            return self._sha
 
459
        heads = self.repository.get_refs()
 
460
        name = self.bzrdir._branch_name_to_ref(self.name, "HEAD")
 
461
        if name in heads:
 
462
            self._sha = heads[name]
 
463
        else:
 
464
            raise NoSuchRef(self.name)
 
465
        return self._sha
 
466
 
 
467
    def _synchronize_history(self, destination, revision_id):
 
468
        """See Branch._synchronize_history()."""
 
469
        destination.generate_revision_history(self.last_revision())
 
470
 
 
471
    def get_push_location(self):
 
472
        return None
 
473
 
 
474
    def set_push_location(self, url):
 
475
        pass