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