/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

TranslateĀ moreĀ strings.

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
    version_info as bzrlib_version,
 
24
    )
 
25
from bzrlib.errors import (
 
26
    BzrError,
 
27
    InProcessTransport,
 
28
    InvalidRevisionId,
 
29
    NoSuchFile,
 
30
    NoSuchRevision,
 
31
    NotBranchError,
 
32
    NotLocalUrl,
 
33
    UninitializableFormat,
 
34
    )
 
35
from bzrlib.transport import (
 
36
    Transport,
 
37
    )
 
38
 
 
39
from bzrlib.plugins.git import (
 
40
    lazy_check_versions,
 
41
    )
 
42
lazy_check_versions()
 
43
 
 
44
from bzrlib.plugins.git.branch import (
 
45
    GitBranch,
 
46
    GitTags,
 
47
    )
 
48
from bzrlib.plugins.git.dir import (
 
49
    GitControlDirFormat,
 
50
    GitDir,
 
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
 
68
import dulwich.client
 
69
from dulwich.errors import (
 
70
    GitProtocolError,
 
71
    )
 
72
from dulwich.pack import (
 
73
    Pack,
 
74
    PackData,
 
75
    )
 
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
def parse_git_error(url, message):
 
107
    """Parse a remote git server error and return a bzr exception.
 
108
 
 
109
    :param url: URL of the remote repository
 
110
    :param message: Message sent by the remote git server
 
111
    """
 
112
    message = str(message).strip()
 
113
    if message.startswith("Could not find Repository "):
 
114
        return NotBranchError(url, message)
 
115
    # Don't know, just return it to the user as-is
 
116
    return BzrError(message)
 
117
 
 
118
 
 
119
class GitSmartTransport(Transport):
 
120
 
 
121
    def __init__(self, url, _client=None):
 
122
        Transport.__init__(self, url)
 
123
        (self._host, self._port, self._username, self._path) = \
 
124
            split_git_url(url)
 
125
        if 'transport' in debug.debug_flags:
 
126
            trace.mutter('host: %r, user: %r, port: %r, path: %r',
 
127
                         self._host, self._username, self._port, self._path)
 
128
        self._client = _client
 
129
        if "," in self._path and bzrlib_version < (2, 5, 0):
 
130
            trace.warning(
 
131
                "ignoring parameters %r, not supported in bzr < 2.5.",
 
132
                self._path.rsplit(",", 1)[1])
 
133
        self._stripped_path = self._path.rsplit(",", 1)[0]
 
134
 
 
135
    def external_url(self):
 
136
        return self.base
 
137
 
 
138
    def has(self, relpath):
 
139
        return False
 
140
 
 
141
    def _get_client(self, thin_packs):
 
142
        raise NotImplementedError(self._get_client)
 
143
 
 
144
    def _get_path(self):
 
145
        return self._stripped_path
 
146
 
 
147
    def get(self, path):
 
148
        raise NoSuchFile(path)
 
149
 
 
150
    def abspath(self, relpath):
 
151
        return urlutils.join(self.base, relpath)
 
152
 
 
153
    def clone(self, offset=None):
 
154
        """See Transport.clone()."""
 
155
        if offset is None:
 
156
            newurl = self.base
 
157
        else:
 
158
            newurl = urlutils.join(self.base, offset)
 
159
 
 
160
        return self.__class__(newurl, self._client)
 
161
 
 
162
 
 
163
class TCPGitSmartTransport(GitSmartTransport):
 
164
 
 
165
    _scheme = 'git'
 
166
 
 
167
    def _get_client(self, thin_packs):
 
168
        if self._client is not None:
 
169
            ret = self._client
 
170
            self._client = None
 
171
            return ret
 
172
        return dulwich.client.TCPGitClient(self._host, self._port,
 
173
            thin_packs=thin_packs, report_activity=self._report_activity)
 
174
 
 
175
 
 
176
class SSHGitSmartTransport(GitSmartTransport):
 
177
 
 
178
    _scheme = 'git+ssh'
 
179
 
 
180
    def _get_path(self):
 
181
        path = self._stripped_path
 
182
        if path.startswith("/~/"):
 
183
            return path[3:]
 
184
        return path
 
185
 
 
186
    def _get_client(self, thin_packs):
 
187
        if self._client is not None:
 
188
            ret = self._client
 
189
            self._client = None
 
190
            return ret
 
191
        location_config = config.LocationConfig(self.base)
 
192
        client = dulwich.client.SSHGitClient(self._host, self._port, self._username,
 
193
            thin_packs=thin_packs, report_activity=self._report_activity)
 
194
        # Set up alternate pack program paths
 
195
        upload_pack = location_config.get_user_option('git_upload_pack')
 
196
        if upload_pack:
 
197
            client.alternative_paths["upload-pack"] = upload_pack
 
198
        receive_pack = location_config.get_user_option('git_receive_pack')
 
199
        if receive_pack:
 
200
            client.alternative_paths["receive-pack"] = receive_pack
 
201
        return client
 
202
 
 
203
 
 
204
class RemoteGitDir(GitDir):
 
205
 
 
206
    def __init__(self, transport, format, get_client, client_path):
 
207
        self._format = format
 
208
        self.root_transport = transport
 
209
        self.transport = transport
 
210
        self._mode_check_done = None
 
211
        self._get_client = get_client
 
212
        self._client_path = client_path
 
213
        self.base = self.root_transport.base
 
214
        self._refs = None
 
215
 
 
216
    def fetch_pack(self, determine_wants, graph_walker, pack_data, progress=None):
 
217
        if progress is None:
 
218
            def progress(text):
 
219
                trace.info("git: %s" % text)
 
220
        client = self._get_client(thin_packs=False)
 
221
        try:
 
222
            return client.fetch_pack(self._client_path, determine_wants,
 
223
                graph_walker, pack_data, progress)
 
224
        except GitProtocolError, e:
 
225
            raise parse_git_error(self.transport.external_url(), e)
 
226
 
 
227
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
228
        client = self._get_client(thin_packs=False)
 
229
        try:
 
230
            return client.send_pack(self._client_path, get_changed_refs,
 
231
                generate_pack_contents)
 
232
        except GitProtocolError, e:
 
233
            raise parse_git_error(self.transport.external_url(), e)
 
234
 
 
235
    def destroy_branch(self, name=None):
 
236
        refname = self._get_selected_ref(name)
 
237
        if refname is None:
 
238
            refname = "HEAD"
 
239
        def get_changed_refs(old_refs):
 
240
            ret = dict(old_refs)
 
241
            if not refname in ret:
 
242
                raise NotBranchError(self.user_url)
 
243
            ret[refname] = "00" * 20
 
244
            return ret
 
245
        self.send_pack(get_changed_refs, lambda have, want: [])
 
246
 
 
247
    @property
 
248
    def user_url(self):
 
249
        return self.control_url
 
250
 
 
251
    @property
 
252
    def user_transport(self):
 
253
        return self.root_transport
 
254
 
 
255
    @property
 
256
    def control_url(self):
 
257
        return self.control_transport.base
 
258
 
 
259
    @property
 
260
    def control_transport(self):
 
261
        return self.root_transport
 
262
 
 
263
    def open_repository(self):
 
264
        return RemoteGitRepository(self)
 
265
 
 
266
    def open_branch(self, name=None, unsupported=False,
 
267
            ignore_fallbacks=False, ref=None, possible_transports=None):
 
268
        repo = self.open_repository()
 
269
        refname = self._get_selected_ref(name, ref)
 
270
        return RemoteGitBranch(self, repo, refname)
 
271
 
 
272
    def open_workingtree(self, recommend_upgrade=False):
 
273
        raise NotLocalUrl(self.transport.base)
 
274
 
 
275
    def get_refs(self):
 
276
        if self._refs is not None:
 
277
            return self._refs
 
278
        self._refs = self.fetch_pack(lambda x: [], None,
 
279
            lambda x: None, lambda x: trace.mutter("git: %s" % x))
 
280
        return self._refs
 
281
 
 
282
 
 
283
class EmptyObjectStoreIterator(dict):
 
284
 
 
285
    def iterobjects(self):
 
286
        return []
 
287
 
 
288
 
 
289
class TemporaryPackIterator(Pack):
 
290
 
 
291
    def __init__(self, path, resolve_ext_ref):
 
292
        super(TemporaryPackIterator, self).__init__(path)
 
293
        self.resolve_ext_ref = resolve_ext_ref
 
294
 
 
295
    @property
 
296
    def data(self):
 
297
        if self._data is None:
 
298
            self._data = PackData(self._data_path)
 
299
        return self._data
 
300
 
 
301
    @property
 
302
    def index(self):
 
303
        if self._idx is None:
 
304
            if not os.path.exists(self._idx_path):
 
305
                pb = ui.ui_factory.nested_progress_bar()
 
306
                try:
 
307
                    def report_progress(cur, total):
 
308
                        pb.update("generating index", cur, total)
 
309
                    self.data.create_index(self._idx_path, 
 
310
                        progress=report_progress)
 
311
                finally:
 
312
                    pb.finished()
 
313
            self._idx = load_pack_index(self._idx_path)
 
314
        return self._idx
 
315
 
 
316
    def __del__(self):
 
317
        if self._idx is not None:
 
318
            self._idx.close()
 
319
            os.remove(self._idx_path)
 
320
        if self._data is not None:
 
321
            self._data.close()
 
322
            os.remove(self._data_path)
 
323
 
 
324
 
 
325
class BzrGitHttpClient(dulwich.client.HttpGitClient):
 
326
 
 
327
    def __init__(self, transport, *args, **kwargs):
 
328
        self.transport = transport
 
329
        super(BzrGitHttpClient, self).__init__(transport.external_url(), *args, **kwargs)
 
330
        import urllib2
 
331
        self._http_perform = getattr(self.transport, "_perform", urllib2.urlopen)
 
332
 
 
333
    def _perform(self, req):
 
334
        req.accepted_errors = (200, 404)
 
335
        req.follow_redirections = True
 
336
        req.redirected_to = None
 
337
        return self._http_perform(req)
 
338
 
 
339
 
 
340
class RemoteGitControlDirFormat(GitControlDirFormat):
 
341
    """The .git directory control format."""
 
342
 
 
343
    supports_workingtrees = False
 
344
 
 
345
    @classmethod
 
346
    def _known_formats(self):
 
347
        return set([RemoteGitControlDirFormat()])
 
348
 
 
349
    def is_initializable(self):
 
350
        return False
 
351
 
 
352
    def is_supported(self):
 
353
        return True
 
354
 
 
355
    def open(self, transport, _found=None):
 
356
        """Open this directory.
 
357
 
 
358
        """
 
359
        # we dont grok readonly - git isn't integrated with transport.
 
360
        url = transport.base
 
361
        if url.startswith('readonly+'):
 
362
            url = url[len('readonly+'):]
 
363
        if isinstance(transport, GitSmartTransport):
 
364
            get_client = transport._get_client
 
365
            client_path = transport._get_path()
 
366
        elif urlparse.urlsplit(transport.external_url())[0] in ("http", "https"):
 
367
            def get_client(thin_packs=False):
 
368
                return BzrGitHttpClient(transport, thin_packs=thin_packs)
 
369
            client_path = transport._path
 
370
        else:
 
371
            raise NotBranchError(transport.base)
 
372
        return RemoteGitDir(transport, self, get_client, client_path)
 
373
 
 
374
    def get_format_description(self):
 
375
        return "Remote Git Repository"
 
376
 
 
377
    def initialize_on_transport(self, transport):
 
378
        raise UninitializableFormat(self)
 
379
 
 
380
    def supports_transport(self, transport):
 
381
        try:
 
382
            external_url = transport.external_url()
 
383
        except InProcessTransport:
 
384
            raise NotBranchError(path=transport.base)
 
385
        return (external_url.startswith("http:") or
 
386
                external_url.startswith("https:") or
 
387
                external_url.startswith("git+") or
 
388
                external_url.startswith("git:"))
 
389
 
 
390
 
 
391
class RemoteGitRepository(GitRepository):
 
392
 
 
393
    @property
 
394
    def user_url(self):
 
395
        return self.control_url
 
396
 
 
397
    def get_parent_map(self, revids):
 
398
        raise GitSmartRemoteNotSupported(self.get_parent_map, self)
 
399
 
 
400
    def fetch_pack(self, determine_wants, graph_walker, pack_data,
 
401
                   progress=None):
 
402
        return self.bzrdir.fetch_pack(determine_wants, graph_walker,
 
403
                                          pack_data, progress)
 
404
 
 
405
    def send_pack(self, get_changed_refs, generate_pack_contents):
 
406
        return self.bzrdir.send_pack(get_changed_refs, generate_pack_contents)
 
407
 
 
408
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
 
409
                      progress=None):
 
410
        fd, path = tempfile.mkstemp(suffix=".pack")
 
411
        try:
 
412
            self.fetch_pack(determine_wants, graph_walker,
 
413
                lambda x: os.write(fd, x), progress)
 
414
        finally:
 
415
            os.close(fd)
 
416
        if os.path.getsize(path) == 0:
 
417
            return EmptyObjectStoreIterator()
 
418
        return TemporaryPackIterator(path[:-len(".pack")], resolve_ext_ref)
 
419
 
 
420
    def lookup_bzr_revision_id(self, bzr_revid):
 
421
        # This won't work for any round-tripped bzr revisions, but it's a start..
 
422
        try:
 
423
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
 
424
        except InvalidRevisionId:
 
425
            raise NoSuchRevision(self, bzr_revid)
 
426
 
 
427
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
428
        """Lookup a revision id.
 
429
 
 
430
        """
 
431
        if mapping is None:
 
432
            mapping = self.get_mapping()
 
433
        # Not really an easy way to parse foreign revids here..
 
434
        return mapping.revision_id_foreign_to_bzr(foreign_revid)
 
435
 
 
436
    def revision_tree(self, revid):
 
437
        raise GitSmartRemoteNotSupported(self.revision_tree, self)
 
438
 
 
439
    def get_revisions(self, revids):
 
440
        raise GitSmartRemoteNotSupported(self.get_revisions, self)
 
441
 
 
442
 
 
443
class RemoteGitTagDict(GitTags):
 
444
 
 
445
    def get_refs(self):
 
446
        return self.repository.bzrdir.get_refs()
 
447
 
 
448
    def _iter_tag_refs(self, refs):
 
449
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
450
            yield (k, peeled, unpeeled,
 
451
                  self.branch.mapping.revision_id_foreign_to_bzr(peeled))
 
452
 
 
453
    def set_tag(self, name, revid):
 
454
        # FIXME: Not supported yet, should do a push of a new ref
 
455
        raise NotImplementedError(self.set_tag)
 
456
 
 
457
 
 
458
class RemoteGitBranch(GitBranch):
 
459
 
 
460
    def __init__(self, bzrdir, repository, name):
 
461
        self._sha = None
 
462
        super(RemoteGitBranch, self).__init__(bzrdir, repository, name)
 
463
 
 
464
    def last_revision_info(self):
 
465
        raise GitSmartRemoteNotSupported(self.last_revision_info, self)
 
466
 
 
467
    @property
 
468
    def user_url(self):
 
469
        return self.control_url
 
470
 
 
471
    @property
 
472
    def control_url(self):
 
473
        return self.base
 
474
 
 
475
    def revision_history(self):
 
476
        raise GitSmartRemoteNotSupported(self.revision_history, self)
 
477
 
 
478
    def revision_id_to_revno(self, revision_id):
 
479
        raise GitSmartRemoteNotSupported(self.revision_id_to_revno, self)
 
480
 
 
481
    def last_revision(self):
 
482
        return self.lookup_foreign_revision_id(self.head)
 
483
 
 
484
    @property
 
485
    def head(self):
 
486
        if self._sha is not None:
 
487
            return self._sha
 
488
        refs = self.bzrdir.get_refs()
 
489
        name = branch_name_to_ref(self.name, "HEAD")
 
490
        try:
 
491
            self._sha = refs[name]
 
492
        except KeyError:
 
493
            raise NoSuchRef(name, self.repository.user_url, refs)
 
494
        return self._sha
 
495
 
 
496
    def _synchronize_history(self, destination, revision_id):
 
497
        """See Branch._synchronize_history()."""
 
498
        destination.generate_revision_history(self.last_revision())
 
499
 
 
500
    def get_push_location(self):
 
501
        return None
 
502
 
 
503
    def set_push_location(self, url):
 
504
        pass