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):
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)
811
return self._real_repository.fetch(
812
source, revision_id=revision_id, pb=pb)
814
def create_bundle(self, target, base, fileobj, format=None):
816
self._real_repository.create_bundle(target, base, fileobj, format)
819
def get_ancestry(self, revision_id, topo_sorted=True):
821
return self._real_repository.get_ancestry(revision_id, topo_sorted)
823
def fileids_altered_by_revision_ids(self, revision_ids):
825
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
827
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
829
return self._real_repository._get_versioned_file_checker(
830
revisions, revision_versions_cache)
832
def iter_files_bytes(self, desired_files):
833
"""See Repository.iter_file_bytes.
836
return self._real_repository.iter_files_bytes(desired_files)
839
def _fetch_order(self):
840
"""Decorate the real repository for now.
842
In the long term getting this back from the remote repository as part
843
of open would be more efficient.
846
return self._real_repository._fetch_order
849
def _fetch_uses_deltas(self):
850
"""Decorate the real repository for now.
852
In the long term getting this back from the remote repository as part
853
of open would be more efficient.
856
return self._real_repository._fetch_uses_deltas
859
def _fetch_reconcile(self):
860
"""Decorate the real repository for now.
862
In the long term getting this back from the remote repository as part
863
of open would be more efficient.
866
return self._real_repository._fetch_reconcile
868
def get_parent_map(self, keys):
869
"""See bzrlib.Graph.get_parent_map()."""
870
# Hack to build up the caching logic.
871
ancestry = self._parents_map
873
# Repository is not locked, so there's no cache.
874
missing_revisions = set(keys)
877
missing_revisions = set(key for key in keys if key not in ancestry)
878
if missing_revisions:
879
parent_map = self._get_parent_map(missing_revisions)
880
if 'hpss' in debug.debug_flags:
881
mutter('retransmitted revisions: %d of %d',
882
len(set(ancestry).intersection(parent_map)),
884
ancestry.update(parent_map)
885
present_keys = [k for k in keys if k in ancestry]
886
if 'hpss' in debug.debug_flags:
887
if self._requested_parents is not None and len(ancestry) != 0:
888
self._requested_parents.update(present_keys)
889
mutter('Current RemoteRepository graph hit rate: %d%%',
890
100.0 * len(self._requested_parents) / len(ancestry))
891
return dict((k, ancestry[k]) for k in present_keys)
893
def _get_parent_map(self, keys):
894
"""Helper for get_parent_map that performs the RPC."""
895
medium = self._client._medium
896
if medium._is_remote_before((1, 2)):
897
# We already found out that the server can't understand
898
# Repository.get_parent_map requests, so just fetch the whole
900
# XXX: Note that this will issue a deprecation warning. This is ok
901
# :- its because we're working with a deprecated server anyway, and
902
# the user will almost certainly have seen a warning about the
903
# server version already.
904
rg = self.get_revision_graph()
905
# There is an api discrepency between get_parent_map and
906
# get_revision_graph. Specifically, a "key:()" pair in
907
# get_revision_graph just means a node has no parents. For
908
# "get_parent_map" it means the node is a ghost. So fix up the
909
# graph to correct this.
910
# https://bugs.launchpad.net/bzr/+bug/214894
911
# There is one other "bug" which is that ghosts in
912
# get_revision_graph() are not returned at all. But we won't worry
913
# about that for now.
914
for node_id, parent_ids in rg.iteritems():
916
rg[node_id] = (NULL_REVISION,)
917
rg[NULL_REVISION] = ()
922
raise ValueError('get_parent_map(None) is not valid')
923
if NULL_REVISION in keys:
924
keys.discard(NULL_REVISION)
925
found_parents = {NULL_REVISION:()}
930
# TODO(Needs analysis): We could assume that the keys being requested
931
# from get_parent_map are in a breadth first search, so typically they
932
# will all be depth N from some common parent, and we don't have to
933
# have the server iterate from the root parent, but rather from the
934
# keys we're searching; and just tell the server the keyspace we
935
# already have; but this may be more traffic again.
937
# Transform self._parents_map into a search request recipe.
938
# TODO: Manage this incrementally to avoid covering the same path
939
# repeatedly. (The server will have to on each request, but the less
940
# work done the better).
941
parents_map = self._parents_map
942
if parents_map is None:
943
# Repository is not locked, so there's no cache.
945
start_set = set(parents_map)
946
result_parents = set()
947
for parents in parents_map.itervalues():
948
result_parents.update(parents)
949
stop_keys = result_parents.difference(start_set)
950
included_keys = start_set.intersection(result_parents)
951
start_set.difference_update(included_keys)
952
recipe = (start_set, stop_keys, len(parents_map))
953
body = self._serialise_search_recipe(recipe)
954
path = self.bzrdir._path_for_remote_call(self._client)
956
if type(key) is not str:
958
"key %r not a plain string" % (key,))
959
verb = 'Repository.get_parent_map'
960
args = (path,) + tuple(keys)
962
response = self._client.call_with_body_bytes_expecting_body(
963
verb, args, self._serialise_search_recipe(recipe))
964
except errors.UnknownSmartMethod:
965
# Server does not support this method, so get the whole graph.
966
# Worse, we have to force a disconnection, because the server now
967
# doesn't realise it has a body on the wire to consume, so the
968
# only way to recover is to abandon the connection.
970
'Server is too old for fast get_parent_map, reconnecting. '
971
'(Upgrade the server to Bazaar 1.2 to avoid this)')
973
# To avoid having to disconnect repeatedly, we keep track of the
974
# fact the server doesn't understand remote methods added in 1.2.
975
medium._remember_remote_is_before((1, 2))
976
return self.get_revision_graph(None)
977
response_tuple, response_handler = response
978
if response_tuple[0] not in ['ok']:
979
response_handler.cancel_read_body()
980
raise errors.UnexpectedSmartServerResponse(response_tuple)
981
if response_tuple[0] == 'ok':
982
coded = bz2.decompress(response_handler.read_body_bytes())
986
lines = coded.split('\n')
989
d = tuple(line.split())
991
revision_graph[d[0]] = d[1:]
993
# No parents - so give the Graph result (NULL_REVISION,).
994
revision_graph[d[0]] = (NULL_REVISION,)
995
return revision_graph
998
def get_signature_text(self, revision_id):
1000
return self._real_repository.get_signature_text(revision_id)
1003
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
1004
def get_revision_graph_with_ghosts(self, revision_ids=None):
1006
return self._real_repository.get_revision_graph_with_ghosts(
1007
revision_ids=revision_ids)
1010
def get_inventory_xml(self, revision_id):
1012
return self._real_repository.get_inventory_xml(revision_id)
1014
def deserialise_inventory(self, revision_id, xml):
1016
return self._real_repository.deserialise_inventory(revision_id, xml)
1018
def reconcile(self, other=None, thorough=False):
1020
return self._real_repository.reconcile(other=other, thorough=thorough)
1022
def all_revision_ids(self):
1024
return self._real_repository.all_revision_ids()
1027
def get_deltas_for_revisions(self, revisions):
1029
return self._real_repository.get_deltas_for_revisions(revisions)
1032
def get_revision_delta(self, revision_id):
1034
return self._real_repository.get_revision_delta(revision_id)
1037
def revision_trees(self, revision_ids):
1039
return self._real_repository.revision_trees(revision_ids)
1042
def get_revision_reconcile(self, revision_id):
1044
return self._real_repository.get_revision_reconcile(revision_id)
1047
def check(self, revision_ids=None):
1049
return self._real_repository.check(revision_ids=revision_ids)
1051
def copy_content_into(self, destination, revision_id=None):
1053
return self._real_repository.copy_content_into(
1054
destination, revision_id=revision_id)
1056
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1057
# get a tarball of the remote repository, and copy from that into the
1059
from bzrlib import osutils
1061
# TODO: Maybe a progress bar while streaming the tarball?
1062
note("Copying repository content as tarball...")
1063
tar_file = self._get_tarball('bz2')
1064
if tar_file is None:
1066
destination = to_bzrdir.create_repository()
1068
tar = tarfile.open('repository', fileobj=tar_file,
1070
tmpdir = osutils.mkdtemp()
1072
_extract_tar(tar, tmpdir)
1073
tmp_bzrdir = BzrDir.open(tmpdir)
1074
tmp_repo = tmp_bzrdir.open_repository()
1075
tmp_repo.copy_content_into(destination, revision_id)
1077
osutils.rmtree(tmpdir)
1081
# TODO: Suggestion from john: using external tar is much faster than
1082
# python's tarfile library, but it may not work on windows.
1085
def inventories(self):
1086
"""Decorate the real repository for now.
1088
In the long term a full blown network facility is needed to
1089
avoid creating a real repository object locally.
1092
return self._real_repository.inventories
1096
"""Compress the data within the repository.
1098
This is not currently implemented within the smart server.
1101
return self._real_repository.pack()
1104
def revisions(self):
1105
"""Decorate the real repository for now.
1107
In the short term this should become a real object to intercept graph
1110
In the long term a full blown network facility is needed.
1113
return self._real_repository.revisions
1115
def set_make_working_trees(self, new_value):
1117
self._real_repository.set_make_working_trees(new_value)
1120
def signatures(self):
1121
"""Decorate the real repository for now.
1123
In the long term a full blown network facility is needed to avoid
1124
creating a real repository object locally.
1127
return self._real_repository.signatures
1130
def sign_revision(self, revision_id, gpg_strategy):
1132
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1136
"""Decorate the real repository for now.
1138
In the long term a full blown network facility is needed to avoid
1139
creating a real repository object locally.
1142
return self._real_repository.texts
1145
def get_revisions(self, revision_ids):
1147
return self._real_repository.get_revisions(revision_ids)
1149
def supports_rich_root(self):
1151
return self._real_repository.supports_rich_root()
1153
def iter_reverse_revision_history(self, revision_id):
1155
return self._real_repository.iter_reverse_revision_history(revision_id)
1158
def _serializer(self):
1160
return self._real_repository._serializer
1162
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1164
return self._real_repository.store_revision_signature(
1165
gpg_strategy, plaintext, revision_id)
1167
def add_signature_text(self, revision_id, signature):
1169
return self._real_repository.add_signature_text(revision_id, signature)
1171
def has_signature_for_revision_id(self, revision_id):
1173
return self._real_repository.has_signature_for_revision_id(revision_id)
1175
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1177
return self._real_repository.item_keys_introduced_by(revision_ids,
1178
_files_pb=_files_pb)
1180
def revision_graph_can_have_wrong_parents(self):
1181
# The answer depends on the remote repo format.
1183
return self._real_repository.revision_graph_can_have_wrong_parents()
1185
def _find_inconsistent_revision_parents(self):
1187
return self._real_repository._find_inconsistent_revision_parents()
1189
def _check_for_inconsistent_revision_parents(self):
1191
return self._real_repository._check_for_inconsistent_revision_parents()
1193
def _make_parents_provider(self):
1196
def _serialise_search_recipe(self, recipe):
1197
"""Serialise a graph search recipe.
1199
:param recipe: A search recipe (start, stop, count).
1200
:return: Serialised bytes.
1202
start_keys = ' '.join(recipe[0])
1203
stop_keys = ' '.join(recipe[1])
1204
count = str(recipe[2])
1205
return '\n'.join((start_keys, stop_keys, count))
1208
class RemoteBranchLockableFiles(LockableFiles):
1209
"""A 'LockableFiles' implementation that talks to a smart server.
1211
This is not a public interface class.
1214
def __init__(self, bzrdir, _client):
1215
self.bzrdir = bzrdir
1216
self._client = _client
1217
self._need_find_modes = True
1218
LockableFiles.__init__(
1219
self, bzrdir.get_branch_transport(None),
1220
'lock', lockdir.LockDir)
1222
def _find_modes(self):
1223
# RemoteBranches don't let the client set the mode of control files.
1224
self._dir_mode = None
1225
self._file_mode = None
1228
class RemoteBranchFormat(branch.BranchFormat):
1230
def __eq__(self, other):
1231
return (isinstance(other, RemoteBranchFormat) and
1232
self.__dict__ == other.__dict__)
1234
def get_format_description(self):
1235
return 'Remote BZR Branch'
1237
def get_format_string(self):
1238
return 'Remote BZR Branch'
1240
def open(self, a_bzrdir):
1241
return a_bzrdir.open_branch()
1243
def initialize(self, a_bzrdir):
1244
return a_bzrdir.create_branch()
1246
def supports_tags(self):
1247
# Remote branches might support tags, but we won't know until we
1248
# access the real remote branch.
1252
class RemoteBranch(branch.Branch):
1253
"""Branch stored on a server accessed by HPSS RPC.
1255
At the moment most operations are mapped down to simple file operations.
1258
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1260
"""Create a RemoteBranch instance.
1262
:param real_branch: An optional local implementation of the branch
1263
format, usually accessing the data via the VFS.
1264
:param _client: Private parameter for testing.
1266
# We intentionally don't call the parent class's __init__, because it
1267
# will try to assign to self.tags, which is a property in this subclass.
1268
# And the parent's __init__ doesn't do much anyway.
1269
self._revision_id_to_revno_cache = None
1270
self._revision_history_cache = None
1271
self._last_revision_info_cache = None
1272
self.bzrdir = remote_bzrdir
1273
if _client is not None:
1274
self._client = _client
1276
self._client = remote_bzrdir._client
1277
self.repository = remote_repository
1278
if real_branch is not None:
1279
self._real_branch = real_branch
1280
# Give the remote repository the matching real repo.
1281
real_repo = self._real_branch.repository
1282
if isinstance(real_repo, RemoteRepository):
1283
real_repo._ensure_real()
1284
real_repo = real_repo._real_repository
1285
self.repository._set_real_repository(real_repo)
1286
# Give the branch the remote repository to let fast-pathing happen.
1287
self._real_branch.repository = self.repository
1289
self._real_branch = None
1290
# Fill out expected attributes of branch for bzrlib api users.
1291
self._format = RemoteBranchFormat()
1292
self.base = self.bzrdir.root_transport.base
1293
self._control_files = None
1294
self._lock_mode = None
1295
self._lock_token = None
1296
self._repo_lock_token = None
1297
self._lock_count = 0
1298
self._leave_lock = False
1299
# The base class init is not called, so we duplicate this:
1300
hooks = branch.Branch.hooks['open']
1303
self._setup_stacking()
1305
def _setup_stacking(self):
1306
# configure stacking into the remote repository, by reading it from
1309
fallback_url = self.get_stacked_on_url()
1310
except (errors.NotStacked, errors.UnstackableBranchFormat,
1311
errors.UnstackableRepositoryFormat), e:
1313
# it's relative to this branch...
1314
fallback_url = urlutils.join(self.base, fallback_url)
1315
transports = [self.bzrdir.root_transport]
1316
if self._real_branch is not None:
1317
transports.append(self._real_branch._transport)
1318
fallback_bzrdir = BzrDir.open(fallback_url, transports)
1319
fallback_repo = fallback_bzrdir.open_repository()
1320
self.repository.add_fallback_repository(fallback_repo)
1322
def _get_real_transport(self):
1323
# if we try vfs access, return the real branch's vfs transport
1325
return self._real_branch._transport
1327
_transport = property(_get_real_transport)
1330
return "%s(%s)" % (self.__class__.__name__, self.base)
1334
def _ensure_real(self):
1335
"""Ensure that there is a _real_branch set.
1337
Used before calls to self._real_branch.
1339
if self._real_branch is None:
1340
if not vfs.vfs_enabled():
1341
raise AssertionError('smart server vfs must be enabled '
1342
'to use vfs implementation')
1343
self.bzrdir._ensure_real()
1344
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1345
if self.repository._real_repository is None:
1346
# Give the remote repository the matching real repo.
1347
real_repo = self._real_branch.repository
1348
if isinstance(real_repo, RemoteRepository):
1349
real_repo._ensure_real()
1350
real_repo = real_repo._real_repository
1351
self.repository._set_real_repository(real_repo)
1352
# Give the real branch the remote repository to let fast-pathing
1354
self._real_branch.repository = self.repository
1355
if self._lock_mode == 'r':
1356
self._real_branch.lock_read()
1357
elif self._lock_mode == 'w':
1358
self._real_branch.lock_write(token=self._lock_token)
1360
def _translate_error(self, err, **context):
1361
self.repository._translate_error(err, branch=self, **context)
1363
def _clear_cached_state(self):
1364
super(RemoteBranch, self)._clear_cached_state()
1365
if self._real_branch is not None:
1366
self._real_branch._clear_cached_state()
1368
def _clear_cached_state_of_remote_branch_only(self):
1369
"""Like _clear_cached_state, but doesn't clear the cache of
1372
This is useful when falling back to calling a method of
1373
self._real_branch that changes state. In that case the underlying
1374
branch changes, so we need to invalidate this RemoteBranch's cache of
1375
it. However, there's no need to invalidate the _real_branch's cache
1376
too, in fact doing so might harm performance.
1378
super(RemoteBranch, self)._clear_cached_state()
1381
def control_files(self):
1382
# Defer actually creating RemoteBranchLockableFiles until its needed,
1383
# because it triggers an _ensure_real that we otherwise might not need.
1384
if self._control_files is None:
1385
self._control_files = RemoteBranchLockableFiles(
1386
self.bzrdir, self._client)
1387
return self._control_files
1389
def _get_checkout_format(self):
1391
return self._real_branch._get_checkout_format()
1393
def get_physical_lock_status(self):
1394
"""See Branch.get_physical_lock_status()."""
1395
# should be an API call to the server, as branches must be lockable.
1397
return self._real_branch.get_physical_lock_status()
1399
def get_stacked_on_url(self):
1400
"""Get the URL this branch is stacked against.
1402
:raises NotStacked: If the branch is not stacked.
1403
:raises UnstackableBranchFormat: If the branch does not support
1405
:raises UnstackableRepositoryFormat: If the repository does not support
1409
response = self._client.call('Branch.get_stacked_on_url',
1410
self._remote_path())
1411
if response[0] != 'ok':
1412
raise errors.UnexpectedSmartServerResponse(response)
1414
except errors.ErrorFromSmartServer, err:
1415
# there may not be a repository yet, so we can't call through
1416
# its _translate_error
1417
_translate_error(err, branch=self)
1418
except errors.UnknownSmartMethod, err:
1420
return self._real_branch.get_stacked_on_url()
1422
def lock_read(self):
1423
self.repository.lock_read()
1424
if not self._lock_mode:
1425
self._lock_mode = 'r'
1426
self._lock_count = 1
1427
if self._real_branch is not None:
1428
self._real_branch.lock_read()
1430
self._lock_count += 1
1432
def _remote_lock_write(self, token):
1434
branch_token = repo_token = ''
1436
branch_token = token
1437
repo_token = self.repository.lock_write()
1438
self.repository.unlock()
1440
response = self._client.call(
1441
'Branch.lock_write', self._remote_path(),
1442
branch_token, repo_token or '')
1443
except errors.ErrorFromSmartServer, err:
1444
self._translate_error(err, token=token)
1445
if response[0] != 'ok':
1446
raise errors.UnexpectedSmartServerResponse(response)
1447
ok, branch_token, repo_token = response
1448
return branch_token, repo_token
1450
def lock_write(self, token=None):
1451
if not self._lock_mode:
1452
# Lock the branch and repo in one remote call.
1453
remote_tokens = self._remote_lock_write(token)
1454
self._lock_token, self._repo_lock_token = remote_tokens
1455
if not self._lock_token:
1456
raise SmartProtocolError('Remote server did not return a token!')
1457
# Tell the self.repository object that it is locked.
1458
self.repository.lock_write(
1459
self._repo_lock_token, _skip_rpc=True)
1461
if self._real_branch is not None:
1462
self._real_branch.lock_write(token=self._lock_token)
1463
if token is not None:
1464
self._leave_lock = True
1466
self._leave_lock = False
1467
self._lock_mode = 'w'
1468
self._lock_count = 1
1469
elif self._lock_mode == 'r':
1470
raise errors.ReadOnlyTransaction
1472
if token is not None:
1473
# A token was given to lock_write, and we're relocking, so
1474
# check that the given token actually matches the one we
1476
if token != self._lock_token:
1477
raise errors.TokenMismatch(token, self._lock_token)
1478
self._lock_count += 1
1479
# Re-lock the repository too.
1480
self.repository.lock_write(self._repo_lock_token)
1481
return self._lock_token or None
1483
def _unlock(self, branch_token, repo_token):
1485
response = self._client.call('Branch.unlock', self._remote_path(), branch_token,
1487
except errors.ErrorFromSmartServer, err:
1488
self._translate_error(err, token=str((branch_token, repo_token)))
1489
if response == ('ok',):
1491
raise errors.UnexpectedSmartServerResponse(response)
1495
self._lock_count -= 1
1496
if not self._lock_count:
1497
self._clear_cached_state()
1498
mode = self._lock_mode
1499
self._lock_mode = None
1500
if self._real_branch is not None:
1501
if (not self._leave_lock and mode == 'w' and
1502
self._repo_lock_token):
1503
# If this RemoteBranch will remove the physical lock
1504
# for the repository, make sure the _real_branch
1505
# doesn't do it first. (Because the _real_branch's
1506
# repository is set to be the RemoteRepository.)
1507
self._real_branch.repository.leave_lock_in_place()
1508
self._real_branch.unlock()
1510
# Only write-locked branched need to make a remote method
1511
# call to perfom the unlock.
1513
if not self._lock_token:
1514
raise AssertionError('Locked, but no token!')
1515
branch_token = self._lock_token
1516
repo_token = self._repo_lock_token
1517
self._lock_token = None
1518
self._repo_lock_token = None
1519
if not self._leave_lock:
1520
self._unlock(branch_token, repo_token)
1522
self.repository.unlock()
1524
def break_lock(self):
1526
return self._real_branch.break_lock()
1528
def leave_lock_in_place(self):
1529
if not self._lock_token:
1530
raise NotImplementedError(self.leave_lock_in_place)
1531
self._leave_lock = True
1533
def dont_leave_lock_in_place(self):
1534
if not self._lock_token:
1535
raise NotImplementedError(self.dont_leave_lock_in_place)
1536
self._leave_lock = False
1538
def _last_revision_info(self):
1539
response = self._client.call('Branch.last_revision_info', self._remote_path())
1540
if response[0] != 'ok':
1541
raise SmartProtocolError('unexpected response code %s' % (response,))
1542
revno = int(response[1])
1543
last_revision = response[2]
1544
return (revno, last_revision)
1546
def _gen_revision_history(self):
1547
"""See Branch._gen_revision_history()."""
1548
response_tuple, response_handler = self._client.call_expecting_body(
1549
'Branch.revision_history', self._remote_path())
1550
if response_tuple[0] != 'ok':
1551
raise errors.UnexpectedSmartServerResponse(response_tuple)
1552
result = response_handler.read_body_bytes().split('\x00')
1557
def _remote_path(self):
1558
return self.bzrdir._path_for_remote_call(self._client)
1560
def _set_last_revision_descendant(self, revision_id, other_branch,
1561
allow_diverged=False, allow_overwrite_descendant=False):
1563
response = self._client.call('Branch.set_last_revision_ex',
1564
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id,
1565
int(allow_diverged), int(allow_overwrite_descendant))
1566
except errors.ErrorFromSmartServer, err:
1567
self._translate_error(err, other_branch=other_branch)
1568
self._clear_cached_state()
1569
if len(response) != 3 and response[0] != 'ok':
1570
raise errors.UnexpectedSmartServerResponse(response)
1571
new_revno, new_revision_id = response[1:]
1572
self._last_revision_info_cache = new_revno, new_revision_id
1573
if self._real_branch is not None:
1574
cache = new_revno, new_revision_id
1575
self._real_branch._last_revision_info_cache = cache
1577
def _set_last_revision(self, revision_id):
1578
self._clear_cached_state()
1580
response = self._client.call('Branch.set_last_revision',
1581
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id)
1582
except errors.ErrorFromSmartServer, err:
1583
self._translate_error(err)
1584
if response != ('ok',):
1585
raise errors.UnexpectedSmartServerResponse(response)
1588
def set_revision_history(self, rev_history):
1589
# Send just the tip revision of the history; the server will generate
1590
# the full history from that. If the revision doesn't exist in this
1591
# branch, NoSuchRevision will be raised.
1592
if rev_history == []:
1595
rev_id = rev_history[-1]
1596
self._set_last_revision(rev_id)
1597
self._cache_revision_history(rev_history)
1599
def get_parent(self):
1601
return self._real_branch.get_parent()
1603
def set_parent(self, url):
1605
return self._real_branch.set_parent(url)
1607
def set_stacked_on_url(self, stacked_location):
1608
"""Set the URL this branch is stacked against.
1610
:raises UnstackableBranchFormat: If the branch does not support
1612
:raises UnstackableRepositoryFormat: If the repository does not support
1616
return self._real_branch.set_stacked_on_url(stacked_location)
1618
def sprout(self, to_bzrdir, revision_id=None):
1619
# Like Branch.sprout, except that it sprouts a branch in the default
1620
# format, because RemoteBranches can't be created at arbitrary URLs.
1621
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1622
# to_bzrdir.create_branch...
1624
result = self._real_branch._format.initialize(to_bzrdir)
1625
self.copy_content_into(result, revision_id=revision_id)
1626
result.set_parent(self.bzrdir.root_transport.base)
1630
def pull(self, source, overwrite=False, stop_revision=None,
1632
self._clear_cached_state_of_remote_branch_only()
1634
return self._real_branch.pull(
1635
source, overwrite=overwrite, stop_revision=stop_revision,
1636
_override_hook_target=self, **kwargs)
1639
def push(self, target, overwrite=False, stop_revision=None):
1641
return self._real_branch.push(
1642
target, overwrite=overwrite, stop_revision=stop_revision,
1643
_override_hook_source_branch=self)
1645
def is_locked(self):
1646
return self._lock_count >= 1
1649
def revision_id_to_revno(self, revision_id):
1651
return self._real_branch.revision_id_to_revno(revision_id)
1654
def set_last_revision_info(self, revno, revision_id):
1655
revision_id = ensure_null(revision_id)
1657
response = self._client.call('Branch.set_last_revision_info',
1658
self._remote_path(), self._lock_token, self._repo_lock_token, str(revno), revision_id)
1659
except errors.UnknownSmartMethod:
1661
self._clear_cached_state_of_remote_branch_only()
1662
self._real_branch.set_last_revision_info(revno, revision_id)
1663
self._last_revision_info_cache = revno, revision_id
1665
except errors.ErrorFromSmartServer, err:
1666
self._translate_error(err)
1667
if response == ('ok',):
1668
self._clear_cached_state()
1669
self._last_revision_info_cache = revno, revision_id
1670
# Update the _real_branch's cache too.
1671
if self._real_branch is not None:
1672
cache = self._last_revision_info_cache
1673
self._real_branch._last_revision_info_cache = cache
1675
raise errors.UnexpectedSmartServerResponse(response)
1678
def generate_revision_history(self, revision_id, last_rev=None,
1680
medium = self._client._medium
1681
if not medium._is_remote_before((1, 6)):
1683
self._set_last_revision_descendant(revision_id, other_branch,
1684
allow_diverged=True, allow_overwrite_descendant=True)
1686
except errors.UnknownSmartMethod:
1687
medium._remember_remote_is_before((1, 6))
1688
self._clear_cached_state_of_remote_branch_only()
1690
self._real_branch.generate_revision_history(
1691
revision_id, last_rev=last_rev, other_branch=other_branch)
1696
return self._real_branch.tags
1698
def set_push_location(self, location):
1700
return self._real_branch.set_push_location(location)
1703
def update_revisions(self, other, stop_revision=None, overwrite=False,
1705
"""See Branch.update_revisions."""
1708
if stop_revision is None:
1709
stop_revision = other.last_revision()
1710
if revision.is_null(stop_revision):
1711
# if there are no commits, we're done.
1713
self.fetch(other, stop_revision)
1716
# Just unconditionally set the new revision. We don't care if
1717
# the branches have diverged.
1718
self._set_last_revision(stop_revision)
1720
medium = self._client._medium
1721
if not medium._is_remote_before((1, 6)):
1723
self._set_last_revision_descendant(stop_revision, other)
1725
except errors.UnknownSmartMethod:
1726
medium._remember_remote_is_before((1, 6))
1727
# Fallback for pre-1.6 servers: check for divergence
1728
# client-side, then do _set_last_revision.
1729
last_rev = revision.ensure_null(self.last_revision())
1731
graph = self.repository.get_graph()
1732
if self._check_if_descendant_or_diverged(
1733
stop_revision, last_rev, graph, other):
1734
# stop_revision is a descendant of last_rev, but we aren't
1735
# overwriting, so we're done.
1737
self._set_last_revision(stop_revision)
1742
def _extract_tar(tar, to_dir):
1743
"""Extract all the contents of a tarfile object.
1745
A replacement for extractall, which is not present in python2.4
1748
tar.extract(tarinfo, to_dir)
1751
def _translate_error(err, **context):
1752
"""Translate an ErrorFromSmartServer into a more useful error.
1754
Possible context keys:
1761
If the error from the server doesn't match a known pattern, then
1762
UnknownErrorFromSmartServer is raised.
1766
return context[name]
1767
except KeyError, keyErr:
1768
mutter('Missing key %r in context %r', keyErr.args[0], context)
1770
if err.error_verb == 'NoSuchRevision':
1771
raise NoSuchRevision(find('branch'), err.error_args[0])
1772
elif err.error_verb == 'nosuchrevision':
1773
raise NoSuchRevision(find('repository'), err.error_args[0])
1774
elif err.error_tuple == ('nobranch',):
1775
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1776
elif err.error_verb == 'norepository':
1777
raise errors.NoRepositoryPresent(find('bzrdir'))
1778
elif err.error_verb == 'LockContention':
1779
raise errors.LockContention('(remote lock)')
1780
elif err.error_verb == 'UnlockableTransport':
1781
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1782
elif err.error_verb == 'LockFailed':
1783
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1784
elif err.error_verb == 'TokenMismatch':
1785
raise errors.TokenMismatch(find('token'), '(remote token)')
1786
elif err.error_verb == 'Diverged':
1787
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1788
elif err.error_verb == 'TipChangeRejected':
1789
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
1790
elif err.error_verb == 'UnstackableBranchFormat':
1791
raise errors.UnstackableBranchFormat(*err.error_args)
1792
elif err.error_verb == 'UnstackableRepositoryFormat':
1793
raise errors.UnstackableRepositoryFormat(*err.error_args)
1794
elif err.error_verb == 'NotStacked':
1795
raise errors.NotStacked(branch=find('branch'))
1796
raise errors.UnknownErrorFromSmartServer(err)