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.
33
from bzrlib.branch import BranchReferenceFormat
34
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
35
from bzrlib.decorators import needs_read_lock, needs_write_lock
36
from bzrlib.errors import (
40
from bzrlib.lockable_files import LockableFiles
41
from bzrlib.smart import client, vfs
42
from bzrlib.revision import ensure_null, NULL_REVISION
43
from bzrlib.trace import mutter, note, warning
46
# Note: RemoteBzrDirFormat is in bzrdir.py
48
class RemoteBzrDir(BzrDir):
49
"""Control directory on a remote server, accessed via bzr:// or similar."""
51
def __init__(self, transport, _client=None):
52
"""Construct a RemoteBzrDir.
54
:param _client: Private parameter for testing. Disables probing and the
57
BzrDir.__init__(self, transport, RemoteBzrDirFormat())
58
# this object holds a delegated bzrdir that uses file-level operations
59
# to talk to the other side
60
self._real_bzrdir = None
63
medium = transport.get_smart_medium()
64
self._client = client._SmartClient(medium)
66
self._client = _client
69
path = self._path_for_remote_call(self._client)
70
response = self._client.call('BzrDir.open', path)
71
if response not in [('yes',), ('no',)]:
72
raise errors.UnexpectedSmartServerResponse(response)
73
if response == ('no',):
74
raise errors.NotBranchError(path=transport.base)
76
def _ensure_real(self):
77
"""Ensure that there is a _real_bzrdir set.
79
Used before calls to self._real_bzrdir.
81
if not self._real_bzrdir:
82
self._real_bzrdir = BzrDir.open_from_transport(
83
self.root_transport, _server_formats=False)
85
def cloning_metadir(self, stacked=False):
87
return self._real_bzrdir.cloning_metadir(stacked)
89
def _translate_error(self, err, **context):
90
_translate_error(err, bzrdir=self, **context)
92
def create_repository(self, shared=False):
94
self._real_bzrdir.create_repository(shared=shared)
95
return self.open_repository()
97
def destroy_repository(self):
98
"""See BzrDir.destroy_repository"""
100
self._real_bzrdir.destroy_repository()
102
def create_branch(self):
104
real_branch = self._real_bzrdir.create_branch()
105
return RemoteBranch(self, self.find_repository(), real_branch)
107
def destroy_branch(self):
108
"""See BzrDir.destroy_branch"""
110
self._real_bzrdir.destroy_branch()
112
def create_workingtree(self, revision_id=None, from_branch=None):
113
raise errors.NotLocalUrl(self.transport.base)
115
def find_branch_format(self):
116
"""Find the branch 'format' for this bzrdir.
118
This might be a synthetic object for e.g. RemoteBranch and SVN.
120
b = self.open_branch()
123
def get_branch_reference(self):
124
"""See BzrDir.get_branch_reference()."""
125
path = self._path_for_remote_call(self._client)
127
response = self._client.call('BzrDir.open_branch', path)
128
except errors.ErrorFromSmartServer, err:
129
self._translate_error(err)
130
if response[0] == 'ok':
131
if response[1] == '':
132
# branch at this location.
135
# a branch reference, use the existing BranchReference logic.
138
raise errors.UnexpectedSmartServerResponse(response)
140
def _get_tree_branch(self):
141
"""See BzrDir._get_tree_branch()."""
142
return None, self.open_branch()
144
def open_branch(self, _unsupported=False):
146
raise NotImplementedError('unsupported flag support not implemented yet.')
147
reference_url = self.get_branch_reference()
148
if reference_url is None:
149
# branch at this location.
150
return RemoteBranch(self, self.find_repository())
152
# a branch reference, use the existing BranchReference logic.
153
format = BranchReferenceFormat()
154
return format.open(self, _found=True, location=reference_url)
156
def open_repository(self):
157
path = self._path_for_remote_call(self._client)
158
verb = 'BzrDir.find_repositoryV2'
161
response = self._client.call(verb, path)
162
except errors.UnknownSmartMethod:
163
verb = 'BzrDir.find_repository'
164
response = self._client.call(verb, path)
165
except errors.ErrorFromSmartServer, err:
166
self._translate_error(err)
167
if response[0] != 'ok':
168
raise errors.UnexpectedSmartServerResponse(response)
169
if verb == 'BzrDir.find_repository':
170
# servers that don't support the V2 method don't support external
172
response = response + ('no', )
173
if not (len(response) == 5):
174
raise SmartProtocolError('incorrect response length %s' % (response,))
175
if response[1] == '':
176
format = RemoteRepositoryFormat()
177
format.rich_root_data = (response[2] == 'yes')
178
format.supports_tree_reference = (response[3] == 'yes')
179
# No wire format to check this yet.
180
format.supports_external_lookups = (response[4] == 'yes')
181
# Used to support creating a real format instance when needed.
182
format._creating_bzrdir = self
183
return RemoteRepository(self, format)
185
raise errors.NoRepositoryPresent(self)
187
def open_workingtree(self, recommend_upgrade=True):
189
if self._real_bzrdir.has_workingtree():
190
raise errors.NotLocalUrl(self.root_transport)
192
raise errors.NoWorkingTree(self.root_transport.base)
194
def _path_for_remote_call(self, client):
195
"""Return the path to be used for this bzrdir in a remote call."""
196
return client.remote_path_from_transport(self.root_transport)
198
def get_branch_transport(self, branch_format):
200
return self._real_bzrdir.get_branch_transport(branch_format)
202
def get_repository_transport(self, repository_format):
204
return self._real_bzrdir.get_repository_transport(repository_format)
206
def get_workingtree_transport(self, workingtree_format):
208
return self._real_bzrdir.get_workingtree_transport(workingtree_format)
210
def can_convert_format(self):
211
"""Upgrading of remote bzrdirs is not supported yet."""
214
def needs_format_conversion(self, format=None):
215
"""Upgrading of remote bzrdirs is not supported yet."""
218
def clone(self, url, revision_id=None, force_new_repo=False,
219
preserve_stacking=False):
221
return self._real_bzrdir.clone(url, revision_id=revision_id,
222
force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
224
def get_config(self):
226
return self._real_bzrdir.get_config()
229
class RemoteRepositoryFormat(repository.RepositoryFormat):
230
"""Format for repositories accessed over a _SmartClient.
232
Instances of this repository are represented by RemoteRepository
235
The RemoteRepositoryFormat is parameterized during construction
236
to reflect the capabilities of the real, remote format. Specifically
237
the attributes rich_root_data and supports_tree_reference are set
238
on a per instance basis, and are not set (and should not be) at
242
_matchingbzrdir = RemoteBzrDirFormat()
244
def initialize(self, a_bzrdir, shared=False):
245
if not isinstance(a_bzrdir, RemoteBzrDir):
246
prior_repo = self._creating_bzrdir.open_repository()
247
prior_repo._ensure_real()
248
return prior_repo._real_repository._format.initialize(
249
a_bzrdir, shared=shared)
250
return a_bzrdir.create_repository(shared=shared)
252
def open(self, a_bzrdir):
253
if not isinstance(a_bzrdir, RemoteBzrDir):
254
raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
255
return a_bzrdir.open_repository()
257
def get_format_description(self):
258
return 'bzr remote repository'
260
def __eq__(self, other):
261
return self.__class__ == other.__class__
263
def check_conversion_target(self, target_format):
264
if self.rich_root_data and not target_format.rich_root_data:
265
raise errors.BadConversionTarget(
266
'Does not support rich root data.', target_format)
267
if (self.supports_tree_reference and
268
not getattr(target_format, 'supports_tree_reference', False)):
269
raise errors.BadConversionTarget(
270
'Does not support nested trees', target_format)
273
class RemoteRepository(object):
274
"""Repository accessed over rpc.
276
For the moment most operations are performed using local transport-backed
280
def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
281
"""Create a RemoteRepository instance.
283
:param remote_bzrdir: The bzrdir hosting this repository.
284
:param format: The RemoteFormat object to use.
285
:param real_repository: If not None, a local implementation of the
286
repository logic for the repository, usually accessing the data
288
:param _client: Private testing parameter - override the smart client
289
to be used by the repository.
292
self._real_repository = real_repository
294
self._real_repository = None
295
self.bzrdir = remote_bzrdir
297
self._client = remote_bzrdir._client
299
self._client = _client
300
self._format = format
301
self._lock_mode = None
302
self._lock_token = None
304
self._leave_lock = False
305
# A cache of looked up revision parent data; reset at unlock time.
306
self._parents_map = None
307
if 'hpss' in debug.debug_flags:
308
self._requested_parents = None
310
# These depend on the actual remote format, so force them off for
311
# maximum compatibility. XXX: In future these should depend on the
312
# remote repository instance, but this is irrelevant until we perform
313
# reconcile via an RPC call.
314
self._reconcile_does_inventory_gc = False
315
self._reconcile_fixes_text_parents = False
316
self._reconcile_backsup_inventory = False
317
self.base = self.bzrdir.transport.base
318
# Additional places to query for data.
319
self._fallback_repositories = []
322
return "%s(%s)" % (self.__class__.__name__, self.base)
326
def abort_write_group(self):
327
"""Complete a write group on the decorated repository.
329
Smart methods peform operations in a single step so this api
330
is not really applicable except as a compatibility thunk
331
for older plugins that don't use e.g. the CommitBuilder
335
return self._real_repository.abort_write_group()
337
def commit_write_group(self):
338
"""Complete a write group on the decorated repository.
340
Smart methods peform operations in a single step so this api
341
is not really applicable except as a compatibility thunk
342
for older plugins that don't use e.g. the CommitBuilder
346
return self._real_repository.commit_write_group()
348
def _ensure_real(self):
349
"""Ensure that there is a _real_repository set.
351
Used before calls to self._real_repository.
353
if self._real_repository is None:
354
self.bzrdir._ensure_real()
355
self._set_real_repository(
356
self.bzrdir._real_bzrdir.open_repository())
358
def _translate_error(self, err, **context):
359
self.bzrdir._translate_error(err, repository=self, **context)
361
def find_text_key_references(self):
362
"""Find the text key references within the repository.
364
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
365
revision_ids. Each altered file-ids has the exact revision_ids that
366
altered it listed explicitly.
367
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
368
to whether they were referred to by the inventory of the
369
revision_id that they contain. The inventory texts from all present
370
revision ids are assessed to generate this report.
373
return self._real_repository.find_text_key_references()
375
def _generate_text_key_index(self):
376
"""Generate a new text key index for the repository.
378
This is an expensive function that will take considerable time to run.
380
:return: A dict mapping (file_id, revision_id) tuples to a list of
381
parents, also (file_id, revision_id) tuples.
384
return self._real_repository._generate_text_key_index()
386
@symbol_versioning.deprecated_method(symbol_versioning.one_four)
387
def get_revision_graph(self, revision_id=None):
388
"""See Repository.get_revision_graph()."""
389
return self._get_revision_graph(revision_id)
391
def _get_revision_graph(self, revision_id):
392
"""Private method for using with old (< 1.2) servers to fallback."""
393
if revision_id is None:
395
elif revision.is_null(revision_id):
398
path = self.bzrdir._path_for_remote_call(self._client)
400
response = self._client.call_expecting_body(
401
'Repository.get_revision_graph', path, revision_id)
402
except errors.ErrorFromSmartServer, err:
403
self._translate_error(err)
404
response_tuple, response_handler = response
405
if response_tuple[0] != 'ok':
406
raise errors.UnexpectedSmartServerResponse(response_tuple)
407
coded = response_handler.read_body_bytes()
409
# no revisions in this repository!
411
lines = coded.split('\n')
414
d = tuple(line.split())
415
revision_graph[d[0]] = d[1:]
417
return revision_graph
419
def has_revision(self, revision_id):
420
"""See Repository.has_revision()."""
421
if revision_id == NULL_REVISION:
422
# The null revision is always present.
424
path = self.bzrdir._path_for_remote_call(self._client)
425
response = self._client.call(
426
'Repository.has_revision', path, revision_id)
427
if response[0] not in ('yes', 'no'):
428
raise errors.UnexpectedSmartServerResponse(response)
429
if response[0] == 'yes':
431
for fallback_repo in self._fallback_repositories:
432
if fallback_repo.has_revision(revision_id):
436
def has_revisions(self, revision_ids):
437
"""See Repository.has_revisions()."""
438
# FIXME: This does many roundtrips, particularly when there are
439
# fallback repositories. -- mbp 20080905
441
for revision_id in revision_ids:
442
if self.has_revision(revision_id):
443
result.add(revision_id)
446
def has_same_location(self, other):
447
return (self.__class__ == other.__class__ and
448
self.bzrdir.transport.base == other.bzrdir.transport.base)
450
def get_graph(self, other_repository=None):
451
"""Return the graph for this repository format"""
452
parents_provider = self
453
if (other_repository is not None and
454
other_repository.bzrdir.transport.base !=
455
self.bzrdir.transport.base):
456
parents_provider = graph._StackedParentsProvider(
457
[parents_provider, other_repository._make_parents_provider()])
458
return graph.Graph(parents_provider)
460
def gather_stats(self, revid=None, committers=None):
461
"""See Repository.gather_stats()."""
462
path = self.bzrdir._path_for_remote_call(self._client)
463
# revid can be None to indicate no revisions, not just NULL_REVISION
464
if revid is None or revision.is_null(revid):
468
if committers is None or not committers:
469
fmt_committers = 'no'
471
fmt_committers = 'yes'
472
response_tuple, response_handler = self._client.call_expecting_body(
473
'Repository.gather_stats', path, fmt_revid, fmt_committers)
474
if response_tuple[0] != 'ok':
475
raise errors.UnexpectedSmartServerResponse(response_tuple)
477
body = response_handler.read_body_bytes()
479
for line in body.split('\n'):
482
key, val_text = line.split(':')
483
if key in ('revisions', 'size', 'committers'):
484
result[key] = int(val_text)
485
elif key in ('firstrev', 'latestrev'):
486
values = val_text.split(' ')[1:]
487
result[key] = (float(values[0]), long(values[1]))
491
def find_branches(self, using=False):
492
"""See Repository.find_branches()."""
493
# should be an API call to the server.
495
return self._real_repository.find_branches(using=using)
497
def get_physical_lock_status(self):
498
"""See Repository.get_physical_lock_status()."""
499
# should be an API call to the server.
501
return self._real_repository.get_physical_lock_status()
503
def is_in_write_group(self):
504
"""Return True if there is an open write group.
506
write groups are only applicable locally for the smart server..
508
if self._real_repository:
509
return self._real_repository.is_in_write_group()
512
return self._lock_count >= 1
515
"""See Repository.is_shared()."""
516
path = self.bzrdir._path_for_remote_call(self._client)
517
response = self._client.call('Repository.is_shared', path)
518
if response[0] not in ('yes', 'no'):
519
raise SmartProtocolError('unexpected response code %s' % (response,))
520
return response[0] == 'yes'
522
def is_write_locked(self):
523
return self._lock_mode == 'w'
526
# wrong eventually - want a local lock cache context
527
if not self._lock_mode:
528
self._lock_mode = 'r'
530
self._parents_map = {}
531
if 'hpss' in debug.debug_flags:
532
self._requested_parents = set()
533
if self._real_repository is not None:
534
self._real_repository.lock_read()
536
self._lock_count += 1
538
def _remote_lock_write(self, token):
539
path = self.bzrdir._path_for_remote_call(self._client)
543
response = self._client.call('Repository.lock_write', path, token)
544
except errors.ErrorFromSmartServer, err:
545
self._translate_error(err, token=token)
547
if response[0] == 'ok':
551
raise errors.UnexpectedSmartServerResponse(response)
553
def lock_write(self, token=None, _skip_rpc=False):
554
if not self._lock_mode:
556
if self._lock_token is not None:
557
if token != self._lock_token:
558
raise errors.TokenMismatch(token, self._lock_token)
559
self._lock_token = token
561
self._lock_token = self._remote_lock_write(token)
562
# if self._lock_token is None, then this is something like packs or
563
# svn where we don't get to lock the repo, or a weave style repository
564
# where we cannot lock it over the wire and attempts to do so will
566
if self._real_repository is not None:
567
self._real_repository.lock_write(token=self._lock_token)
568
if token is not None:
569
self._leave_lock = True
571
self._leave_lock = False
572
self._lock_mode = 'w'
574
self._parents_map = {}
575
if 'hpss' in debug.debug_flags:
576
self._requested_parents = set()
577
elif self._lock_mode == 'r':
578
raise errors.ReadOnlyError(self)
580
self._lock_count += 1
581
return self._lock_token or None
583
def leave_lock_in_place(self):
584
if not self._lock_token:
585
raise NotImplementedError(self.leave_lock_in_place)
586
self._leave_lock = True
588
def dont_leave_lock_in_place(self):
589
if not self._lock_token:
590
raise NotImplementedError(self.dont_leave_lock_in_place)
591
self._leave_lock = False
593
def _set_real_repository(self, repository):
594
"""Set the _real_repository for this repository.
596
:param repository: The repository to fallback to for non-hpss
597
implemented operations.
599
if self._real_repository is not None:
600
raise AssertionError('_real_repository is already set')
601
if isinstance(repository, RemoteRepository):
602
raise AssertionError()
603
self._real_repository = repository
604
for fb in self._fallback_repositories:
605
self._real_repository.add_fallback_repository(fb)
606
if self._lock_mode == 'w':
607
# if we are already locked, the real repository must be able to
608
# acquire the lock with our token.
609
self._real_repository.lock_write(self._lock_token)
610
elif self._lock_mode == 'r':
611
self._real_repository.lock_read()
613
def start_write_group(self):
614
"""Start a write group on the decorated repository.
616
Smart methods peform operations in a single step so this api
617
is not really applicable except as a compatibility thunk
618
for older plugins that don't use e.g. the CommitBuilder
622
return self._real_repository.start_write_group()
624
def _unlock(self, token):
625
path = self.bzrdir._path_for_remote_call(self._client)
627
# with no token the remote repository is not persistently locked.
630
response = self._client.call('Repository.unlock', path, token)
631
except errors.ErrorFromSmartServer, err:
632
self._translate_error(err, token=token)
633
if response == ('ok',):
636
raise errors.UnexpectedSmartServerResponse(response)
639
self._lock_count -= 1
640
if self._lock_count > 0:
642
self._parents_map = None
643
if 'hpss' in debug.debug_flags:
644
self._requested_parents = None
645
old_mode = self._lock_mode
646
self._lock_mode = None
648
# The real repository is responsible at present for raising an
649
# exception if it's in an unfinished write group. However, it
650
# normally will *not* actually remove the lock from disk - that's
651
# done by the server on receiving the Repository.unlock call.
652
# This is just to let the _real_repository stay up to date.
653
if self._real_repository is not None:
654
self._real_repository.unlock()
656
# The rpc-level lock should be released even if there was a
657
# problem releasing the vfs-based lock.
659
# Only write-locked repositories need to make a remote method
660
# call to perfom the unlock.
661
old_token = self._lock_token
662
self._lock_token = None
663
if not self._leave_lock:
664
self._unlock(old_token)
666
def break_lock(self):
667
# should hand off to the network
669
return self._real_repository.break_lock()
671
def _get_tarball(self, compression):
672
"""Return a TemporaryFile containing a repository tarball.
674
Returns None if the server does not support sending tarballs.
677
path = self.bzrdir._path_for_remote_call(self._client)
679
response, protocol = self._client.call_expecting_body(
680
'Repository.tarball', path, compression)
681
except errors.UnknownSmartMethod:
682
protocol.cancel_read_body()
684
if response[0] == 'ok':
685
# Extract the tarball and return it
686
t = tempfile.NamedTemporaryFile()
687
# TODO: rpc layer should read directly into it...
688
t.write(protocol.read_body_bytes())
691
raise errors.UnexpectedSmartServerResponse(response)
693
def sprout(self, to_bzrdir, revision_id=None):
694
# TODO: Option to control what format is created?
696
dest_repo = self._real_repository._format.initialize(to_bzrdir,
698
dest_repo.fetch(self, revision_id=revision_id)
701
### These methods are just thin shims to the VFS object for now.
703
def revision_tree(self, revision_id):
705
return self._real_repository.revision_tree(revision_id)
707
def get_serializer_format(self):
709
return self._real_repository.get_serializer_format()
711
def get_commit_builder(self, branch, parents, config, timestamp=None,
712
timezone=None, committer=None, revprops=None,
714
# FIXME: It ought to be possible to call this without immediately
715
# triggering _ensure_real. For now it's the easiest thing to do.
717
real_repo = self._real_repository
718
builder = real_repo.get_commit_builder(branch, parents,
719
config, timestamp=timestamp, timezone=timezone,
720
committer=committer, revprops=revprops, revision_id=revision_id)
723
def add_fallback_repository(self, repository):
724
"""Add a repository to use for looking up data not held locally.
726
:param repository: A repository.
728
# XXX: At the moment the RemoteRepository will allow fallbacks
729
# unconditionally - however, a _real_repository will usually exist,
730
# and may raise an error if it's not accommodated by the underlying
731
# format. Eventually we should check when opening the repository
732
# whether it's willing to allow them or not.
734
# We need to accumulate additional repositories here, to pass them in
736
self._fallback_repositories.append(repository)
737
# They are also seen by the fallback repository. If it doesn't exist
738
# yet they'll be added then. This implicitly copies them.
741
def add_inventory(self, revid, inv, parents):
743
return self._real_repository.add_inventory(revid, inv, parents)
745
def add_revision(self, rev_id, rev, inv=None, config=None):
747
return self._real_repository.add_revision(
748
rev_id, rev, inv=inv, config=config)
751
def get_inventory(self, revision_id):
753
return self._real_repository.get_inventory(revision_id)
755
def iter_inventories(self, revision_ids):
757
return self._real_repository.iter_inventories(revision_ids)
760
def get_revision(self, revision_id):
762
return self._real_repository.get_revision(revision_id)
764
def get_transaction(self):
766
return self._real_repository.get_transaction()
769
def clone(self, a_bzrdir, revision_id=None):
771
return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
773
def make_working_trees(self):
774
"""See Repository.make_working_trees"""
776
return self._real_repository.make_working_trees()
778
def revision_ids_to_search_result(self, result_set):
779
"""Convert a set of revision ids to a graph SearchResult."""
780
result_parents = set()
781
for parents in self.get_graph().get_parent_map(
782
result_set).itervalues():
783
result_parents.update(parents)
784
included_keys = result_set.intersection(result_parents)
785
start_keys = result_set.difference(included_keys)
786
exclude_keys = result_parents.difference(result_set)
787
result = graph.SearchResult(start_keys, exclude_keys,
788
len(result_set), result_set)
792
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
793
"""Return the revision ids that other has that this does not.
795
These are returned in topological order.
797
revision_id: only return revision ids included by revision_id.
799
return repository.InterRepository.get(
800
other, self).search_missing_revision_ids(revision_id, find_ghosts)
802
def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
803
if self.has_same_location(source):
804
# check that last_revision is in 'from' and then return a
806
if (revision_id is not None and
807
not revision.is_null(revision_id)):
808
self.get_revision(revision_id)
810
inter = repository.InterRepository.get(source, self)
812
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
814
except NotImplementedError:
815
raise errors.IncompatibleRepositories(source, self)
817
def create_bundle(self, target, base, fileobj, format=None):
819
self._real_repository.create_bundle(target, base, fileobj, format)
822
def get_ancestry(self, revision_id, topo_sorted=True):
824
return self._real_repository.get_ancestry(revision_id, topo_sorted)
826
def fileids_altered_by_revision_ids(self, revision_ids):
828
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
830
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
832
return self._real_repository._get_versioned_file_checker(
833
revisions, revision_versions_cache)
835
def iter_files_bytes(self, desired_files):
836
"""See Repository.iter_file_bytes.
839
return self._real_repository.iter_files_bytes(desired_files)
842
def _fetch_order(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_order
852
def _fetch_uses_deltas(self):
853
"""Decorate the real repository for now.
855
In the long term getting this back from the remote repository as part
856
of open would be more efficient.
859
return self._real_repository._fetch_uses_deltas
862
def _fetch_reconcile(self):
863
"""Decorate the real repository for now.
865
In the long term getting this back from the remote repository as part
866
of open would be more efficient.
869
return self._real_repository._fetch_reconcile
871
def get_parent_map(self, keys):
872
"""See bzrlib.Graph.get_parent_map()."""
873
# Hack to build up the caching logic.
874
ancestry = self._parents_map
876
# Repository is not locked, so there's no cache.
877
missing_revisions = set(keys)
880
missing_revisions = set(key for key in keys if key not in ancestry)
881
if missing_revisions:
882
parent_map = self._get_parent_map(missing_revisions)
883
if 'hpss' in debug.debug_flags:
884
mutter('retransmitted revisions: %d of %d',
885
len(set(ancestry).intersection(parent_map)),
887
ancestry.update(parent_map)
888
present_keys = [k for k in keys if k in ancestry]
889
if 'hpss' in debug.debug_flags:
890
if self._requested_parents is not None and len(ancestry) != 0:
891
self._requested_parents.update(present_keys)
892
mutter('Current RemoteRepository graph hit rate: %d%%',
893
100.0 * len(self._requested_parents) / len(ancestry))
894
return dict((k, ancestry[k]) for k in present_keys)
896
def _get_parent_map(self, keys):
897
"""Helper for get_parent_map that performs the RPC."""
898
medium = self._client._medium
899
if medium._is_remote_before((1, 2)):
900
# We already found out that the server can't understand
901
# Repository.get_parent_map requests, so just fetch the whole
903
# XXX: Note that this will issue a deprecation warning. This is ok
904
# :- its because we're working with a deprecated server anyway, and
905
# the user will almost certainly have seen a warning about the
906
# server version already.
907
rg = self.get_revision_graph()
908
# There is an api discrepency between get_parent_map and
909
# get_revision_graph. Specifically, a "key:()" pair in
910
# get_revision_graph just means a node has no parents. For
911
# "get_parent_map" it means the node is a ghost. So fix up the
912
# graph to correct this.
913
# https://bugs.launchpad.net/bzr/+bug/214894
914
# There is one other "bug" which is that ghosts in
915
# get_revision_graph() are not returned at all. But we won't worry
916
# about that for now.
917
for node_id, parent_ids in rg.iteritems():
919
rg[node_id] = (NULL_REVISION,)
920
rg[NULL_REVISION] = ()
925
raise ValueError('get_parent_map(None) is not valid')
926
if NULL_REVISION in keys:
927
keys.discard(NULL_REVISION)
928
found_parents = {NULL_REVISION:()}
933
# TODO(Needs analysis): We could assume that the keys being requested
934
# from get_parent_map are in a breadth first search, so typically they
935
# will all be depth N from some common parent, and we don't have to
936
# have the server iterate from the root parent, but rather from the
937
# keys we're searching; and just tell the server the keyspace we
938
# already have; but this may be more traffic again.
940
# Transform self._parents_map into a search request recipe.
941
# TODO: Manage this incrementally to avoid covering the same path
942
# repeatedly. (The server will have to on each request, but the less
943
# work done the better).
944
parents_map = self._parents_map
945
if parents_map is None:
946
# Repository is not locked, so there's no cache.
948
start_set = set(parents_map)
949
result_parents = set()
950
for parents in parents_map.itervalues():
951
result_parents.update(parents)
952
stop_keys = result_parents.difference(start_set)
953
included_keys = start_set.intersection(result_parents)
954
start_set.difference_update(included_keys)
955
recipe = (start_set, stop_keys, len(parents_map))
956
body = self._serialise_search_recipe(recipe)
957
path = self.bzrdir._path_for_remote_call(self._client)
959
if type(key) is not str:
961
"key %r not a plain string" % (key,))
962
verb = 'Repository.get_parent_map'
963
args = (path,) + tuple(keys)
965
response = self._client.call_with_body_bytes_expecting_body(
966
verb, args, self._serialise_search_recipe(recipe))
967
except errors.UnknownSmartMethod:
968
# Server does not support this method, so get the whole graph.
969
# Worse, we have to force a disconnection, because the server now
970
# doesn't realise it has a body on the wire to consume, so the
971
# only way to recover is to abandon the connection.
973
'Server is too old for fast get_parent_map, reconnecting. '
974
'(Upgrade the server to Bazaar 1.2 to avoid this)')
976
# To avoid having to disconnect repeatedly, we keep track of the
977
# fact the server doesn't understand remote methods added in 1.2.
978
medium._remember_remote_is_before((1, 2))
979
return self.get_revision_graph(None)
980
response_tuple, response_handler = response
981
if response_tuple[0] not in ['ok']:
982
response_handler.cancel_read_body()
983
raise errors.UnexpectedSmartServerResponse(response_tuple)
984
if response_tuple[0] == 'ok':
985
coded = bz2.decompress(response_handler.read_body_bytes())
989
lines = coded.split('\n')
992
d = tuple(line.split())
994
revision_graph[d[0]] = d[1:]
996
# No parents - so give the Graph result (NULL_REVISION,).
997
revision_graph[d[0]] = (NULL_REVISION,)
998
return revision_graph
1001
def get_signature_text(self, revision_id):
1003
return self._real_repository.get_signature_text(revision_id)
1006
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
1007
def get_revision_graph_with_ghosts(self, revision_ids=None):
1009
return self._real_repository.get_revision_graph_with_ghosts(
1010
revision_ids=revision_ids)
1013
def get_inventory_xml(self, revision_id):
1015
return self._real_repository.get_inventory_xml(revision_id)
1017
def deserialise_inventory(self, revision_id, xml):
1019
return self._real_repository.deserialise_inventory(revision_id, xml)
1021
def reconcile(self, other=None, thorough=False):
1023
return self._real_repository.reconcile(other=other, thorough=thorough)
1025
def all_revision_ids(self):
1027
return self._real_repository.all_revision_ids()
1030
def get_deltas_for_revisions(self, revisions):
1032
return self._real_repository.get_deltas_for_revisions(revisions)
1035
def get_revision_delta(self, revision_id):
1037
return self._real_repository.get_revision_delta(revision_id)
1040
def revision_trees(self, revision_ids):
1042
return self._real_repository.revision_trees(revision_ids)
1045
def get_revision_reconcile(self, revision_id):
1047
return self._real_repository.get_revision_reconcile(revision_id)
1050
def check(self, revision_ids=None):
1052
return self._real_repository.check(revision_ids=revision_ids)
1054
def copy_content_into(self, destination, revision_id=None):
1056
return self._real_repository.copy_content_into(
1057
destination, revision_id=revision_id)
1059
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1060
# get a tarball of the remote repository, and copy from that into the
1062
from bzrlib import osutils
1064
# TODO: Maybe a progress bar while streaming the tarball?
1065
note("Copying repository content as tarball...")
1066
tar_file = self._get_tarball('bz2')
1067
if tar_file is None:
1069
destination = to_bzrdir.create_repository()
1071
tar = tarfile.open('repository', fileobj=tar_file,
1073
tmpdir = osutils.mkdtemp()
1075
_extract_tar(tar, tmpdir)
1076
tmp_bzrdir = BzrDir.open(tmpdir)
1077
tmp_repo = tmp_bzrdir.open_repository()
1078
tmp_repo.copy_content_into(destination, revision_id)
1080
osutils.rmtree(tmpdir)
1084
# TODO: Suggestion from john: using external tar is much faster than
1085
# python's tarfile library, but it may not work on windows.
1088
def inventories(self):
1089
"""Decorate the real repository for now.
1091
In the long term a full blown network facility is needed to
1092
avoid creating a real repository object locally.
1095
return self._real_repository.inventories
1099
"""Compress the data within the repository.
1101
This is not currently implemented within the smart server.
1104
return self._real_repository.pack()
1107
def revisions(self):
1108
"""Decorate the real repository for now.
1110
In the short term this should become a real object to intercept graph
1113
In the long term a full blown network facility is needed.
1116
return self._real_repository.revisions
1118
def set_make_working_trees(self, new_value):
1120
self._real_repository.set_make_working_trees(new_value)
1123
def signatures(self):
1124
"""Decorate the real repository for now.
1126
In the long term a full blown network facility is needed to avoid
1127
creating a real repository object locally.
1130
return self._real_repository.signatures
1133
def sign_revision(self, revision_id, gpg_strategy):
1135
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1139
"""Decorate the real repository for now.
1141
In the long term a full blown network facility is needed to avoid
1142
creating a real repository object locally.
1145
return self._real_repository.texts
1148
def get_revisions(self, revision_ids):
1150
return self._real_repository.get_revisions(revision_ids)
1152
def supports_rich_root(self):
1154
return self._real_repository.supports_rich_root()
1156
def iter_reverse_revision_history(self, revision_id):
1158
return self._real_repository.iter_reverse_revision_history(revision_id)
1161
def _serializer(self):
1163
return self._real_repository._serializer
1165
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1167
return self._real_repository.store_revision_signature(
1168
gpg_strategy, plaintext, revision_id)
1170
def add_signature_text(self, revision_id, signature):
1172
return self._real_repository.add_signature_text(revision_id, signature)
1174
def has_signature_for_revision_id(self, revision_id):
1176
return self._real_repository.has_signature_for_revision_id(revision_id)
1178
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1180
return self._real_repository.item_keys_introduced_by(revision_ids,
1181
_files_pb=_files_pb)
1183
def revision_graph_can_have_wrong_parents(self):
1184
# The answer depends on the remote repo format.
1186
return self._real_repository.revision_graph_can_have_wrong_parents()
1188
def _find_inconsistent_revision_parents(self):
1190
return self._real_repository._find_inconsistent_revision_parents()
1192
def _check_for_inconsistent_revision_parents(self):
1194
return self._real_repository._check_for_inconsistent_revision_parents()
1196
def _make_parents_provider(self):
1199
def _serialise_search_recipe(self, recipe):
1200
"""Serialise a graph search recipe.
1202
:param recipe: A search recipe (start, stop, count).
1203
:return: Serialised bytes.
1205
start_keys = ' '.join(recipe[0])
1206
stop_keys = ' '.join(recipe[1])
1207
count = str(recipe[2])
1208
return '\n'.join((start_keys, stop_keys, count))
1211
class RemoteBranchLockableFiles(LockableFiles):
1212
"""A 'LockableFiles' implementation that talks to a smart server.
1214
This is not a public interface class.
1217
def __init__(self, bzrdir, _client):
1218
self.bzrdir = bzrdir
1219
self._client = _client
1220
self._need_find_modes = True
1221
LockableFiles.__init__(
1222
self, bzrdir.get_branch_transport(None),
1223
'lock', lockdir.LockDir)
1225
def _find_modes(self):
1226
# RemoteBranches don't let the client set the mode of control files.
1227
self._dir_mode = None
1228
self._file_mode = None
1231
class RemoteBranchFormat(branch.BranchFormat):
1233
def __eq__(self, other):
1234
return (isinstance(other, RemoteBranchFormat) and
1235
self.__dict__ == other.__dict__)
1237
def get_format_description(self):
1238
return 'Remote BZR Branch'
1240
def get_format_string(self):
1241
return 'Remote BZR Branch'
1243
def open(self, a_bzrdir):
1244
return a_bzrdir.open_branch()
1246
def initialize(self, a_bzrdir):
1247
return a_bzrdir.create_branch()
1249
def supports_tags(self):
1250
# Remote branches might support tags, but we won't know until we
1251
# access the real remote branch.
1255
class RemoteBranch(branch.Branch):
1256
"""Branch stored on a server accessed by HPSS RPC.
1258
At the moment most operations are mapped down to simple file operations.
1261
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1263
"""Create a RemoteBranch instance.
1265
:param real_branch: An optional local implementation of the branch
1266
format, usually accessing the data via the VFS.
1267
:param _client: Private parameter for testing.
1269
# We intentionally don't call the parent class's __init__, because it
1270
# will try to assign to self.tags, which is a property in this subclass.
1271
# And the parent's __init__ doesn't do much anyway.
1272
self._revision_id_to_revno_cache = None
1273
self._revision_history_cache = None
1274
self._last_revision_info_cache = None
1275
self.bzrdir = remote_bzrdir
1276
if _client is not None:
1277
self._client = _client
1279
self._client = remote_bzrdir._client
1280
self.repository = remote_repository
1281
if real_branch is not None:
1282
self._real_branch = real_branch
1283
# Give the remote repository the matching real repo.
1284
real_repo = self._real_branch.repository
1285
if isinstance(real_repo, RemoteRepository):
1286
real_repo._ensure_real()
1287
real_repo = real_repo._real_repository
1288
self.repository._set_real_repository(real_repo)
1289
# Give the branch the remote repository to let fast-pathing happen.
1290
self._real_branch.repository = self.repository
1292
self._real_branch = None
1293
# Fill out expected attributes of branch for bzrlib api users.
1294
self._format = RemoteBranchFormat()
1295
self.base = self.bzrdir.root_transport.base
1296
self._control_files = None
1297
self._lock_mode = None
1298
self._lock_token = None
1299
self._repo_lock_token = None
1300
self._lock_count = 0
1301
self._leave_lock = False
1302
# The base class init is not called, so we duplicate this:
1303
hooks = branch.Branch.hooks['open']
1306
self._setup_stacking()
1308
def _setup_stacking(self):
1309
# configure stacking into the remote repository, by reading it from
1312
fallback_url = self.get_stacked_on_url()
1313
except (errors.NotStacked, errors.UnstackableBranchFormat,
1314
errors.UnstackableRepositoryFormat), e:
1316
# it's relative to this branch...
1317
fallback_url = urlutils.join(self.base, fallback_url)
1318
transports = [self.bzrdir.root_transport]
1319
if self._real_branch is not None:
1320
transports.append(self._real_branch._transport)
1321
fallback_bzrdir = BzrDir.open(fallback_url, transports)
1322
fallback_repo = fallback_bzrdir.open_repository()
1323
self.repository.add_fallback_repository(fallback_repo)
1325
def _get_real_transport(self):
1326
# if we try vfs access, return the real branch's vfs transport
1328
return self._real_branch._transport
1330
_transport = property(_get_real_transport)
1333
return "%s(%s)" % (self.__class__.__name__, self.base)
1337
def _ensure_real(self):
1338
"""Ensure that there is a _real_branch set.
1340
Used before calls to self._real_branch.
1342
if self._real_branch is None:
1343
if not vfs.vfs_enabled():
1344
raise AssertionError('smart server vfs must be enabled '
1345
'to use vfs implementation')
1346
self.bzrdir._ensure_real()
1347
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1348
if self.repository._real_repository is None:
1349
# Give the remote repository the matching real repo.
1350
real_repo = self._real_branch.repository
1351
if isinstance(real_repo, RemoteRepository):
1352
real_repo._ensure_real()
1353
real_repo = real_repo._real_repository
1354
self.repository._set_real_repository(real_repo)
1355
# Give the real branch the remote repository to let fast-pathing
1357
self._real_branch.repository = self.repository
1358
if self._lock_mode == 'r':
1359
self._real_branch.lock_read()
1360
elif self._lock_mode == 'w':
1361
self._real_branch.lock_write(token=self._lock_token)
1363
def _translate_error(self, err, **context):
1364
self.repository._translate_error(err, branch=self, **context)
1366
def _clear_cached_state(self):
1367
super(RemoteBranch, self)._clear_cached_state()
1368
if self._real_branch is not None:
1369
self._real_branch._clear_cached_state()
1371
def _clear_cached_state_of_remote_branch_only(self):
1372
"""Like _clear_cached_state, but doesn't clear the cache of
1375
This is useful when falling back to calling a method of
1376
self._real_branch that changes state. In that case the underlying
1377
branch changes, so we need to invalidate this RemoteBranch's cache of
1378
it. However, there's no need to invalidate the _real_branch's cache
1379
too, in fact doing so might harm performance.
1381
super(RemoteBranch, self)._clear_cached_state()
1384
def control_files(self):
1385
# Defer actually creating RemoteBranchLockableFiles until its needed,
1386
# because it triggers an _ensure_real that we otherwise might not need.
1387
if self._control_files is None:
1388
self._control_files = RemoteBranchLockableFiles(
1389
self.bzrdir, self._client)
1390
return self._control_files
1392
def _get_checkout_format(self):
1394
return self._real_branch._get_checkout_format()
1396
def get_physical_lock_status(self):
1397
"""See Branch.get_physical_lock_status()."""
1398
# should be an API call to the server, as branches must be lockable.
1400
return self._real_branch.get_physical_lock_status()
1402
def get_stacked_on_url(self):
1403
"""Get the URL this branch is stacked against.
1405
:raises NotStacked: If the branch is not stacked.
1406
:raises UnstackableBranchFormat: If the branch does not support
1408
:raises UnstackableRepositoryFormat: If the repository does not support
1412
response = self._client.call('Branch.get_stacked_on_url',
1413
self._remote_path())
1414
if response[0] != 'ok':
1415
raise errors.UnexpectedSmartServerResponse(response)
1417
except errors.ErrorFromSmartServer, err:
1418
# there may not be a repository yet, so we can't call through
1419
# its _translate_error
1420
_translate_error(err, branch=self)
1421
except errors.UnknownSmartMethod, err:
1423
return self._real_branch.get_stacked_on_url()
1425
def lock_read(self):
1426
self.repository.lock_read()
1427
if not self._lock_mode:
1428
self._lock_mode = 'r'
1429
self._lock_count = 1
1430
if self._real_branch is not None:
1431
self._real_branch.lock_read()
1433
self._lock_count += 1
1435
def _remote_lock_write(self, token):
1437
branch_token = repo_token = ''
1439
branch_token = token
1440
repo_token = self.repository.lock_write()
1441
self.repository.unlock()
1443
response = self._client.call(
1444
'Branch.lock_write', self._remote_path(),
1445
branch_token, repo_token or '')
1446
except errors.ErrorFromSmartServer, err:
1447
self._translate_error(err, token=token)
1448
if response[0] != 'ok':
1449
raise errors.UnexpectedSmartServerResponse(response)
1450
ok, branch_token, repo_token = response
1451
return branch_token, repo_token
1453
def lock_write(self, token=None):
1454
if not self._lock_mode:
1455
# Lock the branch and repo in one remote call.
1456
remote_tokens = self._remote_lock_write(token)
1457
self._lock_token, self._repo_lock_token = remote_tokens
1458
if not self._lock_token:
1459
raise SmartProtocolError('Remote server did not return a token!')
1460
# Tell the self.repository object that it is locked.
1461
self.repository.lock_write(
1462
self._repo_lock_token, _skip_rpc=True)
1464
if self._real_branch is not None:
1465
self._real_branch.lock_write(token=self._lock_token)
1466
if token is not None:
1467
self._leave_lock = True
1469
self._leave_lock = False
1470
self._lock_mode = 'w'
1471
self._lock_count = 1
1472
elif self._lock_mode == 'r':
1473
raise errors.ReadOnlyTransaction
1475
if token is not None:
1476
# A token was given to lock_write, and we're relocking, so
1477
# check that the given token actually matches the one we
1479
if token != self._lock_token:
1480
raise errors.TokenMismatch(token, self._lock_token)
1481
self._lock_count += 1
1482
# Re-lock the repository too.
1483
self.repository.lock_write(self._repo_lock_token)
1484
return self._lock_token or None
1486
def _unlock(self, branch_token, repo_token):
1488
response = self._client.call('Branch.unlock', self._remote_path(), branch_token,
1490
except errors.ErrorFromSmartServer, err:
1491
self._translate_error(err, token=str((branch_token, repo_token)))
1492
if response == ('ok',):
1494
raise errors.UnexpectedSmartServerResponse(response)
1498
self._lock_count -= 1
1499
if not self._lock_count:
1500
self._clear_cached_state()
1501
mode = self._lock_mode
1502
self._lock_mode = None
1503
if self._real_branch is not None:
1504
if (not self._leave_lock and mode == 'w' and
1505
self._repo_lock_token):
1506
# If this RemoteBranch will remove the physical lock
1507
# for the repository, make sure the _real_branch
1508
# doesn't do it first. (Because the _real_branch's
1509
# repository is set to be the RemoteRepository.)
1510
self._real_branch.repository.leave_lock_in_place()
1511
self._real_branch.unlock()
1513
# Only write-locked branched need to make a remote method
1514
# call to perfom the unlock.
1516
if not self._lock_token:
1517
raise AssertionError('Locked, but no token!')
1518
branch_token = self._lock_token
1519
repo_token = self._repo_lock_token
1520
self._lock_token = None
1521
self._repo_lock_token = None
1522
if not self._leave_lock:
1523
self._unlock(branch_token, repo_token)
1525
self.repository.unlock()
1527
def break_lock(self):
1529
return self._real_branch.break_lock()
1531
def leave_lock_in_place(self):
1532
if not self._lock_token:
1533
raise NotImplementedError(self.leave_lock_in_place)
1534
self._leave_lock = True
1536
def dont_leave_lock_in_place(self):
1537
if not self._lock_token:
1538
raise NotImplementedError(self.dont_leave_lock_in_place)
1539
self._leave_lock = False
1541
def _last_revision_info(self):
1542
response = self._client.call('Branch.last_revision_info', self._remote_path())
1543
if response[0] != 'ok':
1544
raise SmartProtocolError('unexpected response code %s' % (response,))
1545
revno = int(response[1])
1546
last_revision = response[2]
1547
return (revno, last_revision)
1549
def _gen_revision_history(self):
1550
"""See Branch._gen_revision_history()."""
1551
response_tuple, response_handler = self._client.call_expecting_body(
1552
'Branch.revision_history', self._remote_path())
1553
if response_tuple[0] != 'ok':
1554
raise errors.UnexpectedSmartServerResponse(response_tuple)
1555
result = response_handler.read_body_bytes().split('\x00')
1560
def _remote_path(self):
1561
return self.bzrdir._path_for_remote_call(self._client)
1563
def _set_last_revision_descendant(self, revision_id, other_branch,
1564
allow_diverged=False, allow_overwrite_descendant=False):
1566
response = self._client.call('Branch.set_last_revision_ex',
1567
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id,
1568
int(allow_diverged), int(allow_overwrite_descendant))
1569
except errors.ErrorFromSmartServer, err:
1570
self._translate_error(err, other_branch=other_branch)
1571
self._clear_cached_state()
1572
if len(response) != 3 and response[0] != 'ok':
1573
raise errors.UnexpectedSmartServerResponse(response)
1574
new_revno, new_revision_id = response[1:]
1575
self._last_revision_info_cache = new_revno, new_revision_id
1576
if self._real_branch is not None:
1577
cache = new_revno, new_revision_id
1578
self._real_branch._last_revision_info_cache = cache
1580
def _set_last_revision(self, revision_id):
1581
self._clear_cached_state()
1583
response = self._client.call('Branch.set_last_revision',
1584
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id)
1585
except errors.ErrorFromSmartServer, err:
1586
self._translate_error(err)
1587
if response != ('ok',):
1588
raise errors.UnexpectedSmartServerResponse(response)
1591
def set_revision_history(self, rev_history):
1592
# Send just the tip revision of the history; the server will generate
1593
# the full history from that. If the revision doesn't exist in this
1594
# branch, NoSuchRevision will be raised.
1595
if rev_history == []:
1598
rev_id = rev_history[-1]
1599
self._set_last_revision(rev_id)
1600
self._cache_revision_history(rev_history)
1602
def get_parent(self):
1604
return self._real_branch.get_parent()
1606
def set_parent(self, url):
1608
return self._real_branch.set_parent(url)
1610
def set_stacked_on_url(self, stacked_location):
1611
"""Set the URL this branch is stacked against.
1613
:raises UnstackableBranchFormat: If the branch does not support
1615
:raises UnstackableRepositoryFormat: If the repository does not support
1619
return self._real_branch.set_stacked_on_url(stacked_location)
1621
def sprout(self, to_bzrdir, revision_id=None):
1622
# Like Branch.sprout, except that it sprouts a branch in the default
1623
# format, because RemoteBranches can't be created at arbitrary URLs.
1624
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1625
# to_bzrdir.create_branch...
1627
result = self._real_branch._format.initialize(to_bzrdir)
1628
self.copy_content_into(result, revision_id=revision_id)
1629
result.set_parent(self.bzrdir.root_transport.base)
1633
def pull(self, source, overwrite=False, stop_revision=None,
1635
self._clear_cached_state_of_remote_branch_only()
1637
return self._real_branch.pull(
1638
source, overwrite=overwrite, stop_revision=stop_revision,
1639
_override_hook_target=self, **kwargs)
1642
def push(self, target, overwrite=False, stop_revision=None):
1644
return self._real_branch.push(
1645
target, overwrite=overwrite, stop_revision=stop_revision,
1646
_override_hook_source_branch=self)
1648
def is_locked(self):
1649
return self._lock_count >= 1
1652
def revision_id_to_revno(self, revision_id):
1654
return self._real_branch.revision_id_to_revno(revision_id)
1657
def set_last_revision_info(self, revno, revision_id):
1658
revision_id = ensure_null(revision_id)
1660
response = self._client.call('Branch.set_last_revision_info',
1661
self._remote_path(), self._lock_token, self._repo_lock_token, str(revno), revision_id)
1662
except errors.UnknownSmartMethod:
1664
self._clear_cached_state_of_remote_branch_only()
1665
self._real_branch.set_last_revision_info(revno, revision_id)
1666
self._last_revision_info_cache = revno, revision_id
1668
except errors.ErrorFromSmartServer, err:
1669
self._translate_error(err)
1670
if response == ('ok',):
1671
self._clear_cached_state()
1672
self._last_revision_info_cache = revno, revision_id
1673
# Update the _real_branch's cache too.
1674
if self._real_branch is not None:
1675
cache = self._last_revision_info_cache
1676
self._real_branch._last_revision_info_cache = cache
1678
raise errors.UnexpectedSmartServerResponse(response)
1681
def generate_revision_history(self, revision_id, last_rev=None,
1683
medium = self._client._medium
1684
if not medium._is_remote_before((1, 6)):
1686
self._set_last_revision_descendant(revision_id, other_branch,
1687
allow_diverged=True, allow_overwrite_descendant=True)
1689
except errors.UnknownSmartMethod:
1690
medium._remember_remote_is_before((1, 6))
1691
self._clear_cached_state_of_remote_branch_only()
1693
self._real_branch.generate_revision_history(
1694
revision_id, last_rev=last_rev, other_branch=other_branch)
1699
return self._real_branch.tags
1701
def set_push_location(self, location):
1703
return self._real_branch.set_push_location(location)
1706
def update_revisions(self, other, stop_revision=None, overwrite=False,
1708
"""See Branch.update_revisions."""
1711
if stop_revision is None:
1712
stop_revision = other.last_revision()
1713
if revision.is_null(stop_revision):
1714
# if there are no commits, we're done.
1716
self.fetch(other, stop_revision)
1719
# Just unconditionally set the new revision. We don't care if
1720
# the branches have diverged.
1721
self._set_last_revision(stop_revision)
1723
medium = self._client._medium
1724
if not medium._is_remote_before((1, 6)):
1726
self._set_last_revision_descendant(stop_revision, other)
1728
except errors.UnknownSmartMethod:
1729
medium._remember_remote_is_before((1, 6))
1730
# Fallback for pre-1.6 servers: check for divergence
1731
# client-side, then do _set_last_revision.
1732
last_rev = revision.ensure_null(self.last_revision())
1734
graph = self.repository.get_graph()
1735
if self._check_if_descendant_or_diverged(
1736
stop_revision, last_rev, graph, other):
1737
# stop_revision is a descendant of last_rev, but we aren't
1738
# overwriting, so we're done.
1740
self._set_last_revision(stop_revision)
1745
def _extract_tar(tar, to_dir):
1746
"""Extract all the contents of a tarfile object.
1748
A replacement for extractall, which is not present in python2.4
1751
tar.extract(tarinfo, to_dir)
1754
def _translate_error(err, **context):
1755
"""Translate an ErrorFromSmartServer into a more useful error.
1757
Possible context keys:
1764
If the error from the server doesn't match a known pattern, then
1765
UnknownErrorFromSmartServer is raised.
1769
return context[name]
1770
except KeyError, keyErr:
1771
mutter('Missing key %r in context %r', keyErr.args[0], context)
1773
if err.error_verb == 'NoSuchRevision':
1774
raise NoSuchRevision(find('branch'), err.error_args[0])
1775
elif err.error_verb == 'nosuchrevision':
1776
raise NoSuchRevision(find('repository'), err.error_args[0])
1777
elif err.error_tuple == ('nobranch',):
1778
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1779
elif err.error_verb == 'norepository':
1780
raise errors.NoRepositoryPresent(find('bzrdir'))
1781
elif err.error_verb == 'LockContention':
1782
raise errors.LockContention('(remote lock)')
1783
elif err.error_verb == 'UnlockableTransport':
1784
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1785
elif err.error_verb == 'LockFailed':
1786
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1787
elif err.error_verb == 'TokenMismatch':
1788
raise errors.TokenMismatch(find('token'), '(remote token)')
1789
elif err.error_verb == 'Diverged':
1790
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1791
elif err.error_verb == 'TipChangeRejected':
1792
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
1793
elif err.error_verb == 'UnstackableBranchFormat':
1794
raise errors.UnstackableBranchFormat(*err.error_args)
1795
elif err.error_verb == 'UnstackableRepositoryFormat':
1796
raise errors.UnstackableRepositoryFormat(*err.error_args)
1797
elif err.error_verb == 'NotStacked':
1798
raise errors.NotStacked(branch=find('branch'))
1799
raise errors.UnknownErrorFromSmartServer(err)