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)
819
def get_parent_map(self, keys):
820
"""See bzrlib.Graph.get_parent_map()."""
821
# Hack to build up the caching logic.
822
ancestry = self._parents_map
824
# Repository is not locked, so there's no cache.
825
missing_revisions = set(keys)
828
missing_revisions = set(key for key in keys if key not in ancestry)
829
if missing_revisions:
830
parent_map = self._get_parent_map(missing_revisions)
831
if 'hpss' in debug.debug_flags:
832
mutter('retransmitted revisions: %d of %d',
833
len(set(ancestry).intersection(parent_map)),
835
ancestry.update(parent_map)
836
present_keys = [k for k in keys if k in ancestry]
837
if 'hpss' in debug.debug_flags:
838
if self._requested_parents is not None and len(ancestry) != 0:
839
self._requested_parents.update(present_keys)
840
mutter('Current RemoteRepository graph hit rate: %d%%',
841
100.0 * len(self._requested_parents) / len(ancestry))
842
return dict((k, ancestry[k]) for k in present_keys)
844
def _get_parent_map(self, keys):
845
"""Helper for get_parent_map that performs the RPC."""
846
medium = self._client._medium
847
if medium._is_remote_before((1, 2)):
848
# We already found out that the server can't understand
849
# Repository.get_parent_map requests, so just fetch the whole
851
# XXX: Note that this will issue a deprecation warning. This is ok
852
# :- its because we're working with a deprecated server anyway, and
853
# the user will almost certainly have seen a warning about the
854
# server version already.
855
rg = self.get_revision_graph()
856
# There is an api discrepency between get_parent_map and
857
# get_revision_graph. Specifically, a "key:()" pair in
858
# get_revision_graph just means a node has no parents. For
859
# "get_parent_map" it means the node is a ghost. So fix up the
860
# graph to correct this.
861
# https://bugs.launchpad.net/bzr/+bug/214894
862
# There is one other "bug" which is that ghosts in
863
# get_revision_graph() are not returned at all. But we won't worry
864
# about that for now.
865
for node_id, parent_ids in rg.iteritems():
867
rg[node_id] = (NULL_REVISION,)
868
rg[NULL_REVISION] = ()
873
raise ValueError('get_parent_map(None) is not valid')
874
if NULL_REVISION in keys:
875
keys.discard(NULL_REVISION)
876
found_parents = {NULL_REVISION:()}
881
# TODO(Needs analysis): We could assume that the keys being requested
882
# from get_parent_map are in a breadth first search, so typically they
883
# will all be depth N from some common parent, and we don't have to
884
# have the server iterate from the root parent, but rather from the
885
# keys we're searching; and just tell the server the keyspace we
886
# already have; but this may be more traffic again.
888
# Transform self._parents_map into a search request recipe.
889
# TODO: Manage this incrementally to avoid covering the same path
890
# repeatedly. (The server will have to on each request, but the less
891
# work done the better).
892
parents_map = self._parents_map
893
if parents_map is None:
894
# Repository is not locked, so there's no cache.
896
start_set = set(parents_map)
897
result_parents = set()
898
for parents in parents_map.itervalues():
899
result_parents.update(parents)
900
stop_keys = result_parents.difference(start_set)
901
included_keys = start_set.intersection(result_parents)
902
start_set.difference_update(included_keys)
903
recipe = (start_set, stop_keys, len(parents_map))
904
body = self._serialise_search_recipe(recipe)
905
path = self.bzrdir._path_for_remote_call(self._client)
907
if type(key) is not str:
909
"key %r not a plain string" % (key,))
910
verb = 'Repository.get_parent_map'
911
args = (path,) + tuple(keys)
913
response = self._client.call_with_body_bytes_expecting_body(
914
verb, args, self._serialise_search_recipe(recipe))
915
except errors.UnknownSmartMethod:
916
# Server does not support this method, so get the whole graph.
917
# Worse, we have to force a disconnection, because the server now
918
# doesn't realise it has a body on the wire to consume, so the
919
# only way to recover is to abandon the connection.
921
'Server is too old for fast get_parent_map, reconnecting. '
922
'(Upgrade the server to Bazaar 1.2 to avoid this)')
924
# To avoid having to disconnect repeatedly, we keep track of the
925
# fact the server doesn't understand remote methods added in 1.2.
926
medium._remember_remote_is_before((1, 2))
927
return self.get_revision_graph(None)
928
response_tuple, response_handler = response
929
if response_tuple[0] not in ['ok']:
930
response_handler.cancel_read_body()
931
raise errors.UnexpectedSmartServerResponse(response_tuple)
932
if response_tuple[0] == 'ok':
933
coded = bz2.decompress(response_handler.read_body_bytes())
937
lines = coded.split('\n')
940
d = tuple(line.split())
942
revision_graph[d[0]] = d[1:]
944
# No parents - so give the Graph result (NULL_REVISION,).
945
revision_graph[d[0]] = (NULL_REVISION,)
946
return revision_graph
949
def get_signature_text(self, revision_id):
951
return self._real_repository.get_signature_text(revision_id)
954
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
955
def get_revision_graph_with_ghosts(self, revision_ids=None):
957
return self._real_repository.get_revision_graph_with_ghosts(
958
revision_ids=revision_ids)
961
def get_inventory_xml(self, revision_id):
963
return self._real_repository.get_inventory_xml(revision_id)
965
def deserialise_inventory(self, revision_id, xml):
967
return self._real_repository.deserialise_inventory(revision_id, xml)
969
def reconcile(self, other=None, thorough=False):
971
return self._real_repository.reconcile(other=other, thorough=thorough)
973
def all_revision_ids(self):
975
return self._real_repository.all_revision_ids()
978
def get_deltas_for_revisions(self, revisions):
980
return self._real_repository.get_deltas_for_revisions(revisions)
983
def get_revision_delta(self, revision_id):
985
return self._real_repository.get_revision_delta(revision_id)
988
def revision_trees(self, revision_ids):
990
return self._real_repository.revision_trees(revision_ids)
993
def get_revision_reconcile(self, revision_id):
995
return self._real_repository.get_revision_reconcile(revision_id)
998
def check(self, revision_ids=None):
1000
return self._real_repository.check(revision_ids=revision_ids)
1002
def copy_content_into(self, destination, revision_id=None):
1004
return self._real_repository.copy_content_into(
1005
destination, revision_id=revision_id)
1007
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1008
# get a tarball of the remote repository, and copy from that into the
1010
from bzrlib import osutils
1013
# TODO: Maybe a progress bar while streaming the tarball?
1014
note("Copying repository content as tarball...")
1015
tar_file = self._get_tarball('bz2')
1016
if tar_file is None:
1018
destination = to_bzrdir.create_repository()
1020
tar = tarfile.open('repository', fileobj=tar_file,
1022
tmpdir = tempfile.mkdtemp()
1024
_extract_tar(tar, tmpdir)
1025
tmp_bzrdir = BzrDir.open(tmpdir)
1026
tmp_repo = tmp_bzrdir.open_repository()
1027
tmp_repo.copy_content_into(destination, revision_id)
1029
osutils.rmtree(tmpdir)
1033
# TODO: Suggestion from john: using external tar is much faster than
1034
# python's tarfile library, but it may not work on windows.
1037
def inventories(self):
1038
"""Decorate the real repository for now.
1040
In the long term a full blown network facility is needed to
1041
avoid creating a real repository object locally.
1044
return self._real_repository.inventories
1048
"""Compress the data within the repository.
1050
This is not currently implemented within the smart server.
1053
return self._real_repository.pack()
1056
def revisions(self):
1057
"""Decorate the real repository for now.
1059
In the short term this should become a real object to intercept graph
1062
In the long term a full blown network facility is needed.
1065
return self._real_repository.revisions
1067
def set_make_working_trees(self, new_value):
1069
self._real_repository.set_make_working_trees(new_value)
1072
def signatures(self):
1073
"""Decorate the real repository for now.
1075
In the long term a full blown network facility is needed to avoid
1076
creating a real repository object locally.
1079
return self._real_repository.signatures
1082
def sign_revision(self, revision_id, gpg_strategy):
1084
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1088
"""Decorate the real repository for now.
1090
In the long term a full blown network facility is needed to avoid
1091
creating a real repository object locally.
1094
return self._real_repository.texts
1097
def get_revisions(self, revision_ids):
1099
return self._real_repository.get_revisions(revision_ids)
1101
def supports_rich_root(self):
1103
return self._real_repository.supports_rich_root()
1105
def iter_reverse_revision_history(self, revision_id):
1107
return self._real_repository.iter_reverse_revision_history(revision_id)
1110
def _serializer(self):
1112
return self._real_repository._serializer
1114
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1116
return self._real_repository.store_revision_signature(
1117
gpg_strategy, plaintext, revision_id)
1119
def add_signature_text(self, revision_id, signature):
1121
return self._real_repository.add_signature_text(revision_id, signature)
1123
def has_signature_for_revision_id(self, revision_id):
1125
return self._real_repository.has_signature_for_revision_id(revision_id)
1127
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1129
return self._real_repository.item_keys_introduced_by(revision_ids,
1130
_files_pb=_files_pb)
1132
def revision_graph_can_have_wrong_parents(self):
1133
# The answer depends on the remote repo format.
1135
return self._real_repository.revision_graph_can_have_wrong_parents()
1137
def _find_inconsistent_revision_parents(self):
1139
return self._real_repository._find_inconsistent_revision_parents()
1141
def _check_for_inconsistent_revision_parents(self):
1143
return self._real_repository._check_for_inconsistent_revision_parents()
1145
def _make_parents_provider(self):
1148
def _serialise_search_recipe(self, recipe):
1149
"""Serialise a graph search recipe.
1151
:param recipe: A search recipe (start, stop, count).
1152
:return: Serialised bytes.
1154
start_keys = ' '.join(recipe[0])
1155
stop_keys = ' '.join(recipe[1])
1156
count = str(recipe[2])
1157
return '\n'.join((start_keys, stop_keys, count))
1160
class RemoteBranchLockableFiles(LockableFiles):
1161
"""A 'LockableFiles' implementation that talks to a smart server.
1163
This is not a public interface class.
1166
def __init__(self, bzrdir, _client):
1167
self.bzrdir = bzrdir
1168
self._client = _client
1169
self._need_find_modes = True
1170
LockableFiles.__init__(
1171
self, bzrdir.get_branch_transport(None),
1172
'lock', lockdir.LockDir)
1174
def _find_modes(self):
1175
# RemoteBranches don't let the client set the mode of control files.
1176
self._dir_mode = None
1177
self._file_mode = None
1180
class RemoteBranchFormat(branch.BranchFormat):
1182
def __eq__(self, other):
1183
return (isinstance(other, RemoteBranchFormat) and
1184
self.__dict__ == other.__dict__)
1186
def get_format_description(self):
1187
return 'Remote BZR Branch'
1189
def get_format_string(self):
1190
return 'Remote BZR Branch'
1192
def open(self, a_bzrdir):
1193
return a_bzrdir.open_branch()
1195
def initialize(self, a_bzrdir):
1196
return a_bzrdir.create_branch()
1198
def supports_tags(self):
1199
# Remote branches might support tags, but we won't know until we
1200
# access the real remote branch.
1204
class RemoteBranch(branch.Branch):
1205
"""Branch stored on a server accessed by HPSS RPC.
1207
At the moment most operations are mapped down to simple file operations.
1210
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1212
"""Create a RemoteBranch instance.
1214
:param real_branch: An optional local implementation of the branch
1215
format, usually accessing the data via the VFS.
1216
:param _client: Private parameter for testing.
1218
# We intentionally don't call the parent class's __init__, because it
1219
# will try to assign to self.tags, which is a property in this subclass.
1220
# And the parent's __init__ doesn't do much anyway.
1221
self._revision_id_to_revno_cache = None
1222
self._revision_history_cache = None
1223
self._last_revision_info_cache = None
1224
self.bzrdir = remote_bzrdir
1225
if _client is not None:
1226
self._client = _client
1228
self._client = remote_bzrdir._client
1229
self.repository = remote_repository
1230
if real_branch is not None:
1231
self._real_branch = real_branch
1232
# Give the remote repository the matching real repo.
1233
real_repo = self._real_branch.repository
1234
if isinstance(real_repo, RemoteRepository):
1235
real_repo._ensure_real()
1236
real_repo = real_repo._real_repository
1237
self.repository._set_real_repository(real_repo)
1238
# Give the branch the remote repository to let fast-pathing happen.
1239
self._real_branch.repository = self.repository
1241
self._real_branch = None
1242
# Fill out expected attributes of branch for bzrlib api users.
1243
self._format = RemoteBranchFormat()
1244
self.base = self.bzrdir.root_transport.base
1245
self._control_files = None
1246
self._lock_mode = None
1247
self._lock_token = None
1248
self._repo_lock_token = None
1249
self._lock_count = 0
1250
self._leave_lock = False
1252
def _get_real_transport(self):
1253
# if we try vfs access, return the real branch's vfs transport
1255
return self._real_branch._transport
1257
_transport = property(_get_real_transport)
1260
return "%s(%s)" % (self.__class__.__name__, self.base)
1264
def _ensure_real(self):
1265
"""Ensure that there is a _real_branch set.
1267
Used before calls to self._real_branch.
1269
if self._real_branch is None:
1270
if not vfs.vfs_enabled():
1271
raise AssertionError('smart server vfs must be enabled '
1272
'to use vfs implementation')
1273
self.bzrdir._ensure_real()
1274
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1275
# Give the remote repository the matching real repo.
1276
real_repo = self._real_branch.repository
1277
if isinstance(real_repo, RemoteRepository):
1278
real_repo._ensure_real()
1279
real_repo = real_repo._real_repository
1280
self.repository._set_real_repository(real_repo)
1281
# Give the branch the remote repository to let fast-pathing happen.
1282
self._real_branch.repository = self.repository
1283
# XXX: deal with _lock_mode == 'w'
1284
if self._lock_mode == 'r':
1285
self._real_branch.lock_read()
1287
def _translate_error(self, err, **context):
1288
self.repository._translate_error(err, branch=self, **context)
1290
def _clear_cached_state(self):
1291
super(RemoteBranch, self)._clear_cached_state()
1292
if self._real_branch is not None:
1293
self._real_branch._clear_cached_state()
1295
def _clear_cached_state_of_remote_branch_only(self):
1296
"""Like _clear_cached_state, but doesn't clear the cache of
1299
This is useful when falling back to calling a method of
1300
self._real_branch that changes state. In that case the underlying
1301
branch changes, so we need to invalidate this RemoteBranch's cache of
1302
it. However, there's no need to invalidate the _real_branch's cache
1303
too, in fact doing so might harm performance.
1305
super(RemoteBranch, self)._clear_cached_state()
1308
def control_files(self):
1309
# Defer actually creating RemoteBranchLockableFiles until its needed,
1310
# because it triggers an _ensure_real that we otherwise might not need.
1311
if self._control_files is None:
1312
self._control_files = RemoteBranchLockableFiles(
1313
self.bzrdir, self._client)
1314
return self._control_files
1316
def _get_checkout_format(self):
1318
return self._real_branch._get_checkout_format()
1320
def get_physical_lock_status(self):
1321
"""See Branch.get_physical_lock_status()."""
1322
# should be an API call to the server, as branches must be lockable.
1324
return self._real_branch.get_physical_lock_status()
1326
def get_stacked_on_url(self):
1327
"""Get the URL this branch is stacked against.
1329
:raises NotStacked: If the branch is not stacked.
1330
:raises UnstackableBranchFormat: If the branch does not support
1332
:raises UnstackableRepositoryFormat: If the repository does not support
1336
return self._real_branch.get_stacked_on_url()
1338
def lock_read(self):
1339
if not self._lock_mode:
1340
self._lock_mode = 'r'
1341
self._lock_count = 1
1342
if self._real_branch is not None:
1343
self._real_branch.lock_read()
1345
self._lock_count += 1
1347
def _remote_lock_write(self, token):
1349
branch_token = repo_token = ''
1351
branch_token = token
1352
repo_token = self.repository.lock_write()
1353
self.repository.unlock()
1354
path = self.bzrdir._path_for_remote_call(self._client)
1356
response = self._client.call(
1357
'Branch.lock_write', path, branch_token, repo_token or '')
1358
except errors.ErrorFromSmartServer, err:
1359
self._translate_error(err, token=token)
1360
if response[0] != 'ok':
1361
raise errors.UnexpectedSmartServerResponse(response)
1362
ok, branch_token, repo_token = response
1363
return branch_token, repo_token
1365
def lock_write(self, token=None):
1366
if not self._lock_mode:
1367
remote_tokens = self._remote_lock_write(token)
1368
self._lock_token, self._repo_lock_token = remote_tokens
1369
if not self._lock_token:
1370
raise SmartProtocolError('Remote server did not return a token!')
1371
# TODO: We really, really, really don't want to call _ensure_real
1372
# here, but it's the easiest way to ensure coherency between the
1373
# state of the RemoteBranch and RemoteRepository objects and the
1374
# physical locks. If we don't materialise the real objects here,
1375
# then getting everything in the right state later is complex, so
1376
# for now we just do it the lazy way.
1377
# -- Andrew Bennetts, 2007-02-22.
1379
if self._real_branch is not None:
1380
self._real_branch.repository.lock_write(
1381
token=self._repo_lock_token)
1383
self._real_branch.lock_write(token=self._lock_token)
1385
self._real_branch.repository.unlock()
1386
if token is not None:
1387
self._leave_lock = True
1389
# XXX: this case seems to be unreachable; token cannot be None.
1390
self._leave_lock = False
1391
self._lock_mode = 'w'
1392
self._lock_count = 1
1393
elif self._lock_mode == 'r':
1394
raise errors.ReadOnlyTransaction
1396
if token is not None:
1397
# A token was given to lock_write, and we're relocking, so check
1398
# that the given token actually matches the one we already have.
1399
if token != self._lock_token:
1400
raise errors.TokenMismatch(token, self._lock_token)
1401
self._lock_count += 1
1402
return self._lock_token or None
1404
def _unlock(self, branch_token, repo_token):
1405
path = self.bzrdir._path_for_remote_call(self._client)
1407
response = self._client.call('Branch.unlock', path, branch_token,
1409
except errors.ErrorFromSmartServer, err:
1410
self._translate_error(err, token=str((branch_token, repo_token)))
1411
if response == ('ok',):
1413
raise errors.UnexpectedSmartServerResponse(response)
1416
self._lock_count -= 1
1417
if not self._lock_count:
1418
self._clear_cached_state()
1419
mode = self._lock_mode
1420
self._lock_mode = None
1421
if self._real_branch is not None:
1422
if (not self._leave_lock and mode == 'w' and
1423
self._repo_lock_token):
1424
# If this RemoteBranch will remove the physical lock for the
1425
# repository, make sure the _real_branch doesn't do it
1426
# first. (Because the _real_branch's repository is set to
1427
# be the RemoteRepository.)
1428
self._real_branch.repository.leave_lock_in_place()
1429
self._real_branch.unlock()
1431
# Only write-locked branched need to make a remote method call
1432
# to perfom the unlock.
1434
if not self._lock_token:
1435
raise AssertionError('Locked, but no token!')
1436
branch_token = self._lock_token
1437
repo_token = self._repo_lock_token
1438
self._lock_token = None
1439
self._repo_lock_token = None
1440
if not self._leave_lock:
1441
self._unlock(branch_token, repo_token)
1443
def break_lock(self):
1445
return self._real_branch.break_lock()
1447
def leave_lock_in_place(self):
1448
if not self._lock_token:
1449
raise NotImplementedError(self.leave_lock_in_place)
1450
self._leave_lock = True
1452
def dont_leave_lock_in_place(self):
1453
if not self._lock_token:
1454
raise NotImplementedError(self.dont_leave_lock_in_place)
1455
self._leave_lock = False
1457
def _last_revision_info(self):
1458
path = self.bzrdir._path_for_remote_call(self._client)
1459
response = self._client.call('Branch.last_revision_info', path)
1460
if response[0] != 'ok':
1461
raise SmartProtocolError('unexpected response code %s' % (response,))
1462
revno = int(response[1])
1463
last_revision = response[2]
1464
return (revno, last_revision)
1466
def _gen_revision_history(self):
1467
"""See Branch._gen_revision_history()."""
1468
path = self.bzrdir._path_for_remote_call(self._client)
1469
response_tuple, response_handler = self._client.call_expecting_body(
1470
'Branch.revision_history', path)
1471
if response_tuple[0] != 'ok':
1472
raise errors.UnexpectedSmartServerResponse(response_tuple)
1473
result = response_handler.read_body_bytes().split('\x00')
1478
def _set_last_revision_descendant(self, revision_id, other_branch,
1479
allow_diverged=False, allow_overwrite_descendant=False):
1480
path = self.bzrdir._path_for_remote_call(self._client)
1482
response = self._client.call('Branch.set_last_revision_ex',
1483
path, self._lock_token, self._repo_lock_token, revision_id,
1484
int(allow_diverged), int(allow_overwrite_descendant))
1485
except errors.ErrorFromSmartServer, err:
1486
self._translate_error(err, other_branch=other_branch)
1487
self._clear_cached_state()
1488
if len(response) != 3 and response[0] != 'ok':
1489
raise errors.UnexpectedSmartServerResponse(response)
1490
new_revno, new_revision_id = response[1:]
1491
self._last_revision_info_cache = new_revno, new_revision_id
1492
self._real_branch._last_revision_info_cache = new_revno, new_revision_id
1494
def _set_last_revision(self, revision_id):
1495
path = self.bzrdir._path_for_remote_call(self._client)
1496
self._clear_cached_state()
1498
response = self._client.call('Branch.set_last_revision',
1499
path, self._lock_token, self._repo_lock_token, revision_id)
1500
except errors.ErrorFromSmartServer, err:
1501
self._translate_error(err)
1502
if response != ('ok',):
1503
raise errors.UnexpectedSmartServerResponse(response)
1506
def set_revision_history(self, rev_history):
1507
# Send just the tip revision of the history; the server will generate
1508
# the full history from that. If the revision doesn't exist in this
1509
# branch, NoSuchRevision will be raised.
1510
if rev_history == []:
1513
rev_id = rev_history[-1]
1514
self._set_last_revision(rev_id)
1515
self._cache_revision_history(rev_history)
1517
def get_parent(self):
1519
return self._real_branch.get_parent()
1521
def set_parent(self, url):
1523
return self._real_branch.set_parent(url)
1525
def set_stacked_on_url(self, stacked_location):
1526
"""Set the URL this branch is stacked against.
1528
:raises UnstackableBranchFormat: If the branch does not support
1530
:raises UnstackableRepositoryFormat: If the repository does not support
1534
return self._real_branch.set_stacked_on_url(stacked_location)
1536
def sprout(self, to_bzrdir, revision_id=None):
1537
# Like Branch.sprout, except that it sprouts a branch in the default
1538
# format, because RemoteBranches can't be created at arbitrary URLs.
1539
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1540
# to_bzrdir.create_branch...
1542
result = self._real_branch._format.initialize(to_bzrdir)
1543
self.copy_content_into(result, revision_id=revision_id)
1544
result.set_parent(self.bzrdir.root_transport.base)
1548
def pull(self, source, overwrite=False, stop_revision=None,
1550
self._clear_cached_state_of_remote_branch_only()
1552
return self._real_branch.pull(
1553
source, overwrite=overwrite, stop_revision=stop_revision,
1554
_override_hook_target=self, **kwargs)
1557
def push(self, target, overwrite=False, stop_revision=None):
1559
return self._real_branch.push(
1560
target, overwrite=overwrite, stop_revision=stop_revision,
1561
_override_hook_source_branch=self)
1563
def is_locked(self):
1564
return self._lock_count >= 1
1567
def set_last_revision_info(self, revno, revision_id):
1568
revision_id = ensure_null(revision_id)
1569
path = self.bzrdir._path_for_remote_call(self._client)
1571
response = self._client.call('Branch.set_last_revision_info',
1572
path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
1573
except errors.UnknownSmartMethod:
1575
self._clear_cached_state_of_remote_branch_only()
1576
self._real_branch.set_last_revision_info(revno, revision_id)
1577
self._last_revision_info_cache = revno, revision_id
1579
except errors.ErrorFromSmartServer, err:
1580
self._translate_error(err)
1581
if response == ('ok',):
1582
self._clear_cached_state()
1583
self._last_revision_info_cache = revno, revision_id
1584
# Update the _real_branch's cache too.
1585
if self._real_branch is not None:
1586
cache = self._last_revision_info_cache
1587
self._real_branch._last_revision_info_cache = cache
1589
raise errors.UnexpectedSmartServerResponse(response)
1592
def generate_revision_history(self, revision_id, last_rev=None,
1594
medium = self._client._medium
1595
if not medium._is_remote_before((1, 6)):
1597
self._set_last_revision_descendant(revision_id, other_branch,
1598
allow_diverged=True, allow_overwrite_descendant=True)
1600
except errors.UnknownSmartMethod:
1601
medium._remember_remote_is_before((1, 6))
1602
self._clear_cached_state_of_remote_branch_only()
1604
self._real_branch.generate_revision_history(
1605
revision_id, last_rev=last_rev, other_branch=other_branch)
1610
return self._real_branch.tags
1612
def set_push_location(self, location):
1614
return self._real_branch.set_push_location(location)
1617
def update_revisions(self, other, stop_revision=None, overwrite=False,
1619
"""See Branch.update_revisions."""
1622
if stop_revision is None:
1623
stop_revision = other.last_revision()
1624
if revision.is_null(stop_revision):
1625
# if there are no commits, we're done.
1627
self.fetch(other, stop_revision)
1630
# Just unconditionally set the new revision. We don't care if
1631
# the branches have diverged.
1632
self._set_last_revision(stop_revision)
1634
medium = self._client._medium
1635
if not medium._is_remote_before((1, 6)):
1637
self._set_last_revision_descendant(stop_revision, other)
1639
except errors.UnknownSmartMethod:
1640
medium._remember_remote_is_before((1, 6))
1641
# Fallback for pre-1.6 servers: check for divergence
1642
# client-side, then do _set_last_revision.
1643
last_rev = revision.ensure_null(self.last_revision())
1645
graph = self.repository.get_graph()
1646
if self._check_if_descendant_or_diverged(
1647
stop_revision, last_rev, graph, other):
1648
# stop_revision is a descendant of last_rev, but we aren't
1649
# overwriting, so we're done.
1651
self._set_last_revision(stop_revision)
1656
def _extract_tar(tar, to_dir):
1657
"""Extract all the contents of a tarfile object.
1659
A replacement for extractall, which is not present in python2.4
1662
tar.extract(tarinfo, to_dir)
1665
def _translate_error(err, **context):
1666
"""Translate an ErrorFromSmartServer into a more useful error.
1668
Possible context keys:
1677
return context[name]
1678
except KeyError, keyErr:
1679
mutter('Missing key %r in context %r', keyErr.args[0], context)
1681
if err.error_verb == 'NoSuchRevision':
1682
raise NoSuchRevision(find('branch'), err.error_args[0])
1683
elif err.error_verb == 'nosuchrevision':
1684
raise NoSuchRevision(find('repository'), err.error_args[0])
1685
elif err.error_tuple == ('nobranch',):
1686
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1687
elif err.error_verb == 'norepository':
1688
raise errors.NoRepositoryPresent(find('bzrdir'))
1689
elif err.error_verb == 'LockContention':
1690
raise errors.LockContention('(remote lock)')
1691
elif err.error_verb == 'UnlockableTransport':
1692
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1693
elif err.error_verb == 'LockFailed':
1694
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1695
elif err.error_verb == 'TokenMismatch':
1696
raise errors.TokenMismatch(find('token'), '(remote token)')
1697
elif err.error_verb == 'Diverged':
1698
raise errors.DivergedBranches(find('branch'), find('other_branch'))