1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
 
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.
 
 
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.
 
 
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
 
 
17
# TODO: At some point, handle upgrades by just passing the whole request
 
 
18
# across to run on the server.
 
 
21
from cStringIO import StringIO
 
 
33
from bzrlib.branch import BranchReferenceFormat
 
 
34
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
 
 
35
from bzrlib.config import BranchConfig, TreeConfig
 
 
36
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
 
37
from bzrlib.errors import (
 
 
41
from bzrlib.lockable_files import LockableFiles
 
 
42
from bzrlib.pack import ContainerPushParser
 
 
43
from bzrlib.smart import client, vfs
 
 
44
from bzrlib.symbol_versioning import (
 
 
48
from bzrlib.revision import ensure_null, NULL_REVISION
 
 
49
from bzrlib.trace import mutter, note, warning
 
 
52
# Note: RemoteBzrDirFormat is in bzrdir.py
 
 
54
class RemoteBzrDir(BzrDir):
 
 
55
    """Control directory on a remote server, accessed via bzr:// or similar."""
 
 
57
    def __init__(self, transport, _client=None):
 
 
58
        """Construct a RemoteBzrDir.
 
 
60
        :param _client: Private parameter for testing. Disables probing and the
 
 
63
        BzrDir.__init__(self, transport, RemoteBzrDirFormat())
 
 
64
        # this object holds a delegated bzrdir that uses file-level operations
 
 
65
        # to talk to the other side
 
 
66
        self._real_bzrdir = None
 
 
69
            medium = transport.get_smart_medium()
 
 
70
            self._client = client._SmartClient(medium)
 
 
72
            self._client = _client
 
 
75
        path = self._path_for_remote_call(self._client)
 
 
76
        response = self._client.call('BzrDir.open', path)
 
 
77
        if response not in [('yes',), ('no',)]:
 
 
78
            raise errors.UnexpectedSmartServerResponse(response)
 
 
79
        if response == ('no',):
 
 
80
            raise errors.NotBranchError(path=transport.base)
 
 
82
    def _ensure_real(self):
 
 
83
        """Ensure that there is a _real_bzrdir set.
 
 
85
        Used before calls to self._real_bzrdir.
 
 
87
        if not self._real_bzrdir:
 
 
88
            self._real_bzrdir = BzrDir.open_from_transport(
 
 
89
                self.root_transport, _server_formats=False)
 
 
91
    def cloning_metadir(self):
 
 
93
        return self._real_bzrdir.cloning_metadir()
 
 
95
    def _translate_error(self, err, **context):
 
 
96
        _translate_error(err, bzrdir=self, **context)
 
 
98
    def create_repository(self, shared=False):
 
 
100
        self._real_bzrdir.create_repository(shared=shared)
 
 
101
        return self.open_repository()
 
 
103
    def destroy_repository(self):
 
 
104
        """See BzrDir.destroy_repository"""
 
 
106
        self._real_bzrdir.destroy_repository()
 
 
108
    def create_branch(self):
 
 
110
        real_branch = self._real_bzrdir.create_branch()
 
 
111
        return RemoteBranch(self, self.find_repository(), real_branch)
 
 
113
    def destroy_branch(self):
 
 
114
        """See BzrDir.destroy_branch"""
 
 
116
        self._real_bzrdir.destroy_branch()
 
 
118
    def create_workingtree(self, revision_id=None, from_branch=None):
 
 
119
        raise errors.NotLocalUrl(self.transport.base)
 
 
121
    def find_branch_format(self):
 
 
122
        """Find the branch 'format' for this bzrdir.
 
 
124
        This might be a synthetic object for e.g. RemoteBranch and SVN.
 
 
126
        b = self.open_branch()
 
 
129
    def get_branch_reference(self):
 
 
130
        """See BzrDir.get_branch_reference()."""
 
 
131
        path = self._path_for_remote_call(self._client)
 
 
133
            response = self._client.call('BzrDir.open_branch', path)
 
 
134
        except errors.ErrorFromSmartServer, err:
 
 
135
            self._translate_error(err)
 
 
136
        if response[0] == 'ok':
 
 
137
            if response[1] == '':
 
 
138
                # branch at this location.
 
 
141
                # a branch reference, use the existing BranchReference logic.
 
 
144
            raise errors.UnexpectedSmartServerResponse(response)
 
 
146
    def _get_tree_branch(self):
 
 
147
        """See BzrDir._get_tree_branch()."""
 
 
148
        return None, self.open_branch()
 
 
150
    def open_branch(self, _unsupported=False):
 
 
152
            raise NotImplementedError('unsupported flag support not implemented yet.')
 
 
153
        reference_url = self.get_branch_reference()
 
 
154
        if reference_url is None:
 
 
155
            # branch at this location.
 
 
156
            return RemoteBranch(self, self.find_repository())
 
 
158
            # a branch reference, use the existing BranchReference logic.
 
 
159
            format = BranchReferenceFormat()
 
 
160
            return format.open(self, _found=True, location=reference_url)
 
 
162
    def open_repository(self):
 
 
163
        path = self._path_for_remote_call(self._client)
 
 
164
        verb = 'BzrDir.find_repositoryV2'
 
 
167
                response = self._client.call(verb, path)
 
 
168
            except errors.UnknownSmartMethod:
 
 
169
                verb = 'BzrDir.find_repository'
 
 
170
                response = self._client.call(verb, path)
 
 
171
        except errors.ErrorFromSmartServer, err:
 
 
172
            self._translate_error(err)
 
 
173
        if response[0] != 'ok':
 
 
174
            raise errors.UnexpectedSmartServerResponse(response)
 
 
175
        if verb == 'BzrDir.find_repository':
 
 
176
            # servers that don't support the V2 method don't support external
 
 
178
            response = response + ('no', )
 
 
179
        if not (len(response) == 5):
 
 
180
            raise SmartProtocolError('incorrect response length %s' % (response,))
 
 
181
        if response[1] == '':
 
 
182
            format = RemoteRepositoryFormat()
 
 
183
            format.rich_root_data = (response[2] == 'yes')
 
 
184
            format.supports_tree_reference = (response[3] == 'yes')
 
 
185
            # No wire format to check this yet.
 
 
186
            format.supports_external_lookups = (response[4] == 'yes')
 
 
187
            # Used to support creating a real format instance when needed.
 
 
188
            format._creating_bzrdir = self
 
 
189
            return RemoteRepository(self, format)
 
 
191
            raise errors.NoRepositoryPresent(self)
 
 
193
    def open_workingtree(self, recommend_upgrade=True):
 
 
195
        if self._real_bzrdir.has_workingtree():
 
 
196
            raise errors.NotLocalUrl(self.root_transport)
 
 
198
            raise errors.NoWorkingTree(self.root_transport.base)
 
 
200
    def _path_for_remote_call(self, client):
 
 
201
        """Return the path to be used for this bzrdir in a remote call."""
 
 
202
        return client.remote_path_from_transport(self.root_transport)
 
 
204
    def get_branch_transport(self, branch_format):
 
 
206
        return self._real_bzrdir.get_branch_transport(branch_format)
 
 
208
    def get_repository_transport(self, repository_format):
 
 
210
        return self._real_bzrdir.get_repository_transport(repository_format)
 
 
212
    def get_workingtree_transport(self, workingtree_format):
 
 
214
        return self._real_bzrdir.get_workingtree_transport(workingtree_format)
 
 
216
    def can_convert_format(self):
 
 
217
        """Upgrading of remote bzrdirs is not supported yet."""
 
 
220
    def needs_format_conversion(self, format=None):
 
 
221
        """Upgrading of remote bzrdirs is not supported yet."""
 
 
224
    def clone(self, url, revision_id=None, force_new_repo=False,
 
 
225
              preserve_stacking=False):
 
 
227
        return self._real_bzrdir.clone(url, revision_id=revision_id,
 
 
228
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
 
 
230
    def get_config(self):
 
 
232
        return self._real_bzrdir.get_config()
 
 
235
class RemoteRepositoryFormat(repository.RepositoryFormat):
 
 
236
    """Format for repositories accessed over a _SmartClient.
 
 
238
    Instances of this repository are represented by RemoteRepository
 
 
241
    The RemoteRepositoryFormat is parameterized during construction
 
 
242
    to reflect the capabilities of the real, remote format. Specifically
 
 
243
    the attributes rich_root_data and supports_tree_reference are set
 
 
244
    on a per instance basis, and are not set (and should not be) at
 
 
248
    _matchingbzrdir = RemoteBzrDirFormat()
 
 
250
    def initialize(self, a_bzrdir, shared=False):
 
 
251
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
 
252
            prior_repo = self._creating_bzrdir.open_repository()
 
 
253
            prior_repo._ensure_real()
 
 
254
            return prior_repo._real_repository._format.initialize(
 
 
255
                a_bzrdir, shared=shared)
 
 
256
        return a_bzrdir.create_repository(shared=shared)
 
 
258
    def open(self, a_bzrdir):
 
 
259
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
 
260
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
 
 
261
        return a_bzrdir.open_repository()
 
 
263
    def get_format_description(self):
 
 
264
        return 'bzr remote repository'
 
 
266
    def __eq__(self, other):
 
 
267
        return self.__class__ == other.__class__
 
 
269
    def check_conversion_target(self, target_format):
 
 
270
        if self.rich_root_data and not target_format.rich_root_data:
 
 
271
            raise errors.BadConversionTarget(
 
 
272
                'Does not support rich root data.', target_format)
 
 
273
        if (self.supports_tree_reference and
 
 
274
            not getattr(target_format, 'supports_tree_reference', False)):
 
 
275
            raise errors.BadConversionTarget(
 
 
276
                'Does not support nested trees', target_format)
 
 
279
class RemoteRepository(object):
 
 
280
    """Repository accessed over rpc.
 
 
282
    For the moment most operations are performed using local transport-backed
 
 
286
    def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
 
 
287
        """Create a RemoteRepository instance.
 
 
289
        :param remote_bzrdir: The bzrdir hosting this repository.
 
 
290
        :param format: The RemoteFormat object to use.
 
 
291
        :param real_repository: If not None, a local implementation of the
 
 
292
            repository logic for the repository, usually accessing the data
 
 
294
        :param _client: Private testing parameter - override the smart client
 
 
295
            to be used by the repository.
 
 
298
            self._real_repository = real_repository
 
 
300
            self._real_repository = None
 
 
301
        self.bzrdir = remote_bzrdir
 
 
303
            self._client = remote_bzrdir._client
 
 
305
            self._client = _client
 
 
306
        self._format = format
 
 
307
        self._lock_mode = None
 
 
308
        self._lock_token = None
 
 
310
        self._leave_lock = False
 
 
311
        # A cache of looked up revision parent data; reset at unlock time.
 
 
312
        self._parents_map = None
 
 
313
        if 'hpss' in debug.debug_flags:
 
 
314
            self._requested_parents = None
 
 
316
        # These depend on the actual remote format, so force them off for
 
 
317
        # maximum compatibility. XXX: In future these should depend on the
 
 
318
        # remote repository instance, but this is irrelevant until we perform
 
 
319
        # reconcile via an RPC call.
 
 
320
        self._reconcile_does_inventory_gc = False
 
 
321
        self._reconcile_fixes_text_parents = False
 
 
322
        self._reconcile_backsup_inventory = False
 
 
323
        self.base = self.bzrdir.transport.base
 
 
324
        # Additional places to query for data.
 
 
325
        self._fallback_repositories = []
 
 
328
        return "%s(%s)" % (self.__class__.__name__, self.base)
 
 
332
    def abort_write_group(self):
 
 
333
        """Complete a write group on the decorated repository.
 
 
335
        Smart methods peform operations in a single step so this api
 
 
336
        is not really applicable except as a compatibility thunk
 
 
337
        for older plugins that don't use e.g. the CommitBuilder
 
 
341
        return self._real_repository.abort_write_group()
 
 
343
    def commit_write_group(self):
 
 
344
        """Complete a write group on the decorated repository.
 
 
346
        Smart methods peform operations in a single step so this api
 
 
347
        is not really applicable except as a compatibility thunk
 
 
348
        for older plugins that don't use e.g. the CommitBuilder
 
 
352
        return self._real_repository.commit_write_group()
 
 
354
    def _ensure_real(self):
 
 
355
        """Ensure that there is a _real_repository set.
 
 
357
        Used before calls to self._real_repository.
 
 
359
        if not self._real_repository:
 
 
360
            self.bzrdir._ensure_real()
 
 
361
            #self._real_repository = self.bzrdir._real_bzrdir.open_repository()
 
 
362
            self._set_real_repository(self.bzrdir._real_bzrdir.open_repository())
 
 
364
    def _translate_error(self, err, **context):
 
 
365
        self.bzrdir._translate_error(err, repository=self, **context)
 
 
367
    def find_text_key_references(self):
 
 
368
        """Find the text key references within the repository.
 
 
370
        :return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
 
 
371
        revision_ids. Each altered file-ids has the exact revision_ids that
 
 
372
        altered it listed explicitly.
 
 
373
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
 
374
            to whether they were referred to by the inventory of the
 
 
375
            revision_id that they contain. The inventory texts from all present
 
 
376
            revision ids are assessed to generate this report.
 
 
379
        return self._real_repository.find_text_key_references()
 
 
381
    def _generate_text_key_index(self):
 
 
382
        """Generate a new text key index for the repository.
 
 
384
        This is an expensive function that will take considerable time to run.
 
 
386
        :return: A dict mapping (file_id, revision_id) tuples to a list of
 
 
387
            parents, also (file_id, revision_id) tuples.
 
 
390
        return self._real_repository._generate_text_key_index()
 
 
392
    @symbol_versioning.deprecated_method(symbol_versioning.one_four)
 
 
393
    def get_revision_graph(self, revision_id=None):
 
 
394
        """See Repository.get_revision_graph()."""
 
 
395
        return self._get_revision_graph(revision_id)
 
 
397
    def _get_revision_graph(self, revision_id):
 
 
398
        """Private method for using with old (< 1.2) servers to fallback."""
 
 
399
        if revision_id is None:
 
 
401
        elif revision.is_null(revision_id):
 
 
404
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
406
            response = self._client.call_expecting_body(
 
 
407
                'Repository.get_revision_graph', path, revision_id)
 
 
408
        except errors.ErrorFromSmartServer, err:
 
 
409
            self._translate_error(err)
 
 
410
        response_tuple, response_handler = response
 
 
411
        if response_tuple[0] != 'ok':
 
 
412
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
 
413
        coded = response_handler.read_body_bytes()
 
 
415
            # no revisions in this repository!
 
 
417
        lines = coded.split('\n')
 
 
420
            d = tuple(line.split())
 
 
421
            revision_graph[d[0]] = d[1:]
 
 
423
        return revision_graph
 
 
425
    def has_revision(self, revision_id):
 
 
426
        """See Repository.has_revision()."""
 
 
427
        if revision_id == NULL_REVISION:
 
 
428
            # The null revision is always present.
 
 
430
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
431
        response = self._client.call(
 
 
432
            'Repository.has_revision', path, revision_id)
 
 
433
        if response[0] not in ('yes', 'no'):
 
 
434
            raise errors.UnexpectedSmartServerResponse(response)
 
 
435
        return response[0] == 'yes'
 
 
437
    def has_revisions(self, revision_ids):
 
 
438
        """See Repository.has_revisions()."""
 
 
440
        for revision_id in revision_ids:
 
 
441
            if self.has_revision(revision_id):
 
 
442
                result.add(revision_id)
 
 
445
    def has_same_location(self, other):
 
 
446
        return (self.__class__ == other.__class__ and
 
 
447
                self.bzrdir.transport.base == other.bzrdir.transport.base)
 
 
449
    def get_graph(self, other_repository=None):
 
 
450
        """Return the graph for this repository format"""
 
 
451
        parents_provider = self
 
 
452
        if (other_repository is not None and
 
 
453
            other_repository.bzrdir.transport.base !=
 
 
454
            self.bzrdir.transport.base):
 
 
455
            parents_provider = graph._StackedParentsProvider(
 
 
456
                [parents_provider, other_repository._make_parents_provider()])
 
 
457
        return graph.Graph(parents_provider)
 
 
459
    def gather_stats(self, revid=None, committers=None):
 
 
460
        """See Repository.gather_stats()."""
 
 
461
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
462
        # revid can be None to indicate no revisions, not just NULL_REVISION
 
 
463
        if revid is None or revision.is_null(revid):
 
 
467
        if committers is None or not committers:
 
 
468
            fmt_committers = 'no'
 
 
470
            fmt_committers = 'yes'
 
 
471
        response_tuple, response_handler = self._client.call_expecting_body(
 
 
472
            'Repository.gather_stats', path, fmt_revid, fmt_committers)
 
 
473
        if response_tuple[0] != 'ok':
 
 
474
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
 
476
        body = response_handler.read_body_bytes()
 
 
478
        for line in body.split('\n'):
 
 
481
            key, val_text = line.split(':')
 
 
482
            if key in ('revisions', 'size', 'committers'):
 
 
483
                result[key] = int(val_text)
 
 
484
            elif key in ('firstrev', 'latestrev'):
 
 
485
                values = val_text.split(' ')[1:]
 
 
486
                result[key] = (float(values[0]), long(values[1]))
 
 
490
    def find_branches(self, using=False):
 
 
491
        """See Repository.find_branches()."""
 
 
492
        # should be an API call to the server.
 
 
494
        return self._real_repository.find_branches(using=using)
 
 
496
    def get_physical_lock_status(self):
 
 
497
        """See Repository.get_physical_lock_status()."""
 
 
498
        # should be an API call to the server.
 
 
500
        return self._real_repository.get_physical_lock_status()
 
 
502
    def is_in_write_group(self):
 
 
503
        """Return True if there is an open write group.
 
 
505
        write groups are only applicable locally for the smart server..
 
 
507
        if self._real_repository:
 
 
508
            return self._real_repository.is_in_write_group()
 
 
511
        return self._lock_count >= 1
 
 
514
        """See Repository.is_shared()."""
 
 
515
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
516
        response = self._client.call('Repository.is_shared', path)
 
 
517
        if response[0] not in ('yes', 'no'):
 
 
518
            raise SmartProtocolError('unexpected response code %s' % (response,))
 
 
519
        return response[0] == 'yes'
 
 
521
    def is_write_locked(self):
 
 
522
        return self._lock_mode == 'w'
 
 
525
        # wrong eventually - want a local lock cache context
 
 
526
        if not self._lock_mode:
 
 
527
            self._lock_mode = 'r'
 
 
529
            self._parents_map = {}
 
 
530
            if 'hpss' in debug.debug_flags:
 
 
531
                self._requested_parents = set()
 
 
532
            if self._real_repository is not None:
 
 
533
                self._real_repository.lock_read()
 
 
535
            self._lock_count += 1
 
 
537
    def _remote_lock_write(self, token):
 
 
538
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
542
            response = self._client.call('Repository.lock_write', path, token)
 
 
543
        except errors.ErrorFromSmartServer, err:
 
 
544
            self._translate_error(err, token=token)
 
 
546
        if response[0] == 'ok':
 
 
550
            raise errors.UnexpectedSmartServerResponse(response)
 
 
552
    def lock_write(self, token=None):
 
 
553
        if not self._lock_mode:
 
 
554
            self._lock_token = self._remote_lock_write(token)
 
 
555
            # if self._lock_token is None, then this is something like packs or
 
 
556
            # svn where we don't get to lock the repo, or a weave style repository
 
 
557
            # where we cannot lock it over the wire and attempts to do so will
 
 
559
            if self._real_repository is not None:
 
 
560
                self._real_repository.lock_write(token=self._lock_token)
 
 
561
            if token is not None:
 
 
562
                self._leave_lock = True
 
 
564
                self._leave_lock = False
 
 
565
            self._lock_mode = 'w'
 
 
567
            self._parents_map = {}
 
 
568
            if 'hpss' in debug.debug_flags:
 
 
569
                self._requested_parents = set()
 
 
570
        elif self._lock_mode == 'r':
 
 
571
            raise errors.ReadOnlyError(self)
 
 
573
            self._lock_count += 1
 
 
574
        return self._lock_token or None
 
 
576
    def leave_lock_in_place(self):
 
 
577
        if not self._lock_token:
 
 
578
            raise NotImplementedError(self.leave_lock_in_place)
 
 
579
        self._leave_lock = True
 
 
581
    def dont_leave_lock_in_place(self):
 
 
582
        if not self._lock_token:
 
 
583
            raise NotImplementedError(self.dont_leave_lock_in_place)
 
 
584
        self._leave_lock = False
 
 
586
    def _set_real_repository(self, repository):
 
 
587
        """Set the _real_repository for this repository.
 
 
589
        :param repository: The repository to fallback to for non-hpss
 
 
590
            implemented operations.
 
 
592
        if isinstance(repository, RemoteRepository):
 
 
593
            raise AssertionError()
 
 
594
        self._real_repository = repository
 
 
595
        if self._lock_mode == 'w':
 
 
596
            # if we are already locked, the real repository must be able to
 
 
597
            # acquire the lock with our token.
 
 
598
            self._real_repository.lock_write(self._lock_token)
 
 
599
        elif self._lock_mode == 'r':
 
 
600
            self._real_repository.lock_read()
 
 
602
    def start_write_group(self):
 
 
603
        """Start a write group on the decorated repository.
 
 
605
        Smart methods peform operations in a single step so this api
 
 
606
        is not really applicable except as a compatibility thunk
 
 
607
        for older plugins that don't use e.g. the CommitBuilder
 
 
611
        return self._real_repository.start_write_group()
 
 
613
    def _unlock(self, token):
 
 
614
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
616
            # with no token the remote repository is not persistently locked.
 
 
619
            response = self._client.call('Repository.unlock', path, token)
 
 
620
        except errors.ErrorFromSmartServer, err:
 
 
621
            self._translate_error(err, token=token)
 
 
622
        if response == ('ok',):
 
 
625
            raise errors.UnexpectedSmartServerResponse(response)
 
 
628
        self._lock_count -= 1
 
 
629
        if self._lock_count > 0:
 
 
631
        self._parents_map = None
 
 
632
        if 'hpss' in debug.debug_flags:
 
 
633
            self._requested_parents = None
 
 
634
        old_mode = self._lock_mode
 
 
635
        self._lock_mode = None
 
 
637
            # The real repository is responsible at present for raising an
 
 
638
            # exception if it's in an unfinished write group.  However, it
 
 
639
            # normally will *not* actually remove the lock from disk - that's
 
 
640
            # done by the server on receiving the Repository.unlock call.
 
 
641
            # This is just to let the _real_repository stay up to date.
 
 
642
            if self._real_repository is not None:
 
 
643
                self._real_repository.unlock()
 
 
645
            # The rpc-level lock should be released even if there was a
 
 
646
            # problem releasing the vfs-based lock.
 
 
648
                # Only write-locked repositories need to make a remote method
 
 
649
                # call to perfom the unlock.
 
 
650
                old_token = self._lock_token
 
 
651
                self._lock_token = None
 
 
652
                if not self._leave_lock:
 
 
653
                    self._unlock(old_token)
 
 
655
    def break_lock(self):
 
 
656
        # should hand off to the network
 
 
658
        return self._real_repository.break_lock()
 
 
660
    def _get_tarball(self, compression):
 
 
661
        """Return a TemporaryFile containing a repository tarball.
 
 
663
        Returns None if the server does not support sending tarballs.
 
 
666
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
668
            response, protocol = self._client.call_expecting_body(
 
 
669
                'Repository.tarball', path, compression)
 
 
670
        except errors.UnknownSmartMethod:
 
 
671
            protocol.cancel_read_body()
 
 
673
        if response[0] == 'ok':
 
 
674
            # Extract the tarball and return it
 
 
675
            t = tempfile.NamedTemporaryFile()
 
 
676
            # TODO: rpc layer should read directly into it...
 
 
677
            t.write(protocol.read_body_bytes())
 
 
680
        raise errors.UnexpectedSmartServerResponse(response)
 
 
682
    def sprout(self, to_bzrdir, revision_id=None):
 
 
683
        # TODO: Option to control what format is created?
 
 
685
        dest_repo = self._real_repository._format.initialize(to_bzrdir,
 
 
687
        dest_repo.fetch(self, revision_id=revision_id)
 
 
690
    ### These methods are just thin shims to the VFS object for now.
 
 
692
    def revision_tree(self, revision_id):
 
 
694
        return self._real_repository.revision_tree(revision_id)
 
 
696
    def get_serializer_format(self):
 
 
698
        return self._real_repository.get_serializer_format()
 
 
700
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
 
701
                           timezone=None, committer=None, revprops=None,
 
 
703
        # FIXME: It ought to be possible to call this without immediately
 
 
704
        # triggering _ensure_real.  For now it's the easiest thing to do.
 
 
706
        builder = self._real_repository.get_commit_builder(branch, parents,
 
 
707
                config, timestamp=timestamp, timezone=timezone,
 
 
708
                committer=committer, revprops=revprops, revision_id=revision_id)
 
 
711
    def add_fallback_repository(self, repository):
 
 
712
        """Add a repository to use for looking up data not held locally.
 
 
714
        :param repository: A repository.
 
 
716
        if not self._format.supports_external_lookups:
 
 
717
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
 
718
        # We need to accumulate additional repositories here, to pass them in
 
 
720
        self._fallback_repositories.append(repository)
 
 
722
    def add_inventory(self, revid, inv, parents):
 
 
724
        return self._real_repository.add_inventory(revid, inv, parents)
 
 
726
    def add_revision(self, rev_id, rev, inv=None, config=None):
 
 
728
        return self._real_repository.add_revision(
 
 
729
            rev_id, rev, inv=inv, config=config)
 
 
732
    def get_inventory(self, revision_id):
 
 
734
        return self._real_repository.get_inventory(revision_id)
 
 
736
    def iter_inventories(self, revision_ids):
 
 
738
        return self._real_repository.iter_inventories(revision_ids)
 
 
741
    def get_revision(self, revision_id):
 
 
743
        return self._real_repository.get_revision(revision_id)
 
 
745
    def get_transaction(self):
 
 
747
        return self._real_repository.get_transaction()
 
 
750
    def clone(self, a_bzrdir, revision_id=None):
 
 
752
        return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
 
 
754
    def make_working_trees(self):
 
 
755
        """See Repository.make_working_trees"""
 
 
757
        return self._real_repository.make_working_trees()
 
 
759
    def revision_ids_to_search_result(self, result_set):
 
 
760
        """Convert a set of revision ids to a graph SearchResult."""
 
 
761
        result_parents = set()
 
 
762
        for parents in self.get_graph().get_parent_map(
 
 
763
            result_set).itervalues():
 
 
764
            result_parents.update(parents)
 
 
765
        included_keys = result_set.intersection(result_parents)
 
 
766
        start_keys = result_set.difference(included_keys)
 
 
767
        exclude_keys = result_parents.difference(result_set)
 
 
768
        result = graph.SearchResult(start_keys, exclude_keys,
 
 
769
            len(result_set), result_set)
 
 
773
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
 
774
        """Return the revision ids that other has that this does not.
 
 
776
        These are returned in topological order.
 
 
778
        revision_id: only return revision ids included by revision_id.
 
 
780
        return repository.InterRepository.get(
 
 
781
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
 
 
783
    def fetch(self, source, revision_id=None, pb=None):
 
 
784
        if self.has_same_location(source):
 
 
785
            # check that last_revision is in 'from' and then return a
 
 
787
            if (revision_id is not None and
 
 
788
                not revision.is_null(revision_id)):
 
 
789
                self.get_revision(revision_id)
 
 
792
        return self._real_repository.fetch(
 
 
793
            source, revision_id=revision_id, pb=pb)
 
 
795
    def create_bundle(self, target, base, fileobj, format=None):
 
 
797
        self._real_repository.create_bundle(target, base, fileobj, format)
 
 
800
    def get_ancestry(self, revision_id, topo_sorted=True):
 
 
802
        return self._real_repository.get_ancestry(revision_id, topo_sorted)
 
 
804
    def fileids_altered_by_revision_ids(self, revision_ids):
 
 
806
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
 
 
808
    def _get_versioned_file_checker(self, revisions, revision_versions_cache):
 
 
810
        return self._real_repository._get_versioned_file_checker(
 
 
811
            revisions, revision_versions_cache)
 
 
813
    def iter_files_bytes(self, desired_files):
 
 
814
        """See Repository.iter_file_bytes.
 
 
817
        return self._real_repository.iter_files_bytes(desired_files)
 
 
820
    def _fetch_order(self):
 
 
821
        """Decorate the real repository for now.
 
 
823
        In the long term getting this back from the remote repository as part
 
 
824
        of open would be more efficient.
 
 
827
        return self._real_repository._fetch_order
 
 
830
    def _fetch_uses_deltas(self):
 
 
831
        """Decorate the real repository for now.
 
 
833
        In the long term getting this back from the remote repository as part
 
 
834
        of open would be more efficient.
 
 
837
        return self._real_repository._fetch_uses_deltas
 
 
840
    def _fetch_reconcile(self):
 
 
841
        """Decorate the real repository for now.
 
 
843
        In the long term getting this back from the remote repository as part
 
 
844
        of open would be more efficient.
 
 
847
        return self._real_repository._fetch_reconcile
 
 
849
    def get_parent_map(self, keys):
 
 
850
        """See bzrlib.Graph.get_parent_map()."""
 
 
851
        # Hack to build up the caching logic.
 
 
852
        ancestry = self._parents_map
 
 
854
            # Repository is not locked, so there's no cache.
 
 
855
            missing_revisions = set(keys)
 
 
858
            missing_revisions = set(key for key in keys if key not in ancestry)
 
 
859
        if missing_revisions:
 
 
860
            parent_map = self._get_parent_map(missing_revisions)
 
 
861
            if 'hpss' in debug.debug_flags:
 
 
862
                mutter('retransmitted revisions: %d of %d',
 
 
863
                        len(set(ancestry).intersection(parent_map)),
 
 
865
            ancestry.update(parent_map)
 
 
866
        present_keys = [k for k in keys if k in ancestry]
 
 
867
        if 'hpss' in debug.debug_flags:
 
 
868
            if self._requested_parents is not None and len(ancestry) != 0:
 
 
869
                self._requested_parents.update(present_keys)
 
 
870
                mutter('Current RemoteRepository graph hit rate: %d%%',
 
 
871
                    100.0 * len(self._requested_parents) / len(ancestry))
 
 
872
        return dict((k, ancestry[k]) for k in present_keys)
 
 
874
    def _get_parent_map(self, keys):
 
 
875
        """Helper for get_parent_map that performs the RPC."""
 
 
876
        medium = self._client._medium
 
 
877
        if medium._is_remote_before((1, 2)):
 
 
878
            # We already found out that the server can't understand
 
 
879
            # Repository.get_parent_map requests, so just fetch the whole
 
 
881
            # XXX: Note that this will issue a deprecation warning. This is ok
 
 
882
            # :- its because we're working with a deprecated server anyway, and
 
 
883
            # the user will almost certainly have seen a warning about the
 
 
884
            # server version already.
 
 
885
            rg = self.get_revision_graph()
 
 
886
            # There is an api discrepency between get_parent_map and
 
 
887
            # get_revision_graph. Specifically, a "key:()" pair in
 
 
888
            # get_revision_graph just means a node has no parents. For
 
 
889
            # "get_parent_map" it means the node is a ghost. So fix up the
 
 
890
            # graph to correct this.
 
 
891
            #   https://bugs.launchpad.net/bzr/+bug/214894
 
 
892
            # There is one other "bug" which is that ghosts in
 
 
893
            # get_revision_graph() are not returned at all. But we won't worry
 
 
894
            # about that for now.
 
 
895
            for node_id, parent_ids in rg.iteritems():
 
 
897
                    rg[node_id] = (NULL_REVISION,)
 
 
898
            rg[NULL_REVISION] = ()
 
 
903
            raise ValueError('get_parent_map(None) is not valid')
 
 
904
        if NULL_REVISION in keys:
 
 
905
            keys.discard(NULL_REVISION)
 
 
906
            found_parents = {NULL_REVISION:()}
 
 
911
        # TODO(Needs analysis): We could assume that the keys being requested
 
 
912
        # from get_parent_map are in a breadth first search, so typically they
 
 
913
        # will all be depth N from some common parent, and we don't have to
 
 
914
        # have the server iterate from the root parent, but rather from the
 
 
915
        # keys we're searching; and just tell the server the keyspace we
 
 
916
        # already have; but this may be more traffic again.
 
 
918
        # Transform self._parents_map into a search request recipe.
 
 
919
        # TODO: Manage this incrementally to avoid covering the same path
 
 
920
        # repeatedly. (The server will have to on each request, but the less
 
 
921
        # work done the better).
 
 
922
        parents_map = self._parents_map
 
 
923
        if parents_map is None:
 
 
924
            # Repository is not locked, so there's no cache.
 
 
926
        start_set = set(parents_map)
 
 
927
        result_parents = set()
 
 
928
        for parents in parents_map.itervalues():
 
 
929
            result_parents.update(parents)
 
 
930
        stop_keys = result_parents.difference(start_set)
 
 
931
        included_keys = start_set.intersection(result_parents)
 
 
932
        start_set.difference_update(included_keys)
 
 
933
        recipe = (start_set, stop_keys, len(parents_map))
 
 
934
        body = self._serialise_search_recipe(recipe)
 
 
935
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
937
            if type(key) is not str:
 
 
939
                    "key %r not a plain string" % (key,))
 
 
940
        verb = 'Repository.get_parent_map'
 
 
941
        args = (path,) + tuple(keys)
 
 
943
            response = self._client.call_with_body_bytes_expecting_body(
 
 
944
                verb, args, self._serialise_search_recipe(recipe))
 
 
945
        except errors.UnknownSmartMethod:
 
 
946
            # Server does not support this method, so get the whole graph.
 
 
947
            # Worse, we have to force a disconnection, because the server now
 
 
948
            # doesn't realise it has a body on the wire to consume, so the
 
 
949
            # only way to recover is to abandon the connection.
 
 
951
                'Server is too old for fast get_parent_map, reconnecting.  '
 
 
952
                '(Upgrade the server to Bazaar 1.2 to avoid this)')
 
 
954
            # To avoid having to disconnect repeatedly, we keep track of the
 
 
955
            # fact the server doesn't understand remote methods added in 1.2.
 
 
956
            medium._remember_remote_is_before((1, 2))
 
 
957
            return self.get_revision_graph(None)
 
 
958
        response_tuple, response_handler = response
 
 
959
        if response_tuple[0] not in ['ok']:
 
 
960
            response_handler.cancel_read_body()
 
 
961
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
 
962
        if response_tuple[0] == 'ok':
 
 
963
            coded = bz2.decompress(response_handler.read_body_bytes())
 
 
967
            lines = coded.split('\n')
 
 
970
                d = tuple(line.split())
 
 
972
                    revision_graph[d[0]] = d[1:]
 
 
974
                    # No parents - so give the Graph result (NULL_REVISION,).
 
 
975
                    revision_graph[d[0]] = (NULL_REVISION,)
 
 
976
            return revision_graph
 
 
979
    def get_signature_text(self, revision_id):
 
 
981
        return self._real_repository.get_signature_text(revision_id)
 
 
984
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
 
 
985
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
 
987
        return self._real_repository.get_revision_graph_with_ghosts(
 
 
988
            revision_ids=revision_ids)
 
 
991
    def get_inventory_xml(self, revision_id):
 
 
993
        return self._real_repository.get_inventory_xml(revision_id)
 
 
995
    def deserialise_inventory(self, revision_id, xml):
 
 
997
        return self._real_repository.deserialise_inventory(revision_id, xml)
 
 
999
    def reconcile(self, other=None, thorough=False):
 
 
1001
        return self._real_repository.reconcile(other=other, thorough=thorough)
 
 
1003
    def all_revision_ids(self):
 
 
1005
        return self._real_repository.all_revision_ids()
 
 
1008
    def get_deltas_for_revisions(self, revisions):
 
 
1010
        return self._real_repository.get_deltas_for_revisions(revisions)
 
 
1013
    def get_revision_delta(self, revision_id):
 
 
1015
        return self._real_repository.get_revision_delta(revision_id)
 
 
1018
    def revision_trees(self, revision_ids):
 
 
1020
        return self._real_repository.revision_trees(revision_ids)
 
 
1023
    def get_revision_reconcile(self, revision_id):
 
 
1025
        return self._real_repository.get_revision_reconcile(revision_id)
 
 
1028
    def check(self, revision_ids=None):
 
 
1030
        return self._real_repository.check(revision_ids=revision_ids)
 
 
1032
    def copy_content_into(self, destination, revision_id=None):
 
 
1034
        return self._real_repository.copy_content_into(
 
 
1035
            destination, revision_id=revision_id)
 
 
1037
    def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
 
 
1038
        # get a tarball of the remote repository, and copy from that into the
 
 
1040
        from bzrlib import osutils
 
 
1043
        # TODO: Maybe a progress bar while streaming the tarball?
 
 
1044
        note("Copying repository content as tarball...")
 
 
1045
        tar_file = self._get_tarball('bz2')
 
 
1046
        if tar_file is None:
 
 
1048
        destination = to_bzrdir.create_repository()
 
 
1050
            tar = tarfile.open('repository', fileobj=tar_file,
 
 
1052
            tmpdir = tempfile.mkdtemp()
 
 
1054
                _extract_tar(tar, tmpdir)
 
 
1055
                tmp_bzrdir = BzrDir.open(tmpdir)
 
 
1056
                tmp_repo = tmp_bzrdir.open_repository()
 
 
1057
                tmp_repo.copy_content_into(destination, revision_id)
 
 
1059
                osutils.rmtree(tmpdir)
 
 
1063
        # TODO: Suggestion from john: using external tar is much faster than
 
 
1064
        # python's tarfile library, but it may not work on windows.
 
 
1067
    def inventories(self):
 
 
1068
        """Decorate the real repository for now.
 
 
1070
        In the long term a full blown network facility is needed to
 
 
1071
        avoid creating a real repository object locally.
 
 
1074
        return self._real_repository.inventories
 
 
1078
        """Compress the data within the repository.
 
 
1080
        This is not currently implemented within the smart server.
 
 
1083
        return self._real_repository.pack()
 
 
1086
    def revisions(self):
 
 
1087
        """Decorate the real repository for now.
 
 
1089
        In the short term this should become a real object to intercept graph
 
 
1092
        In the long term a full blown network facility is needed.
 
 
1095
        return self._real_repository.revisions
 
 
1097
    def set_make_working_trees(self, new_value):
 
 
1099
        self._real_repository.set_make_working_trees(new_value)
 
 
1102
    def signatures(self):
 
 
1103
        """Decorate the real repository for now.
 
 
1105
        In the long term a full blown network facility is needed to avoid
 
 
1106
        creating a real repository object locally.
 
 
1109
        return self._real_repository.signatures
 
 
1112
    def sign_revision(self, revision_id, gpg_strategy):
 
 
1114
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
 
 
1118
        """Decorate the real repository for now.
 
 
1120
        In the long term a full blown network facility is needed to avoid
 
 
1121
        creating a real repository object locally.
 
 
1124
        return self._real_repository.texts
 
 
1127
    def get_revisions(self, revision_ids):
 
 
1129
        return self._real_repository.get_revisions(revision_ids)
 
 
1131
    def supports_rich_root(self):
 
 
1133
        return self._real_repository.supports_rich_root()
 
 
1135
    def iter_reverse_revision_history(self, revision_id):
 
 
1137
        return self._real_repository.iter_reverse_revision_history(revision_id)
 
 
1140
    def _serializer(self):
 
 
1142
        return self._real_repository._serializer
 
 
1144
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
 
 
1146
        return self._real_repository.store_revision_signature(
 
 
1147
            gpg_strategy, plaintext, revision_id)
 
 
1149
    def add_signature_text(self, revision_id, signature):
 
 
1151
        return self._real_repository.add_signature_text(revision_id, signature)
 
 
1153
    def has_signature_for_revision_id(self, revision_id):
 
 
1155
        return self._real_repository.has_signature_for_revision_id(revision_id)
 
 
1157
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
 
 
1159
        return self._real_repository.item_keys_introduced_by(revision_ids,
 
 
1160
            _files_pb=_files_pb)
 
 
1162
    def revision_graph_can_have_wrong_parents(self):
 
 
1163
        # The answer depends on the remote repo format.
 
 
1165
        return self._real_repository.revision_graph_can_have_wrong_parents()
 
 
1167
    def _find_inconsistent_revision_parents(self):
 
 
1169
        return self._real_repository._find_inconsistent_revision_parents()
 
 
1171
    def _check_for_inconsistent_revision_parents(self):
 
 
1173
        return self._real_repository._check_for_inconsistent_revision_parents()
 
 
1175
    def _make_parents_provider(self):
 
 
1178
    def _serialise_search_recipe(self, recipe):
 
 
1179
        """Serialise a graph search recipe.
 
 
1181
        :param recipe: A search recipe (start, stop, count).
 
 
1182
        :return: Serialised bytes.
 
 
1184
        start_keys = ' '.join(recipe[0])
 
 
1185
        stop_keys = ' '.join(recipe[1])
 
 
1186
        count = str(recipe[2])
 
 
1187
        return '\n'.join((start_keys, stop_keys, count))
 
 
1190
class RemoteBranchLockableFiles(LockableFiles):
 
 
1191
    """A 'LockableFiles' implementation that talks to a smart server.
 
 
1193
    This is not a public interface class.
 
 
1196
    def __init__(self, bzrdir, _client):
 
 
1197
        self.bzrdir = bzrdir
 
 
1198
        self._client = _client
 
 
1199
        self._need_find_modes = True
 
 
1200
        LockableFiles.__init__(
 
 
1201
            self, bzrdir.get_branch_transport(None),
 
 
1202
            'lock', lockdir.LockDir)
 
 
1204
    def _find_modes(self):
 
 
1205
        # RemoteBranches don't let the client set the mode of control files.
 
 
1206
        self._dir_mode = None
 
 
1207
        self._file_mode = None
 
 
1210
class RemoteBranchFormat(branch.BranchFormat):
 
 
1212
    def __eq__(self, other):
 
 
1213
        return (isinstance(other, RemoteBranchFormat) and 
 
 
1214
            self.__dict__ == other.__dict__)
 
 
1216
    def get_format_description(self):
 
 
1217
        return 'Remote BZR Branch'
 
 
1219
    def get_format_string(self):
 
 
1220
        return 'Remote BZR Branch'
 
 
1222
    def open(self, a_bzrdir):
 
 
1223
        return a_bzrdir.open_branch()
 
 
1225
    def initialize(self, a_bzrdir):
 
 
1226
        return a_bzrdir.create_branch()
 
 
1228
    def supports_tags(self):
 
 
1229
        # Remote branches might support tags, but we won't know until we
 
 
1230
        # access the real remote branch.
 
 
1234
class RemoteBranch(branch.Branch):
 
 
1235
    """Branch stored on a server accessed by HPSS RPC.
 
 
1237
    At the moment most operations are mapped down to simple file operations.
 
 
1240
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
 
 
1242
        """Create a RemoteBranch instance.
 
 
1244
        :param real_branch: An optional local implementation of the branch
 
 
1245
            format, usually accessing the data via the VFS.
 
 
1246
        :param _client: Private parameter for testing.
 
 
1248
        # We intentionally don't call the parent class's __init__, because it
 
 
1249
        # will try to assign to self.tags, which is a property in this subclass.
 
 
1250
        # And the parent's __init__ doesn't do much anyway.
 
 
1251
        self._revision_id_to_revno_cache = None
 
 
1252
        self._revision_history_cache = None
 
 
1253
        self._last_revision_info_cache = None
 
 
1254
        self.bzrdir = remote_bzrdir
 
 
1255
        if _client is not None:
 
 
1256
            self._client = _client
 
 
1258
            self._client = remote_bzrdir._client
 
 
1259
        self.repository = remote_repository
 
 
1260
        if real_branch is not None:
 
 
1261
            self._real_branch = real_branch
 
 
1262
            # Give the remote repository the matching real repo.
 
 
1263
            real_repo = self._real_branch.repository
 
 
1264
            if isinstance(real_repo, RemoteRepository):
 
 
1265
                real_repo._ensure_real()
 
 
1266
                real_repo = real_repo._real_repository
 
 
1267
            self.repository._set_real_repository(real_repo)
 
 
1268
            # Give the branch the remote repository to let fast-pathing happen.
 
 
1269
            self._real_branch.repository = self.repository
 
 
1271
            self._real_branch = None
 
 
1272
        # Fill out expected attributes of branch for bzrlib api users.
 
 
1273
        self._format = RemoteBranchFormat()
 
 
1274
        self.base = self.bzrdir.root_transport.base
 
 
1275
        self._control_files = None
 
 
1276
        self._lock_mode = None
 
 
1277
        self._lock_token = None
 
 
1278
        self._repo_lock_token = None
 
 
1279
        self._lock_count = 0
 
 
1280
        self._leave_lock = False
 
 
1282
    def _get_real_transport(self):
 
 
1283
        # if we try vfs access, return the real branch's vfs transport
 
 
1285
        return self._real_branch._transport
 
 
1287
    _transport = property(_get_real_transport)
 
 
1290
        return "%s(%s)" % (self.__class__.__name__, self.base)
 
 
1294
    def _ensure_real(self):
 
 
1295
        """Ensure that there is a _real_branch set.
 
 
1297
        Used before calls to self._real_branch.
 
 
1299
        if self._real_branch is None:
 
 
1300
            if not vfs.vfs_enabled():
 
 
1301
                raise AssertionError('smart server vfs must be enabled '
 
 
1302
                    'to use vfs implementation')
 
 
1303
            self.bzrdir._ensure_real()
 
 
1304
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
 
 
1305
            # Give the remote repository the matching real repo.
 
 
1306
            real_repo = self._real_branch.repository
 
 
1307
            if isinstance(real_repo, RemoteRepository):
 
 
1308
                real_repo._ensure_real()
 
 
1309
                real_repo = real_repo._real_repository
 
 
1310
            self.repository._set_real_repository(real_repo)
 
 
1311
            # Give the branch the remote repository to let fast-pathing happen.
 
 
1312
            self._real_branch.repository = self.repository
 
 
1313
            # XXX: deal with _lock_mode == 'w'
 
 
1314
            if self._lock_mode == 'r':
 
 
1315
                self._real_branch.lock_read()
 
 
1317
    def _translate_error(self, err, **context):
 
 
1318
        self.repository._translate_error(err, branch=self, **context)
 
 
1320
    def _clear_cached_state(self):
 
 
1321
        super(RemoteBranch, self)._clear_cached_state()
 
 
1322
        if self._real_branch is not None:
 
 
1323
            self._real_branch._clear_cached_state()
 
 
1325
    def _clear_cached_state_of_remote_branch_only(self):
 
 
1326
        """Like _clear_cached_state, but doesn't clear the cache of
 
 
1329
        This is useful when falling back to calling a method of
 
 
1330
        self._real_branch that changes state.  In that case the underlying
 
 
1331
        branch changes, so we need to invalidate this RemoteBranch's cache of
 
 
1332
        it.  However, there's no need to invalidate the _real_branch's cache
 
 
1333
        too, in fact doing so might harm performance.
 
 
1335
        super(RemoteBranch, self)._clear_cached_state()
 
 
1338
    def control_files(self):
 
 
1339
        # Defer actually creating RemoteBranchLockableFiles until its needed,
 
 
1340
        # because it triggers an _ensure_real that we otherwise might not need.
 
 
1341
        if self._control_files is None:
 
 
1342
            self._control_files = RemoteBranchLockableFiles(
 
 
1343
                self.bzrdir, self._client)
 
 
1344
        return self._control_files
 
 
1346
    def _get_checkout_format(self):
 
 
1348
        return self._real_branch._get_checkout_format()
 
 
1350
    def get_physical_lock_status(self):
 
 
1351
        """See Branch.get_physical_lock_status()."""
 
 
1352
        # should be an API call to the server, as branches must be lockable.
 
 
1354
        return self._real_branch.get_physical_lock_status()
 
 
1356
    def get_stacked_on_url(self):
 
 
1357
        """Get the URL this branch is stacked against.
 
 
1359
        :raises NotStacked: If the branch is not stacked.
 
 
1360
        :raises UnstackableBranchFormat: If the branch does not support
 
 
1362
        :raises UnstackableRepositoryFormat: If the repository does not support
 
 
1366
        return self._real_branch.get_stacked_on_url()
 
 
1368
    def lock_read(self):
 
 
1369
        if not self._lock_mode:
 
 
1370
            self._lock_mode = 'r'
 
 
1371
            self._lock_count = 1
 
 
1372
            if self._real_branch is not None:
 
 
1373
                self._real_branch.lock_read()
 
 
1375
            self._lock_count += 1
 
 
1377
    def _remote_lock_write(self, token):
 
 
1379
            branch_token = repo_token = ''
 
 
1381
            branch_token = token
 
 
1382
            repo_token = self.repository.lock_write()
 
 
1383
            self.repository.unlock()
 
 
1384
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1386
            response = self._client.call(
 
 
1387
                'Branch.lock_write', path, branch_token, repo_token or '')
 
 
1388
        except errors.ErrorFromSmartServer, err:
 
 
1389
            self._translate_error(err, token=token)
 
 
1390
        if response[0] != 'ok':
 
 
1391
            raise errors.UnexpectedSmartServerResponse(response)
 
 
1392
        ok, branch_token, repo_token = response
 
 
1393
        return branch_token, repo_token
 
 
1395
    def lock_write(self, token=None):
 
 
1396
        if not self._lock_mode:
 
 
1397
            remote_tokens = self._remote_lock_write(token)
 
 
1398
            self._lock_token, self._repo_lock_token = remote_tokens
 
 
1399
            if not self._lock_token:
 
 
1400
                raise SmartProtocolError('Remote server did not return a token!')
 
 
1401
            # TODO: We really, really, really don't want to call _ensure_real
 
 
1402
            # here, but it's the easiest way to ensure coherency between the
 
 
1403
            # state of the RemoteBranch and RemoteRepository objects and the
 
 
1404
            # physical locks.  If we don't materialise the real objects here,
 
 
1405
            # then getting everything in the right state later is complex, so
 
 
1406
            # for now we just do it the lazy way.
 
 
1407
            #   -- Andrew Bennetts, 2007-02-22.
 
 
1409
            if self._real_branch is not None:
 
 
1410
                self._real_branch.repository.lock_write(
 
 
1411
                    token=self._repo_lock_token)
 
 
1413
                    self._real_branch.lock_write(token=self._lock_token)
 
 
1415
                    self._real_branch.repository.unlock()
 
 
1416
            if token is not None:
 
 
1417
                self._leave_lock = True
 
 
1419
                # XXX: this case seems to be unreachable; token cannot be None.
 
 
1420
                self._leave_lock = False
 
 
1421
            self._lock_mode = 'w'
 
 
1422
            self._lock_count = 1
 
 
1423
        elif self._lock_mode == 'r':
 
 
1424
            raise errors.ReadOnlyTransaction
 
 
1426
            if token is not None:
 
 
1427
                # A token was given to lock_write, and we're relocking, so check
 
 
1428
                # that the given token actually matches the one we already have.
 
 
1429
                if token != self._lock_token:
 
 
1430
                    raise errors.TokenMismatch(token, self._lock_token)
 
 
1431
            self._lock_count += 1
 
 
1432
        return self._lock_token or None
 
 
1434
    def _unlock(self, branch_token, repo_token):
 
 
1435
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1437
            response = self._client.call('Branch.unlock', path, branch_token,
 
 
1439
        except errors.ErrorFromSmartServer, err:
 
 
1440
            self._translate_error(err, token=str((branch_token, repo_token)))
 
 
1441
        if response == ('ok',):
 
 
1443
        raise errors.UnexpectedSmartServerResponse(response)
 
 
1446
        self._lock_count -= 1
 
 
1447
        if not self._lock_count:
 
 
1448
            self._clear_cached_state()
 
 
1449
            mode = self._lock_mode
 
 
1450
            self._lock_mode = None
 
 
1451
            if self._real_branch is not None:
 
 
1452
                if (not self._leave_lock and mode == 'w' and
 
 
1453
                    self._repo_lock_token):
 
 
1454
                    # If this RemoteBranch will remove the physical lock for the
 
 
1455
                    # repository, make sure the _real_branch doesn't do it
 
 
1456
                    # first.  (Because the _real_branch's repository is set to
 
 
1457
                    # be the RemoteRepository.)
 
 
1458
                    self._real_branch.repository.leave_lock_in_place()
 
 
1459
                self._real_branch.unlock()
 
 
1461
                # Only write-locked branched need to make a remote method call
 
 
1462
                # to perfom the unlock.
 
 
1464
            if not self._lock_token:
 
 
1465
                raise AssertionError('Locked, but no token!')
 
 
1466
            branch_token = self._lock_token
 
 
1467
            repo_token = self._repo_lock_token
 
 
1468
            self._lock_token = None
 
 
1469
            self._repo_lock_token = None
 
 
1470
            if not self._leave_lock:
 
 
1471
                self._unlock(branch_token, repo_token)
 
 
1473
    def break_lock(self):
 
 
1475
        return self._real_branch.break_lock()
 
 
1477
    def leave_lock_in_place(self):
 
 
1478
        if not self._lock_token:
 
 
1479
            raise NotImplementedError(self.leave_lock_in_place)
 
 
1480
        self._leave_lock = True
 
 
1482
    def dont_leave_lock_in_place(self):
 
 
1483
        if not self._lock_token:
 
 
1484
            raise NotImplementedError(self.dont_leave_lock_in_place)
 
 
1485
        self._leave_lock = False
 
 
1487
    def _last_revision_info(self):
 
 
1488
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1489
        response = self._client.call('Branch.last_revision_info', path)
 
 
1490
        if response[0] != 'ok':
 
 
1491
            raise SmartProtocolError('unexpected response code %s' % (response,))
 
 
1492
        revno = int(response[1])
 
 
1493
        last_revision = response[2]
 
 
1494
        return (revno, last_revision)
 
 
1496
    def _gen_revision_history(self):
 
 
1497
        """See Branch._gen_revision_history()."""
 
 
1498
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1499
        response_tuple, response_handler = self._client.call_expecting_body(
 
 
1500
            'Branch.revision_history', path)
 
 
1501
        if response_tuple[0] != 'ok':
 
 
1502
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
 
1503
        result = response_handler.read_body_bytes().split('\x00')
 
 
1508
    def _set_last_revision_descendant(self, revision_id, other_branch,
 
 
1509
            allow_diverged=False, allow_overwrite_descendant=False):
 
 
1510
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1512
            response = self._client.call('Branch.set_last_revision_ex',
 
 
1513
                path, self._lock_token, self._repo_lock_token, revision_id,
 
 
1514
                int(allow_diverged), int(allow_overwrite_descendant))
 
 
1515
        except errors.ErrorFromSmartServer, err:
 
 
1516
            self._translate_error(err, other_branch=other_branch)
 
 
1517
        self._clear_cached_state()
 
 
1518
        if len(response) != 3 and response[0] != 'ok':
 
 
1519
            raise errors.UnexpectedSmartServerResponse(response)
 
 
1520
        new_revno, new_revision_id = response[1:]
 
 
1521
        self._last_revision_info_cache = new_revno, new_revision_id
 
 
1522
        self._real_branch._last_revision_info_cache = new_revno, new_revision_id
 
 
1524
    def _set_last_revision(self, revision_id):
 
 
1525
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1526
        self._clear_cached_state()
 
 
1528
            response = self._client.call('Branch.set_last_revision',
 
 
1529
                path, self._lock_token, self._repo_lock_token, revision_id)
 
 
1530
        except errors.ErrorFromSmartServer, err:
 
 
1531
            self._translate_error(err)
 
 
1532
        if response != ('ok',):
 
 
1533
            raise errors.UnexpectedSmartServerResponse(response)
 
 
1536
    def set_revision_history(self, rev_history):
 
 
1537
        # Send just the tip revision of the history; the server will generate
 
 
1538
        # the full history from that.  If the revision doesn't exist in this
 
 
1539
        # branch, NoSuchRevision will be raised.
 
 
1540
        if rev_history == []:
 
 
1543
            rev_id = rev_history[-1]
 
 
1544
        self._set_last_revision(rev_id)
 
 
1545
        self._cache_revision_history(rev_history)
 
 
1547
    def get_parent(self):
 
 
1549
        return self._real_branch.get_parent()
 
 
1551
    def set_parent(self, url):
 
 
1553
        return self._real_branch.set_parent(url)
 
 
1555
    def set_stacked_on_url(self, stacked_location):
 
 
1556
        """Set the URL this branch is stacked against.
 
 
1558
        :raises UnstackableBranchFormat: If the branch does not support
 
 
1560
        :raises UnstackableRepositoryFormat: If the repository does not support
 
 
1564
        return self._real_branch.set_stacked_on_url(stacked_location)
 
 
1566
    def sprout(self, to_bzrdir, revision_id=None):
 
 
1567
        # Like Branch.sprout, except that it sprouts a branch in the default
 
 
1568
        # format, because RemoteBranches can't be created at arbitrary URLs.
 
 
1569
        # XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
 
 
1570
        # to_bzrdir.create_branch...
 
 
1572
        result = self._real_branch._format.initialize(to_bzrdir)
 
 
1573
        self.copy_content_into(result, revision_id=revision_id)
 
 
1574
        result.set_parent(self.bzrdir.root_transport.base)
 
 
1578
    def pull(self, source, overwrite=False, stop_revision=None,
 
 
1580
        self._clear_cached_state_of_remote_branch_only()
 
 
1582
        return self._real_branch.pull(
 
 
1583
            source, overwrite=overwrite, stop_revision=stop_revision,
 
 
1584
            _override_hook_target=self, **kwargs)
 
 
1587
    def push(self, target, overwrite=False, stop_revision=None):
 
 
1589
        return self._real_branch.push(
 
 
1590
            target, overwrite=overwrite, stop_revision=stop_revision,
 
 
1591
            _override_hook_source_branch=self)
 
 
1593
    def is_locked(self):
 
 
1594
        return self._lock_count >= 1
 
 
1597
    def revision_id_to_revno(self, revision_id):
 
 
1599
        return self._real_branch.revision_id_to_revno(revision_id)
 
 
1602
    def set_last_revision_info(self, revno, revision_id):
 
 
1603
        revision_id = ensure_null(revision_id)
 
 
1604
        path = self.bzrdir._path_for_remote_call(self._client)
 
 
1606
            response = self._client.call('Branch.set_last_revision_info',
 
 
1607
                path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
 
 
1608
        except errors.UnknownSmartMethod:
 
 
1610
            self._clear_cached_state_of_remote_branch_only()
 
 
1611
            self._real_branch.set_last_revision_info(revno, revision_id)
 
 
1612
            self._last_revision_info_cache = revno, revision_id
 
 
1614
        except errors.ErrorFromSmartServer, err:
 
 
1615
            self._translate_error(err)
 
 
1616
        if response == ('ok',):
 
 
1617
            self._clear_cached_state()
 
 
1618
            self._last_revision_info_cache = revno, revision_id
 
 
1619
            # Update the _real_branch's cache too.
 
 
1620
            if self._real_branch is not None:
 
 
1621
                cache = self._last_revision_info_cache
 
 
1622
                self._real_branch._last_revision_info_cache = cache
 
 
1624
            raise errors.UnexpectedSmartServerResponse(response)
 
 
1627
    def generate_revision_history(self, revision_id, last_rev=None,
 
 
1629
        medium = self._client._medium
 
 
1630
        if not medium._is_remote_before((1, 6)):
 
 
1632
                self._set_last_revision_descendant(revision_id, other_branch,
 
 
1633
                    allow_diverged=True, allow_overwrite_descendant=True)
 
 
1635
            except errors.UnknownSmartMethod:
 
 
1636
                medium._remember_remote_is_before((1, 6))
 
 
1637
        self._clear_cached_state_of_remote_branch_only()
 
 
1639
        self._real_branch.generate_revision_history(
 
 
1640
            revision_id, last_rev=last_rev, other_branch=other_branch)
 
 
1645
        return self._real_branch.tags
 
 
1647
    def set_push_location(self, location):
 
 
1649
        return self._real_branch.set_push_location(location)
 
 
1652
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
 
1654
        """See Branch.update_revisions."""
 
 
1657
            if stop_revision is None:
 
 
1658
                stop_revision = other.last_revision()
 
 
1659
                if revision.is_null(stop_revision):
 
 
1660
                    # if there are no commits, we're done.
 
 
1662
            self.fetch(other, stop_revision)
 
 
1665
                # Just unconditionally set the new revision.  We don't care if
 
 
1666
                # the branches have diverged.
 
 
1667
                self._set_last_revision(stop_revision)
 
 
1669
                medium = self._client._medium
 
 
1670
                if not medium._is_remote_before((1, 6)):
 
 
1672
                        self._set_last_revision_descendant(stop_revision, other)
 
 
1674
                    except errors.UnknownSmartMethod:
 
 
1675
                        medium._remember_remote_is_before((1, 6))
 
 
1676
                # Fallback for pre-1.6 servers: check for divergence
 
 
1677
                # client-side, then do _set_last_revision.
 
 
1678
                last_rev = revision.ensure_null(self.last_revision())
 
 
1680
                    graph = self.repository.get_graph()
 
 
1681
                if self._check_if_descendant_or_diverged(
 
 
1682
                        stop_revision, last_rev, graph, other):
 
 
1683
                    # stop_revision is a descendant of last_rev, but we aren't
 
 
1684
                    # overwriting, so we're done.
 
 
1686
                self._set_last_revision(stop_revision)
 
 
1691
def _extract_tar(tar, to_dir):
 
 
1692
    """Extract all the contents of a tarfile object.
 
 
1694
    A replacement for extractall, which is not present in python2.4
 
 
1697
        tar.extract(tarinfo, to_dir)
 
 
1700
def _translate_error(err, **context):
 
 
1701
    """Translate an ErrorFromSmartServer into a more useful error.
 
 
1703
    Possible context keys:
 
 
1712
            return context[name]
 
 
1713
        except KeyError, keyErr:
 
 
1714
            mutter('Missing key %r in context %r', keyErr.args[0], context)
 
 
1716
    if err.error_verb == 'NoSuchRevision':
 
 
1717
        raise NoSuchRevision(find('branch'), err.error_args[0])
 
 
1718
    elif err.error_verb == 'nosuchrevision':
 
 
1719
        raise NoSuchRevision(find('repository'), err.error_args[0])
 
 
1720
    elif err.error_tuple == ('nobranch',):
 
 
1721
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
 
 
1722
    elif err.error_verb == 'norepository':
 
 
1723
        raise errors.NoRepositoryPresent(find('bzrdir'))
 
 
1724
    elif err.error_verb == 'LockContention':
 
 
1725
        raise errors.LockContention('(remote lock)')
 
 
1726
    elif err.error_verb == 'UnlockableTransport':
 
 
1727
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
 
 
1728
    elif err.error_verb == 'LockFailed':
 
 
1729
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
 
 
1730
    elif err.error_verb == 'TokenMismatch':
 
 
1731
        raise errors.TokenMismatch(find('token'), '(remote token)')
 
 
1732
    elif err.error_verb == 'Diverged':
 
 
1733
        raise errors.DivergedBranches(find('branch'), find('other_branch'))
 
 
1734
    elif err.error_verb == 'TipChangeRejected':
 
 
1735
        raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))