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.
32
from bzrlib.branch import BranchReferenceFormat
33
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
34
from bzrlib.decorators import needs_read_lock, needs_write_lock
35
from bzrlib.errors import (
39
from bzrlib.lockable_files import LockableFiles
40
from bzrlib.smart import client, vfs
41
from bzrlib.revision import ensure_null, NULL_REVISION
42
from bzrlib.trace import mutter, note, warning
45
# Note: RemoteBzrDirFormat is in bzrdir.py
47
class RemoteBzrDir(BzrDir):
48
"""Control directory on a remote server, accessed via bzr:// or similar."""
50
def __init__(self, transport, _client=None):
51
"""Construct a RemoteBzrDir.
53
:param _client: Private parameter for testing. Disables probing and the
56
BzrDir.__init__(self, transport, RemoteBzrDirFormat())
57
# this object holds a delegated bzrdir that uses file-level operations
58
# to talk to the other side
59
self._real_bzrdir = None
62
medium = transport.get_smart_medium()
63
self._client = client._SmartClient(medium)
65
self._client = _client
68
path = self._path_for_remote_call(self._client)
69
response = self._client.call('BzrDir.open', path)
70
if response not in [('yes',), ('no',)]:
71
raise errors.UnexpectedSmartServerResponse(response)
72
if response == ('no',):
73
raise errors.NotBranchError(path=transport.base)
75
def _ensure_real(self):
76
"""Ensure that there is a _real_bzrdir set.
78
Used before calls to self._real_bzrdir.
80
if not self._real_bzrdir:
81
self._real_bzrdir = BzrDir.open_from_transport(
82
self.root_transport, _server_formats=False)
84
def cloning_metadir(self, stacked=False):
86
return self._real_bzrdir.cloning_metadir(stacked)
88
def _translate_error(self, err, **context):
89
_translate_error(err, bzrdir=self, **context)
91
def create_repository(self, shared=False):
93
self._real_bzrdir.create_repository(shared=shared)
94
return self.open_repository()
96
def destroy_repository(self):
97
"""See BzrDir.destroy_repository"""
99
self._real_bzrdir.destroy_repository()
101
def create_branch(self):
103
real_branch = self._real_bzrdir.create_branch()
104
return RemoteBranch(self, self.find_repository(), real_branch)
106
def destroy_branch(self):
107
"""See BzrDir.destroy_branch"""
109
self._real_bzrdir.destroy_branch()
111
def create_workingtree(self, revision_id=None, from_branch=None):
112
raise errors.NotLocalUrl(self.transport.base)
114
def find_branch_format(self):
115
"""Find the branch 'format' for this bzrdir.
117
This might be a synthetic object for e.g. RemoteBranch and SVN.
119
b = self.open_branch()
122
def get_branch_reference(self):
123
"""See BzrDir.get_branch_reference()."""
124
path = self._path_for_remote_call(self._client)
126
response = self._client.call('BzrDir.open_branch', path)
127
except errors.ErrorFromSmartServer, err:
128
self._translate_error(err)
129
if response[0] == 'ok':
130
if response[1] == '':
131
# branch at this location.
134
# a branch reference, use the existing BranchReference logic.
137
raise errors.UnexpectedSmartServerResponse(response)
139
def _get_tree_branch(self):
140
"""See BzrDir._get_tree_branch()."""
141
return None, self.open_branch()
143
def open_branch(self, _unsupported=False):
145
raise NotImplementedError('unsupported flag support not implemented yet.')
146
reference_url = self.get_branch_reference()
147
if reference_url is None:
148
# branch at this location.
149
return RemoteBranch(self, self.find_repository())
151
# a branch reference, use the existing BranchReference logic.
152
format = BranchReferenceFormat()
153
return format.open(self, _found=True, location=reference_url)
155
def open_repository(self):
156
path = self._path_for_remote_call(self._client)
157
verb = 'BzrDir.find_repositoryV2'
160
response = self._client.call(verb, path)
161
except errors.UnknownSmartMethod:
162
verb = 'BzrDir.find_repository'
163
response = self._client.call(verb, path)
164
except errors.ErrorFromSmartServer, err:
165
self._translate_error(err)
166
if response[0] != 'ok':
167
raise errors.UnexpectedSmartServerResponse(response)
168
if verb == 'BzrDir.find_repository':
169
# servers that don't support the V2 method don't support external
171
response = response + ('no', )
172
if not (len(response) == 5):
173
raise SmartProtocolError('incorrect response length %s' % (response,))
174
if response[1] == '':
175
format = RemoteRepositoryFormat()
176
format.rich_root_data = (response[2] == 'yes')
177
format.supports_tree_reference = (response[3] == 'yes')
178
# No wire format to check this yet.
179
format.supports_external_lookups = (response[4] == 'yes')
180
# Used to support creating a real format instance when needed.
181
format._creating_bzrdir = self
182
return RemoteRepository(self, format)
184
raise errors.NoRepositoryPresent(self)
186
def open_workingtree(self, recommend_upgrade=True):
188
if self._real_bzrdir.has_workingtree():
189
raise errors.NotLocalUrl(self.root_transport)
191
raise errors.NoWorkingTree(self.root_transport.base)
193
def _path_for_remote_call(self, client):
194
"""Return the path to be used for this bzrdir in a remote call."""
195
return client.remote_path_from_transport(self.root_transport)
197
def get_branch_transport(self, branch_format):
199
return self._real_bzrdir.get_branch_transport(branch_format)
201
def get_repository_transport(self, repository_format):
203
return self._real_bzrdir.get_repository_transport(repository_format)
205
def get_workingtree_transport(self, workingtree_format):
207
return self._real_bzrdir.get_workingtree_transport(workingtree_format)
209
def can_convert_format(self):
210
"""Upgrading of remote bzrdirs is not supported yet."""
213
def needs_format_conversion(self, format=None):
214
"""Upgrading of remote bzrdirs is not supported yet."""
217
def clone(self, url, revision_id=None, force_new_repo=False,
218
preserve_stacking=False):
220
return self._real_bzrdir.clone(url, revision_id=revision_id,
221
force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
223
def get_config(self):
225
return self._real_bzrdir.get_config()
228
class RemoteRepositoryFormat(repository.RepositoryFormat):
229
"""Format for repositories accessed over a _SmartClient.
231
Instances of this repository are represented by RemoteRepository
234
The RemoteRepositoryFormat is parameterized during construction
235
to reflect the capabilities of the real, remote format. Specifically
236
the attributes rich_root_data and supports_tree_reference are set
237
on a per instance basis, and are not set (and should not be) at
241
_matchingbzrdir = RemoteBzrDirFormat()
243
def initialize(self, a_bzrdir, shared=False):
244
if not isinstance(a_bzrdir, RemoteBzrDir):
245
prior_repo = self._creating_bzrdir.open_repository()
246
prior_repo._ensure_real()
247
return prior_repo._real_repository._format.initialize(
248
a_bzrdir, shared=shared)
249
return a_bzrdir.create_repository(shared=shared)
251
def open(self, a_bzrdir):
252
if not isinstance(a_bzrdir, RemoteBzrDir):
253
raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
254
return a_bzrdir.open_repository()
256
def get_format_description(self):
257
return 'bzr remote repository'
259
def __eq__(self, other):
260
return self.__class__ == other.__class__
262
def check_conversion_target(self, target_format):
263
if self.rich_root_data and not target_format.rich_root_data:
264
raise errors.BadConversionTarget(
265
'Does not support rich root data.', target_format)
266
if (self.supports_tree_reference and
267
not getattr(target_format, 'supports_tree_reference', False)):
268
raise errors.BadConversionTarget(
269
'Does not support nested trees', target_format)
272
class RemoteRepository(object):
273
"""Repository accessed over rpc.
275
For the moment most operations are performed using local transport-backed
279
def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
280
"""Create a RemoteRepository instance.
282
:param remote_bzrdir: The bzrdir hosting this repository.
283
:param format: The RemoteFormat object to use.
284
:param real_repository: If not None, a local implementation of the
285
repository logic for the repository, usually accessing the data
287
:param _client: Private testing parameter - override the smart client
288
to be used by the repository.
291
self._real_repository = real_repository
293
self._real_repository = None
294
self.bzrdir = remote_bzrdir
296
self._client = remote_bzrdir._client
298
self._client = _client
299
self._format = format
300
self._lock_mode = None
301
self._lock_token = None
303
self._leave_lock = False
304
# A cache of looked up revision parent data; reset at unlock time.
305
self._parents_map = None
306
if 'hpss' in debug.debug_flags:
307
self._requested_parents = None
309
# These depend on the actual remote format, so force them off for
310
# maximum compatibility. XXX: In future these should depend on the
311
# remote repository instance, but this is irrelevant until we perform
312
# reconcile via an RPC call.
313
self._reconcile_does_inventory_gc = False
314
self._reconcile_fixes_text_parents = False
315
self._reconcile_backsup_inventory = False
316
self.base = self.bzrdir.transport.base
317
# Additional places to query for data.
318
self._fallback_repositories = []
321
return "%s(%s)" % (self.__class__.__name__, self.base)
325
def abort_write_group(self):
326
"""Complete a write group on the decorated repository.
328
Smart methods peform operations in a single step so this api
329
is not really applicable except as a compatibility thunk
330
for older plugins that don't use e.g. the CommitBuilder
334
return self._real_repository.abort_write_group()
336
def commit_write_group(self):
337
"""Complete a write group on the decorated repository.
339
Smart methods peform operations in a single step so this api
340
is not really applicable except as a compatibility thunk
341
for older plugins that don't use e.g. the CommitBuilder
345
return self._real_repository.commit_write_group()
347
def _ensure_real(self):
348
"""Ensure that there is a _real_repository set.
350
Used before calls to self._real_repository.
352
if self._real_repository is None:
353
self.bzrdir._ensure_real()
354
self._set_real_repository(
355
self.bzrdir._real_bzrdir.open_repository())
357
def _translate_error(self, err, **context):
358
self.bzrdir._translate_error(err, repository=self, **context)
360
def find_text_key_references(self):
361
"""Find the text key references within the repository.
363
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
364
revision_ids. Each altered file-ids has the exact revision_ids that
365
altered it listed explicitly.
366
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
367
to whether they were referred to by the inventory of the
368
revision_id that they contain. The inventory texts from all present
369
revision ids are assessed to generate this report.
372
return self._real_repository.find_text_key_references()
374
def _generate_text_key_index(self):
375
"""Generate a new text key index for the repository.
377
This is an expensive function that will take considerable time to run.
379
:return: A dict mapping (file_id, revision_id) tuples to a list of
380
parents, also (file_id, revision_id) tuples.
383
return self._real_repository._generate_text_key_index()
385
@symbol_versioning.deprecated_method(symbol_versioning.one_four)
386
def get_revision_graph(self, revision_id=None):
387
"""See Repository.get_revision_graph()."""
388
return self._get_revision_graph(revision_id)
390
def _get_revision_graph(self, revision_id):
391
"""Private method for using with old (< 1.2) servers to fallback."""
392
if revision_id is None:
394
elif revision.is_null(revision_id):
397
path = self.bzrdir._path_for_remote_call(self._client)
399
response = self._client.call_expecting_body(
400
'Repository.get_revision_graph', path, revision_id)
401
except errors.ErrorFromSmartServer, err:
402
self._translate_error(err)
403
response_tuple, response_handler = response
404
if response_tuple[0] != 'ok':
405
raise errors.UnexpectedSmartServerResponse(response_tuple)
406
coded = response_handler.read_body_bytes()
408
# no revisions in this repository!
410
lines = coded.split('\n')
413
d = tuple(line.split())
414
revision_graph[d[0]] = d[1:]
416
return revision_graph
418
def has_revision(self, revision_id):
419
"""See Repository.has_revision()."""
420
if revision_id == NULL_REVISION:
421
# The null revision is always present.
423
path = self.bzrdir._path_for_remote_call(self._client)
424
response = self._client.call(
425
'Repository.has_revision', path, revision_id)
426
if response[0] not in ('yes', 'no'):
427
raise errors.UnexpectedSmartServerResponse(response)
428
return response[0] == 'yes'
430
def has_revisions(self, revision_ids):
431
"""See Repository.has_revisions()."""
433
for revision_id in revision_ids:
434
if self.has_revision(revision_id):
435
result.add(revision_id)
438
def has_same_location(self, other):
439
return (self.__class__ == other.__class__ and
440
self.bzrdir.transport.base == other.bzrdir.transport.base)
442
def get_graph(self, other_repository=None):
443
"""Return the graph for this repository format"""
444
parents_provider = self
445
if (other_repository is not None and
446
other_repository.bzrdir.transport.base !=
447
self.bzrdir.transport.base):
448
parents_provider = graph._StackedParentsProvider(
449
[parents_provider, other_repository._make_parents_provider()])
450
return graph.Graph(parents_provider)
452
def gather_stats(self, revid=None, committers=None):
453
"""See Repository.gather_stats()."""
454
path = self.bzrdir._path_for_remote_call(self._client)
455
# revid can be None to indicate no revisions, not just NULL_REVISION
456
if revid is None or revision.is_null(revid):
460
if committers is None or not committers:
461
fmt_committers = 'no'
463
fmt_committers = 'yes'
464
response_tuple, response_handler = self._client.call_expecting_body(
465
'Repository.gather_stats', path, fmt_revid, fmt_committers)
466
if response_tuple[0] != 'ok':
467
raise errors.UnexpectedSmartServerResponse(response_tuple)
469
body = response_handler.read_body_bytes()
471
for line in body.split('\n'):
474
key, val_text = line.split(':')
475
if key in ('revisions', 'size', 'committers'):
476
result[key] = int(val_text)
477
elif key in ('firstrev', 'latestrev'):
478
values = val_text.split(' ')[1:]
479
result[key] = (float(values[0]), long(values[1]))
483
def find_branches(self, using=False):
484
"""See Repository.find_branches()."""
485
# should be an API call to the server.
487
return self._real_repository.find_branches(using=using)
489
def get_physical_lock_status(self):
490
"""See Repository.get_physical_lock_status()."""
491
# should be an API call to the server.
493
return self._real_repository.get_physical_lock_status()
495
def is_in_write_group(self):
496
"""Return True if there is an open write group.
498
write groups are only applicable locally for the smart server..
500
if self._real_repository:
501
return self._real_repository.is_in_write_group()
504
return self._lock_count >= 1
507
"""See Repository.is_shared()."""
508
path = self.bzrdir._path_for_remote_call(self._client)
509
response = self._client.call('Repository.is_shared', path)
510
if response[0] not in ('yes', 'no'):
511
raise SmartProtocolError('unexpected response code %s' % (response,))
512
return response[0] == 'yes'
514
def is_write_locked(self):
515
return self._lock_mode == 'w'
518
# wrong eventually - want a local lock cache context
519
if not self._lock_mode:
520
self._lock_mode = 'r'
522
self._parents_map = {}
523
if 'hpss' in debug.debug_flags:
524
self._requested_parents = set()
525
if self._real_repository is not None:
526
self._real_repository.lock_read()
528
self._lock_count += 1
530
def _remote_lock_write(self, token):
531
path = self.bzrdir._path_for_remote_call(self._client)
535
response = self._client.call('Repository.lock_write', path, token)
536
except errors.ErrorFromSmartServer, err:
537
self._translate_error(err, token=token)
539
if response[0] == 'ok':
543
raise errors.UnexpectedSmartServerResponse(response)
545
def lock_write(self, token=None, _skip_rpc=False):
546
if not self._lock_mode:
548
if self._lock_token is not None:
549
if token != self._lock_token:
550
raise errors.TokenMismatch(token, self._lock_token)
551
self._lock_token = token
553
self._lock_token = self._remote_lock_write(token)
554
# if self._lock_token is None, then this is something like packs or
555
# svn where we don't get to lock the repo, or a weave style repository
556
# where we cannot lock it over the wire and attempts to do so will
558
if self._real_repository is not None:
559
self._real_repository.lock_write(token=self._lock_token)
560
if token is not None:
561
self._leave_lock = True
563
self._leave_lock = False
564
self._lock_mode = 'w'
566
self._parents_map = {}
567
if 'hpss' in debug.debug_flags:
568
self._requested_parents = set()
569
elif self._lock_mode == 'r':
570
raise errors.ReadOnlyError(self)
572
self._lock_count += 1
573
return self._lock_token or None
575
def leave_lock_in_place(self):
576
if not self._lock_token:
577
raise NotImplementedError(self.leave_lock_in_place)
578
self._leave_lock = True
580
def dont_leave_lock_in_place(self):
581
if not self._lock_token:
582
raise NotImplementedError(self.dont_leave_lock_in_place)
583
self._leave_lock = False
585
def _set_real_repository(self, repository):
586
"""Set the _real_repository for this repository.
588
:param repository: The repository to fallback to for non-hpss
589
implemented operations.
591
if self._real_repository is not None:
592
raise AssertionError('_real_repository is already set')
593
if isinstance(repository, RemoteRepository):
594
raise AssertionError()
595
self._real_repository = repository
596
if self._lock_mode == 'w':
597
# if we are already locked, the real repository must be able to
598
# acquire the lock with our token.
599
self._real_repository.lock_write(self._lock_token)
600
elif self._lock_mode == 'r':
601
self._real_repository.lock_read()
603
def start_write_group(self):
604
"""Start a write group on the decorated repository.
606
Smart methods peform operations in a single step so this api
607
is not really applicable except as a compatibility thunk
608
for older plugins that don't use e.g. the CommitBuilder
612
return self._real_repository.start_write_group()
614
def _unlock(self, token):
615
path = self.bzrdir._path_for_remote_call(self._client)
617
# with no token the remote repository is not persistently locked.
620
response = self._client.call('Repository.unlock', path, token)
621
except errors.ErrorFromSmartServer, err:
622
self._translate_error(err, token=token)
623
if response == ('ok',):
626
raise errors.UnexpectedSmartServerResponse(response)
629
self._lock_count -= 1
630
if self._lock_count > 0:
632
self._parents_map = None
633
if 'hpss' in debug.debug_flags:
634
self._requested_parents = None
635
old_mode = self._lock_mode
636
self._lock_mode = None
638
# The real repository is responsible at present for raising an
639
# exception if it's in an unfinished write group. However, it
640
# normally will *not* actually remove the lock from disk - that's
641
# done by the server on receiving the Repository.unlock call.
642
# This is just to let the _real_repository stay up to date.
643
if self._real_repository is not None:
644
self._real_repository.unlock()
646
# The rpc-level lock should be released even if there was a
647
# problem releasing the vfs-based lock.
649
# Only write-locked repositories need to make a remote method
650
# call to perfom the unlock.
651
old_token = self._lock_token
652
self._lock_token = None
653
if not self._leave_lock:
654
self._unlock(old_token)
656
def break_lock(self):
657
# should hand off to the network
659
return self._real_repository.break_lock()
661
def _get_tarball(self, compression):
662
"""Return a TemporaryFile containing a repository tarball.
664
Returns None if the server does not support sending tarballs.
667
path = self.bzrdir._path_for_remote_call(self._client)
669
response, protocol = self._client.call_expecting_body(
670
'Repository.tarball', path, compression)
671
except errors.UnknownSmartMethod:
672
protocol.cancel_read_body()
674
if response[0] == 'ok':
675
# Extract the tarball and return it
676
t = tempfile.NamedTemporaryFile()
677
# TODO: rpc layer should read directly into it...
678
t.write(protocol.read_body_bytes())
681
raise errors.UnexpectedSmartServerResponse(response)
683
def sprout(self, to_bzrdir, revision_id=None):
684
# TODO: Option to control what format is created?
686
dest_repo = self._real_repository._format.initialize(to_bzrdir,
688
dest_repo.fetch(self, revision_id=revision_id)
691
### These methods are just thin shims to the VFS object for now.
693
def revision_tree(self, revision_id):
695
return self._real_repository.revision_tree(revision_id)
697
def get_serializer_format(self):
699
return self._real_repository.get_serializer_format()
701
def get_commit_builder(self, branch, parents, config, timestamp=None,
702
timezone=None, committer=None, revprops=None,
704
# FIXME: It ought to be possible to call this without immediately
705
# triggering _ensure_real. For now it's the easiest thing to do.
707
real_repo = self._real_repository
708
builder = real_repo.get_commit_builder(branch, parents,
709
config, timestamp=timestamp, timezone=timezone,
710
committer=committer, revprops=revprops, revision_id=revision_id)
713
def add_fallback_repository(self, repository):
714
"""Add a repository to use for looking up data not held locally.
716
:param repository: A repository.
718
if not self._format.supports_external_lookups:
719
raise errors.UnstackableRepositoryFormat(self._format, self.base)
720
# We need to accumulate additional repositories here, to pass them in
722
self._fallback_repositories.append(repository)
724
def add_inventory(self, revid, inv, parents):
726
return self._real_repository.add_inventory(revid, inv, parents)
728
def add_revision(self, rev_id, rev, inv=None, config=None):
730
return self._real_repository.add_revision(
731
rev_id, rev, inv=inv, config=config)
734
def get_inventory(self, revision_id):
736
return self._real_repository.get_inventory(revision_id)
738
def iter_inventories(self, revision_ids):
740
return self._real_repository.iter_inventories(revision_ids)
743
def get_revision(self, revision_id):
745
return self._real_repository.get_revision(revision_id)
747
def get_transaction(self):
749
return self._real_repository.get_transaction()
752
def clone(self, a_bzrdir, revision_id=None):
754
return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
756
def make_working_trees(self):
757
"""See Repository.make_working_trees"""
759
return self._real_repository.make_working_trees()
761
def revision_ids_to_search_result(self, result_set):
762
"""Convert a set of revision ids to a graph SearchResult."""
763
result_parents = set()
764
for parents in self.get_graph().get_parent_map(
765
result_set).itervalues():
766
result_parents.update(parents)
767
included_keys = result_set.intersection(result_parents)
768
start_keys = result_set.difference(included_keys)
769
exclude_keys = result_parents.difference(result_set)
770
result = graph.SearchResult(start_keys, exclude_keys,
771
len(result_set), result_set)
775
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
776
"""Return the revision ids that other has that this does not.
778
These are returned in topological order.
780
revision_id: only return revision ids included by revision_id.
782
return repository.InterRepository.get(
783
other, self).search_missing_revision_ids(revision_id, find_ghosts)
785
def fetch(self, source, revision_id=None, pb=None):
786
if self.has_same_location(source):
787
# check that last_revision is in 'from' and then return a
789
if (revision_id is not None and
790
not revision.is_null(revision_id)):
791
self.get_revision(revision_id)
794
return self._real_repository.fetch(
795
source, revision_id=revision_id, pb=pb)
797
def create_bundle(self, target, base, fileobj, format=None):
799
self._real_repository.create_bundle(target, base, fileobj, format)
802
def get_ancestry(self, revision_id, topo_sorted=True):
804
return self._real_repository.get_ancestry(revision_id, topo_sorted)
806
def fileids_altered_by_revision_ids(self, revision_ids):
808
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
810
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
812
return self._real_repository._get_versioned_file_checker(
813
revisions, revision_versions_cache)
815
def iter_files_bytes(self, desired_files):
816
"""See Repository.iter_file_bytes.
819
return self._real_repository.iter_files_bytes(desired_files)
822
def _fetch_order(self):
823
"""Decorate the real repository for now.
825
In the long term getting this back from the remote repository as part
826
of open would be more efficient.
829
return self._real_repository._fetch_order
832
def _fetch_uses_deltas(self):
833
"""Decorate the real repository for now.
835
In the long term getting this back from the remote repository as part
836
of open would be more efficient.
839
return self._real_repository._fetch_uses_deltas
842
def _fetch_reconcile(self):
843
"""Decorate the real repository for now.
845
In the long term getting this back from the remote repository as part
846
of open would be more efficient.
849
return self._real_repository._fetch_reconcile
851
def get_parent_map(self, keys):
852
"""See bzrlib.Graph.get_parent_map()."""
853
# Hack to build up the caching logic.
854
ancestry = self._parents_map
856
# Repository is not locked, so there's no cache.
857
missing_revisions = set(keys)
860
missing_revisions = set(key for key in keys if key not in ancestry)
861
if missing_revisions:
862
parent_map = self._get_parent_map(missing_revisions)
863
if 'hpss' in debug.debug_flags:
864
mutter('retransmitted revisions: %d of %d',
865
len(set(ancestry).intersection(parent_map)),
867
ancestry.update(parent_map)
868
present_keys = [k for k in keys if k in ancestry]
869
if 'hpss' in debug.debug_flags:
870
if self._requested_parents is not None and len(ancestry) != 0:
871
self._requested_parents.update(present_keys)
872
mutter('Current RemoteRepository graph hit rate: %d%%',
873
100.0 * len(self._requested_parents) / len(ancestry))
874
return dict((k, ancestry[k]) for k in present_keys)
876
def _get_parent_map(self, keys):
877
"""Helper for get_parent_map that performs the RPC."""
878
medium = self._client._medium
879
if medium._is_remote_before((1, 2)):
880
# We already found out that the server can't understand
881
# Repository.get_parent_map requests, so just fetch the whole
883
# XXX: Note that this will issue a deprecation warning. This is ok
884
# :- its because we're working with a deprecated server anyway, and
885
# the user will almost certainly have seen a warning about the
886
# server version already.
887
rg = self.get_revision_graph()
888
# There is an api discrepency between get_parent_map and
889
# get_revision_graph. Specifically, a "key:()" pair in
890
# get_revision_graph just means a node has no parents. For
891
# "get_parent_map" it means the node is a ghost. So fix up the
892
# graph to correct this.
893
# https://bugs.launchpad.net/bzr/+bug/214894
894
# There is one other "bug" which is that ghosts in
895
# get_revision_graph() are not returned at all. But we won't worry
896
# about that for now.
897
for node_id, parent_ids in rg.iteritems():
899
rg[node_id] = (NULL_REVISION,)
900
rg[NULL_REVISION] = ()
905
raise ValueError('get_parent_map(None) is not valid')
906
if NULL_REVISION in keys:
907
keys.discard(NULL_REVISION)
908
found_parents = {NULL_REVISION:()}
913
# TODO(Needs analysis): We could assume that the keys being requested
914
# from get_parent_map are in a breadth first search, so typically they
915
# will all be depth N from some common parent, and we don't have to
916
# have the server iterate from the root parent, but rather from the
917
# keys we're searching; and just tell the server the keyspace we
918
# already have; but this may be more traffic again.
920
# Transform self._parents_map into a search request recipe.
921
# TODO: Manage this incrementally to avoid covering the same path
922
# repeatedly. (The server will have to on each request, but the less
923
# work done the better).
924
parents_map = self._parents_map
925
if parents_map is None:
926
# Repository is not locked, so there's no cache.
928
start_set = set(parents_map)
929
result_parents = set()
930
for parents in parents_map.itervalues():
931
result_parents.update(parents)
932
stop_keys = result_parents.difference(start_set)
933
included_keys = start_set.intersection(result_parents)
934
start_set.difference_update(included_keys)
935
recipe = (start_set, stop_keys, len(parents_map))
936
body = self._serialise_search_recipe(recipe)
937
path = self.bzrdir._path_for_remote_call(self._client)
939
if type(key) is not str:
941
"key %r not a plain string" % (key,))
942
verb = 'Repository.get_parent_map'
943
args = (path,) + tuple(keys)
945
response = self._client.call_with_body_bytes_expecting_body(
946
verb, args, self._serialise_search_recipe(recipe))
947
except errors.UnknownSmartMethod:
948
# Server does not support this method, so get the whole graph.
949
# Worse, we have to force a disconnection, because the server now
950
# doesn't realise it has a body on the wire to consume, so the
951
# only way to recover is to abandon the connection.
953
'Server is too old for fast get_parent_map, reconnecting. '
954
'(Upgrade the server to Bazaar 1.2 to avoid this)')
956
# To avoid having to disconnect repeatedly, we keep track of the
957
# fact the server doesn't understand remote methods added in 1.2.
958
medium._remember_remote_is_before((1, 2))
959
return self.get_revision_graph(None)
960
response_tuple, response_handler = response
961
if response_tuple[0] not in ['ok']:
962
response_handler.cancel_read_body()
963
raise errors.UnexpectedSmartServerResponse(response_tuple)
964
if response_tuple[0] == 'ok':
965
coded = bz2.decompress(response_handler.read_body_bytes())
969
lines = coded.split('\n')
972
d = tuple(line.split())
974
revision_graph[d[0]] = d[1:]
976
# No parents - so give the Graph result (NULL_REVISION,).
977
revision_graph[d[0]] = (NULL_REVISION,)
978
return revision_graph
981
def get_signature_text(self, revision_id):
983
return self._real_repository.get_signature_text(revision_id)
986
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
987
def get_revision_graph_with_ghosts(self, revision_ids=None):
989
return self._real_repository.get_revision_graph_with_ghosts(
990
revision_ids=revision_ids)
993
def get_inventory_xml(self, revision_id):
995
return self._real_repository.get_inventory_xml(revision_id)
997
def deserialise_inventory(self, revision_id, xml):
999
return self._real_repository.deserialise_inventory(revision_id, xml)
1001
def reconcile(self, other=None, thorough=False):
1003
return self._real_repository.reconcile(other=other, thorough=thorough)
1005
def all_revision_ids(self):
1007
return self._real_repository.all_revision_ids()
1010
def get_deltas_for_revisions(self, revisions):
1012
return self._real_repository.get_deltas_for_revisions(revisions)
1015
def get_revision_delta(self, revision_id):
1017
return self._real_repository.get_revision_delta(revision_id)
1020
def revision_trees(self, revision_ids):
1022
return self._real_repository.revision_trees(revision_ids)
1025
def get_revision_reconcile(self, revision_id):
1027
return self._real_repository.get_revision_reconcile(revision_id)
1030
def check(self, revision_ids=None):
1032
return self._real_repository.check(revision_ids=revision_ids)
1034
def copy_content_into(self, destination, revision_id=None):
1036
return self._real_repository.copy_content_into(
1037
destination, revision_id=revision_id)
1039
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1040
# get a tarball of the remote repository, and copy from that into the
1042
from bzrlib import osutils
1044
# TODO: Maybe a progress bar while streaming the tarball?
1045
note("Copying repository content as tarball...")
1046
tar_file = self._get_tarball('bz2')
1047
if tar_file is None:
1049
destination = to_bzrdir.create_repository()
1051
tar = tarfile.open('repository', fileobj=tar_file,
1053
tmpdir = osutils.mkdtemp()
1055
_extract_tar(tar, tmpdir)
1056
tmp_bzrdir = BzrDir.open(tmpdir)
1057
tmp_repo = tmp_bzrdir.open_repository()
1058
tmp_repo.copy_content_into(destination, revision_id)
1060
osutils.rmtree(tmpdir)
1064
# TODO: Suggestion from john: using external tar is much faster than
1065
# python's tarfile library, but it may not work on windows.
1068
def inventories(self):
1069
"""Decorate the real repository for now.
1071
In the long term a full blown network facility is needed to
1072
avoid creating a real repository object locally.
1075
return self._real_repository.inventories
1079
"""Compress the data within the repository.
1081
This is not currently implemented within the smart server.
1084
return self._real_repository.pack()
1087
def revisions(self):
1088
"""Decorate the real repository for now.
1090
In the short term this should become a real object to intercept graph
1093
In the long term a full blown network facility is needed.
1096
return self._real_repository.revisions
1098
def set_make_working_trees(self, new_value):
1100
self._real_repository.set_make_working_trees(new_value)
1103
def signatures(self):
1104
"""Decorate the real repository for now.
1106
In the long term a full blown network facility is needed to avoid
1107
creating a real repository object locally.
1110
return self._real_repository.signatures
1113
def sign_revision(self, revision_id, gpg_strategy):
1115
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1119
"""Decorate the real repository for now.
1121
In the long term a full blown network facility is needed to avoid
1122
creating a real repository object locally.
1125
return self._real_repository.texts
1128
def get_revisions(self, revision_ids):
1130
return self._real_repository.get_revisions(revision_ids)
1132
def supports_rich_root(self):
1134
return self._real_repository.supports_rich_root()
1136
def iter_reverse_revision_history(self, revision_id):
1138
return self._real_repository.iter_reverse_revision_history(revision_id)
1141
def _serializer(self):
1143
return self._real_repository._serializer
1145
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1147
return self._real_repository.store_revision_signature(
1148
gpg_strategy, plaintext, revision_id)
1150
def add_signature_text(self, revision_id, signature):
1152
return self._real_repository.add_signature_text(revision_id, signature)
1154
def has_signature_for_revision_id(self, revision_id):
1156
return self._real_repository.has_signature_for_revision_id(revision_id)
1158
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1160
return self._real_repository.item_keys_introduced_by(revision_ids,
1161
_files_pb=_files_pb)
1163
def revision_graph_can_have_wrong_parents(self):
1164
# The answer depends on the remote repo format.
1166
return self._real_repository.revision_graph_can_have_wrong_parents()
1168
def _find_inconsistent_revision_parents(self):
1170
return self._real_repository._find_inconsistent_revision_parents()
1172
def _check_for_inconsistent_revision_parents(self):
1174
return self._real_repository._check_for_inconsistent_revision_parents()
1176
def _make_parents_provider(self):
1179
def _serialise_search_recipe(self, recipe):
1180
"""Serialise a graph search recipe.
1182
:param recipe: A search recipe (start, stop, count).
1183
:return: Serialised bytes.
1185
start_keys = ' '.join(recipe[0])
1186
stop_keys = ' '.join(recipe[1])
1187
count = str(recipe[2])
1188
return '\n'.join((start_keys, stop_keys, count))
1191
class RemoteBranchLockableFiles(LockableFiles):
1192
"""A 'LockableFiles' implementation that talks to a smart server.
1194
This is not a public interface class.
1197
def __init__(self, bzrdir, _client):
1198
self.bzrdir = bzrdir
1199
self._client = _client
1200
self._need_find_modes = True
1201
LockableFiles.__init__(
1202
self, bzrdir.get_branch_transport(None),
1203
'lock', lockdir.LockDir)
1205
def _find_modes(self):
1206
# RemoteBranches don't let the client set the mode of control files.
1207
self._dir_mode = None
1208
self._file_mode = None
1211
class RemoteBranchFormat(branch.BranchFormat):
1213
def __eq__(self, other):
1214
return (isinstance(other, RemoteBranchFormat) and
1215
self.__dict__ == other.__dict__)
1217
def get_format_description(self):
1218
return 'Remote BZR Branch'
1220
def get_format_string(self):
1221
return 'Remote BZR Branch'
1223
def open(self, a_bzrdir):
1224
return a_bzrdir.open_branch()
1226
def initialize(self, a_bzrdir):
1227
return a_bzrdir.create_branch()
1229
def supports_tags(self):
1230
# Remote branches might support tags, but we won't know until we
1231
# access the real remote branch.
1235
class RemoteBranch(branch.Branch):
1236
"""Branch stored on a server accessed by HPSS RPC.
1238
At the moment most operations are mapped down to simple file operations.
1241
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1243
"""Create a RemoteBranch instance.
1245
:param real_branch: An optional local implementation of the branch
1246
format, usually accessing the data via the VFS.
1247
:param _client: Private parameter for testing.
1249
# We intentionally don't call the parent class's __init__, because it
1250
# will try to assign to self.tags, which is a property in this subclass.
1251
# And the parent's __init__ doesn't do much anyway.
1252
self._revision_id_to_revno_cache = None
1253
self._revision_history_cache = None
1254
self._last_revision_info_cache = None
1255
self.bzrdir = remote_bzrdir
1256
if _client is not None:
1257
self._client = _client
1259
self._client = remote_bzrdir._client
1260
self.repository = remote_repository
1261
if real_branch is not None:
1262
self._real_branch = real_branch
1263
# Give the remote repository the matching real repo.
1264
real_repo = self._real_branch.repository
1265
if isinstance(real_repo, RemoteRepository):
1266
real_repo._ensure_real()
1267
real_repo = real_repo._real_repository
1268
self.repository._set_real_repository(real_repo)
1269
# Give the branch the remote repository to let fast-pathing happen.
1270
self._real_branch.repository = self.repository
1272
self._real_branch = None
1273
# Fill out expected attributes of branch for bzrlib api users.
1274
self._format = RemoteBranchFormat()
1275
self.base = self.bzrdir.root_transport.base
1276
self._control_files = None
1277
self._lock_mode = None
1278
self._lock_token = None
1279
self._repo_lock_token = None
1280
self._lock_count = 0
1281
self._leave_lock = False
1283
def _get_real_transport(self):
1284
# if we try vfs access, return the real branch's vfs transport
1286
return self._real_branch._transport
1288
_transport = property(_get_real_transport)
1291
return "%s(%s)" % (self.__class__.__name__, self.base)
1295
def _ensure_real(self):
1296
"""Ensure that there is a _real_branch set.
1298
Used before calls to self._real_branch.
1300
if self._real_branch is None:
1301
if not vfs.vfs_enabled():
1302
raise AssertionError('smart server vfs must be enabled '
1303
'to use vfs implementation')
1304
self.bzrdir._ensure_real()
1305
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1306
if self.repository._real_repository is None:
1307
# Give the remote repository the matching real repo.
1308
real_repo = self._real_branch.repository
1309
if isinstance(real_repo, RemoteRepository):
1310
real_repo._ensure_real()
1311
real_repo = real_repo._real_repository
1312
self.repository._set_real_repository(real_repo)
1313
# Give the real branch the remote repository to let fast-pathing
1315
self._real_branch.repository = self.repository
1316
if self._lock_mode == 'r':
1317
self._real_branch.lock_read()
1318
elif self._lock_mode == 'w':
1319
self._real_branch.lock_write(token=self._lock_token)
1321
def _translate_error(self, err, **context):
1322
self.repository._translate_error(err, branch=self, **context)
1324
def _clear_cached_state(self):
1325
super(RemoteBranch, self)._clear_cached_state()
1326
if self._real_branch is not None:
1327
self._real_branch._clear_cached_state()
1329
def _clear_cached_state_of_remote_branch_only(self):
1330
"""Like _clear_cached_state, but doesn't clear the cache of
1333
This is useful when falling back to calling a method of
1334
self._real_branch that changes state. In that case the underlying
1335
branch changes, so we need to invalidate this RemoteBranch's cache of
1336
it. However, there's no need to invalidate the _real_branch's cache
1337
too, in fact doing so might harm performance.
1339
super(RemoteBranch, self)._clear_cached_state()
1342
def control_files(self):
1343
# Defer actually creating RemoteBranchLockableFiles until its needed,
1344
# because it triggers an _ensure_real that we otherwise might not need.
1345
if self._control_files is None:
1346
self._control_files = RemoteBranchLockableFiles(
1347
self.bzrdir, self._client)
1348
return self._control_files
1350
def _get_checkout_format(self):
1352
return self._real_branch._get_checkout_format()
1354
def get_physical_lock_status(self):
1355
"""See Branch.get_physical_lock_status()."""
1356
# should be an API call to the server, as branches must be lockable.
1358
return self._real_branch.get_physical_lock_status()
1360
def get_stacked_on_url(self):
1361
"""Get the URL this branch is stacked against.
1363
:raises NotStacked: If the branch is not stacked.
1364
:raises UnstackableBranchFormat: If the branch does not support
1366
:raises UnstackableRepositoryFormat: If the repository does not support
1370
return self._real_branch.get_stacked_on_url()
1372
def lock_read(self):
1373
self.repository.lock_read()
1374
if not self._lock_mode:
1375
self._lock_mode = 'r'
1376
self._lock_count = 1
1377
if self._real_branch is not None:
1378
self._real_branch.lock_read()
1380
self._lock_count += 1
1382
def _remote_lock_write(self, token):
1384
branch_token = repo_token = ''
1386
branch_token = token
1387
repo_token = self.repository.lock_write()
1388
self.repository.unlock()
1389
path = self.bzrdir._path_for_remote_call(self._client)
1391
response = self._client.call(
1392
'Branch.lock_write', path, branch_token, repo_token or '')
1393
except errors.ErrorFromSmartServer, err:
1394
self._translate_error(err, token=token)
1395
if response[0] != 'ok':
1396
raise errors.UnexpectedSmartServerResponse(response)
1397
ok, branch_token, repo_token = response
1398
return branch_token, repo_token
1400
def lock_write(self, token=None):
1401
if not self._lock_mode:
1402
# Lock the branch and repo in one remote call.
1403
remote_tokens = self._remote_lock_write(token)
1404
self._lock_token, self._repo_lock_token = remote_tokens
1405
if not self._lock_token:
1406
raise SmartProtocolError('Remote server did not return a token!')
1407
# Tell the self.repository object that it is locked.
1408
self.repository.lock_write(
1409
self._repo_lock_token, _skip_rpc=True)
1411
if self._real_branch is not None:
1412
self._real_branch.lock_write(token=self._lock_token)
1413
if token is not None:
1414
self._leave_lock = True
1416
self._leave_lock = False
1417
self._lock_mode = 'w'
1418
self._lock_count = 1
1419
elif self._lock_mode == 'r':
1420
raise errors.ReadOnlyTransaction
1422
if token is not None:
1423
# A token was given to lock_write, and we're relocking, so
1424
# check that the given token actually matches the one we
1426
if token != self._lock_token:
1427
raise errors.TokenMismatch(token, self._lock_token)
1428
self._lock_count += 1
1429
# Re-lock the repository too.
1430
self.repository.lock_write(self._repo_lock_token)
1431
return self._lock_token or None
1433
def _unlock(self, branch_token, repo_token):
1434
path = self.bzrdir._path_for_remote_call(self._client)
1436
response = self._client.call('Branch.unlock', path, branch_token,
1438
except errors.ErrorFromSmartServer, err:
1439
self._translate_error(err, token=str((branch_token, repo_token)))
1440
if response == ('ok',):
1442
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
1455
# for the repository, make sure the _real_branch
1456
# doesn't do it first. (Because the _real_branch's
1457
# repository is set to 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
1462
# call 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
self.repository.unlock()
1475
def break_lock(self):
1477
return self._real_branch.break_lock()
1479
def leave_lock_in_place(self):
1480
if not self._lock_token:
1481
raise NotImplementedError(self.leave_lock_in_place)
1482
self._leave_lock = True
1484
def dont_leave_lock_in_place(self):
1485
if not self._lock_token:
1486
raise NotImplementedError(self.dont_leave_lock_in_place)
1487
self._leave_lock = False
1489
def _last_revision_info(self):
1490
path = self.bzrdir._path_for_remote_call(self._client)
1491
response = self._client.call('Branch.last_revision_info', path)
1492
if response[0] != 'ok':
1493
raise SmartProtocolError('unexpected response code %s' % (response,))
1494
revno = int(response[1])
1495
last_revision = response[2]
1496
return (revno, last_revision)
1498
def _gen_revision_history(self):
1499
"""See Branch._gen_revision_history()."""
1500
path = self.bzrdir._path_for_remote_call(self._client)
1501
response_tuple, response_handler = self._client.call_expecting_body(
1502
'Branch.revision_history', path)
1503
if response_tuple[0] != 'ok':
1504
raise errors.UnexpectedSmartServerResponse(response_tuple)
1505
result = response_handler.read_body_bytes().split('\x00')
1510
def _set_last_revision_descendant(self, revision_id, other_branch,
1511
allow_diverged=False, allow_overwrite_descendant=False):
1512
path = self.bzrdir._path_for_remote_call(self._client)
1514
response = self._client.call('Branch.set_last_revision_ex',
1515
path, self._lock_token, self._repo_lock_token, revision_id,
1516
int(allow_diverged), int(allow_overwrite_descendant))
1517
except errors.ErrorFromSmartServer, err:
1518
self._translate_error(err, other_branch=other_branch)
1519
self._clear_cached_state()
1520
if len(response) != 3 and response[0] != 'ok':
1521
raise errors.UnexpectedSmartServerResponse(response)
1522
new_revno, new_revision_id = response[1:]
1523
self._last_revision_info_cache = new_revno, new_revision_id
1524
if self._real_branch is not None:
1525
cache = new_revno, new_revision_id
1526
self._real_branch._last_revision_info_cache = cache
1528
def _set_last_revision(self, revision_id):
1529
path = self.bzrdir._path_for_remote_call(self._client)
1530
self._clear_cached_state()
1532
response = self._client.call('Branch.set_last_revision',
1533
path, self._lock_token, self._repo_lock_token, revision_id)
1534
except errors.ErrorFromSmartServer, err:
1535
self._translate_error(err)
1536
if response != ('ok',):
1537
raise errors.UnexpectedSmartServerResponse(response)
1540
def set_revision_history(self, rev_history):
1541
# Send just the tip revision of the history; the server will generate
1542
# the full history from that. If the revision doesn't exist in this
1543
# branch, NoSuchRevision will be raised.
1544
if rev_history == []:
1547
rev_id = rev_history[-1]
1548
self._set_last_revision(rev_id)
1549
self._cache_revision_history(rev_history)
1551
def get_parent(self):
1553
return self._real_branch.get_parent()
1555
def set_parent(self, url):
1557
return self._real_branch.set_parent(url)
1559
def set_stacked_on_url(self, stacked_location):
1560
"""Set the URL this branch is stacked against.
1562
:raises UnstackableBranchFormat: If the branch does not support
1564
:raises UnstackableRepositoryFormat: If the repository does not support
1568
return self._real_branch.set_stacked_on_url(stacked_location)
1570
def sprout(self, to_bzrdir, revision_id=None):
1571
# Like Branch.sprout, except that it sprouts a branch in the default
1572
# format, because RemoteBranches can't be created at arbitrary URLs.
1573
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1574
# to_bzrdir.create_branch...
1576
result = self._real_branch._format.initialize(to_bzrdir)
1577
self.copy_content_into(result, revision_id=revision_id)
1578
result.set_parent(self.bzrdir.root_transport.base)
1582
def pull(self, source, overwrite=False, stop_revision=None,
1584
self._clear_cached_state_of_remote_branch_only()
1586
return self._real_branch.pull(
1587
source, overwrite=overwrite, stop_revision=stop_revision,
1588
_override_hook_target=self, **kwargs)
1591
def push(self, target, overwrite=False, stop_revision=None):
1593
return self._real_branch.push(
1594
target, overwrite=overwrite, stop_revision=stop_revision,
1595
_override_hook_source_branch=self)
1597
def is_locked(self):
1598
return self._lock_count >= 1
1601
def revision_id_to_revno(self, revision_id):
1603
return self._real_branch.revision_id_to_revno(revision_id)
1606
def set_last_revision_info(self, revno, revision_id):
1607
revision_id = ensure_null(revision_id)
1608
path = self.bzrdir._path_for_remote_call(self._client)
1610
response = self._client.call('Branch.set_last_revision_info',
1611
path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
1612
except errors.UnknownSmartMethod:
1614
self._clear_cached_state_of_remote_branch_only()
1615
self._real_branch.set_last_revision_info(revno, revision_id)
1616
self._last_revision_info_cache = revno, revision_id
1618
except errors.ErrorFromSmartServer, err:
1619
self._translate_error(err)
1620
if response == ('ok',):
1621
self._clear_cached_state()
1622
self._last_revision_info_cache = revno, revision_id
1623
# Update the _real_branch's cache too.
1624
if self._real_branch is not None:
1625
cache = self._last_revision_info_cache
1626
self._real_branch._last_revision_info_cache = cache
1628
raise errors.UnexpectedSmartServerResponse(response)
1631
def generate_revision_history(self, revision_id, last_rev=None,
1633
medium = self._client._medium
1634
if not medium._is_remote_before((1, 6)):
1636
self._set_last_revision_descendant(revision_id, other_branch,
1637
allow_diverged=True, allow_overwrite_descendant=True)
1639
except errors.UnknownSmartMethod:
1640
medium._remember_remote_is_before((1, 6))
1641
self._clear_cached_state_of_remote_branch_only()
1643
self._real_branch.generate_revision_history(
1644
revision_id, last_rev=last_rev, other_branch=other_branch)
1649
return self._real_branch.tags
1651
def set_push_location(self, location):
1653
return self._real_branch.set_push_location(location)
1656
def update_revisions(self, other, stop_revision=None, overwrite=False,
1658
"""See Branch.update_revisions."""
1661
if stop_revision is None:
1662
stop_revision = other.last_revision()
1663
if revision.is_null(stop_revision):
1664
# if there are no commits, we're done.
1666
self.fetch(other, stop_revision)
1669
# Just unconditionally set the new revision. We don't care if
1670
# the branches have diverged.
1671
self._set_last_revision(stop_revision)
1673
medium = self._client._medium
1674
if not medium._is_remote_before((1, 6)):
1676
self._set_last_revision_descendant(stop_revision, other)
1678
except errors.UnknownSmartMethod:
1679
medium._remember_remote_is_before((1, 6))
1680
# Fallback for pre-1.6 servers: check for divergence
1681
# client-side, then do _set_last_revision.
1682
last_rev = revision.ensure_null(self.last_revision())
1684
graph = self.repository.get_graph()
1685
if self._check_if_descendant_or_diverged(
1686
stop_revision, last_rev, graph, other):
1687
# stop_revision is a descendant of last_rev, but we aren't
1688
# overwriting, so we're done.
1690
self._set_last_revision(stop_revision)
1695
def _extract_tar(tar, to_dir):
1696
"""Extract all the contents of a tarfile object.
1698
A replacement for extractall, which is not present in python2.4
1701
tar.extract(tarinfo, to_dir)
1704
def _translate_error(err, **context):
1705
"""Translate an ErrorFromSmartServer into a more useful error.
1707
Possible context keys:
1714
If the error from the server doesn't match a known pattern, then
1715
UnknownErrorFromSmartServer is raised.
1719
return context[name]
1720
except KeyError, keyErr:
1721
mutter('Missing key %r in context %r', keyErr.args[0], context)
1723
if err.error_verb == 'NoSuchRevision':
1724
raise NoSuchRevision(find('branch'), err.error_args[0])
1725
elif err.error_verb == 'nosuchrevision':
1726
raise NoSuchRevision(find('repository'), err.error_args[0])
1727
elif err.error_tuple == ('nobranch',):
1728
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1729
elif err.error_verb == 'norepository':
1730
raise errors.NoRepositoryPresent(find('bzrdir'))
1731
elif err.error_verb == 'LockContention':
1732
raise errors.LockContention('(remote lock)')
1733
elif err.error_verb == 'UnlockableTransport':
1734
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1735
elif err.error_verb == 'LockFailed':
1736
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1737
elif err.error_verb == 'TokenMismatch':
1738
raise errors.TokenMismatch(find('token'), '(remote token)')
1739
elif err.error_verb == 'Diverged':
1740
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1741
elif err.error_verb == 'TipChangeRejected':
1742
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
1743
raise errors.UnknownErrorFromSmartServer(err)