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
# Not delegated to _real_repository so that InterRepository.get has a
804
# chance to find an InterRepository specialised for RemoteRepository.
805
if self.has_same_location(source):
806
# check that last_revision is in 'from' and then return a
808
if (revision_id is not None and
809
not revision.is_null(revision_id)):
810
self.get_revision(revision_id)
812
inter = repository.InterRepository.get(source, self)
814
return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
815
except NotImplementedError:
816
raise errors.IncompatibleRepositories(source, self)
818
def create_bundle(self, target, base, fileobj, format=None):
820
self._real_repository.create_bundle(target, base, fileobj, format)
823
def get_ancestry(self, revision_id, topo_sorted=True):
825
return self._real_repository.get_ancestry(revision_id, topo_sorted)
827
def fileids_altered_by_revision_ids(self, revision_ids):
829
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
831
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
833
return self._real_repository._get_versioned_file_checker(
834
revisions, revision_versions_cache)
836
def iter_files_bytes(self, desired_files):
837
"""See Repository.iter_file_bytes.
840
return self._real_repository.iter_files_bytes(desired_files)
843
def _fetch_order(self):
844
"""Decorate the real repository for now.
846
In the long term getting this back from the remote repository as part
847
of open would be more efficient.
850
return self._real_repository._fetch_order
853
def _fetch_uses_deltas(self):
854
"""Decorate the real repository for now.
856
In the long term getting this back from the remote repository as part
857
of open would be more efficient.
860
return self._real_repository._fetch_uses_deltas
863
def _fetch_reconcile(self):
864
"""Decorate the real repository for now.
866
In the long term getting this back from the remote repository as part
867
of open would be more efficient.
870
return self._real_repository._fetch_reconcile
872
def get_parent_map(self, keys):
873
"""See bzrlib.Graph.get_parent_map()."""
874
# Hack to build up the caching logic.
875
ancestry = self._parents_map
877
# Repository is not locked, so there's no cache.
878
missing_revisions = set(keys)
881
missing_revisions = set(key for key in keys if key not in ancestry)
882
if missing_revisions:
883
parent_map = self._get_parent_map(missing_revisions)
884
if 'hpss' in debug.debug_flags:
885
mutter('retransmitted revisions: %d of %d',
886
len(set(ancestry).intersection(parent_map)),
888
ancestry.update(parent_map)
889
present_keys = [k for k in keys if k in ancestry]
890
if 'hpss' in debug.debug_flags:
891
if self._requested_parents is not None and len(ancestry) != 0:
892
self._requested_parents.update(present_keys)
893
mutter('Current RemoteRepository graph hit rate: %d%%',
894
100.0 * len(self._requested_parents) / len(ancestry))
895
return dict((k, ancestry[k]) for k in present_keys)
897
def _get_parent_map(self, keys):
898
"""Helper for get_parent_map that performs the RPC."""
899
medium = self._client._medium
900
if medium._is_remote_before((1, 2)):
901
# We already found out that the server can't understand
902
# Repository.get_parent_map requests, so just fetch the whole
904
# XXX: Note that this will issue a deprecation warning. This is ok
905
# :- its because we're working with a deprecated server anyway, and
906
# the user will almost certainly have seen a warning about the
907
# server version already.
908
rg = self.get_revision_graph()
909
# There is an api discrepency between get_parent_map and
910
# get_revision_graph. Specifically, a "key:()" pair in
911
# get_revision_graph just means a node has no parents. For
912
# "get_parent_map" it means the node is a ghost. So fix up the
913
# graph to correct this.
914
# https://bugs.launchpad.net/bzr/+bug/214894
915
# There is one other "bug" which is that ghosts in
916
# get_revision_graph() are not returned at all. But we won't worry
917
# about that for now.
918
for node_id, parent_ids in rg.iteritems():
920
rg[node_id] = (NULL_REVISION,)
921
rg[NULL_REVISION] = ()
926
raise ValueError('get_parent_map(None) is not valid')
927
if NULL_REVISION in keys:
928
keys.discard(NULL_REVISION)
929
found_parents = {NULL_REVISION:()}
934
# TODO(Needs analysis): We could assume that the keys being requested
935
# from get_parent_map are in a breadth first search, so typically they
936
# will all be depth N from some common parent, and we don't have to
937
# have the server iterate from the root parent, but rather from the
938
# keys we're searching; and just tell the server the keyspace we
939
# already have; but this may be more traffic again.
941
# Transform self._parents_map into a search request recipe.
942
# TODO: Manage this incrementally to avoid covering the same path
943
# repeatedly. (The server will have to on each request, but the less
944
# work done the better).
945
parents_map = self._parents_map
946
if parents_map is None:
947
# Repository is not locked, so there's no cache.
949
start_set = set(parents_map)
950
result_parents = set()
951
for parents in parents_map.itervalues():
952
result_parents.update(parents)
953
stop_keys = result_parents.difference(start_set)
954
included_keys = start_set.intersection(result_parents)
955
start_set.difference_update(included_keys)
956
recipe = (start_set, stop_keys, len(parents_map))
957
body = self._serialise_search_recipe(recipe)
958
path = self.bzrdir._path_for_remote_call(self._client)
960
if type(key) is not str:
962
"key %r not a plain string" % (key,))
963
verb = 'Repository.get_parent_map'
964
args = (path,) + tuple(keys)
966
response = self._client.call_with_body_bytes_expecting_body(
967
verb, args, self._serialise_search_recipe(recipe))
968
except errors.UnknownSmartMethod:
969
# Server does not support this method, so get the whole graph.
970
# Worse, we have to force a disconnection, because the server now
971
# doesn't realise it has a body on the wire to consume, so the
972
# only way to recover is to abandon the connection.
974
'Server is too old for fast get_parent_map, reconnecting. '
975
'(Upgrade the server to Bazaar 1.2 to avoid this)')
977
# To avoid having to disconnect repeatedly, we keep track of the
978
# fact the server doesn't understand remote methods added in 1.2.
979
medium._remember_remote_is_before((1, 2))
980
return self.get_revision_graph(None)
981
response_tuple, response_handler = response
982
if response_tuple[0] not in ['ok']:
983
response_handler.cancel_read_body()
984
raise errors.UnexpectedSmartServerResponse(response_tuple)
985
if response_tuple[0] == 'ok':
986
coded = bz2.decompress(response_handler.read_body_bytes())
990
lines = coded.split('\n')
993
d = tuple(line.split())
995
revision_graph[d[0]] = d[1:]
997
# No parents - so give the Graph result (NULL_REVISION,).
998
revision_graph[d[0]] = (NULL_REVISION,)
999
return revision_graph
1002
def get_signature_text(self, revision_id):
1004
return self._real_repository.get_signature_text(revision_id)
1007
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
1008
def get_revision_graph_with_ghosts(self, revision_ids=None):
1010
return self._real_repository.get_revision_graph_with_ghosts(
1011
revision_ids=revision_ids)
1014
def get_inventory_xml(self, revision_id):
1016
return self._real_repository.get_inventory_xml(revision_id)
1018
def deserialise_inventory(self, revision_id, xml):
1020
return self._real_repository.deserialise_inventory(revision_id, xml)
1022
def reconcile(self, other=None, thorough=False):
1024
return self._real_repository.reconcile(other=other, thorough=thorough)
1026
def all_revision_ids(self):
1028
return self._real_repository.all_revision_ids()
1031
def get_deltas_for_revisions(self, revisions):
1033
return self._real_repository.get_deltas_for_revisions(revisions)
1036
def get_revision_delta(self, revision_id):
1038
return self._real_repository.get_revision_delta(revision_id)
1041
def revision_trees(self, revision_ids):
1043
return self._real_repository.revision_trees(revision_ids)
1046
def get_revision_reconcile(self, revision_id):
1048
return self._real_repository.get_revision_reconcile(revision_id)
1051
def check(self, revision_ids=None):
1053
return self._real_repository.check(revision_ids=revision_ids)
1055
def copy_content_into(self, destination, revision_id=None):
1057
return self._real_repository.copy_content_into(
1058
destination, revision_id=revision_id)
1060
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1061
# get a tarball of the remote repository, and copy from that into the
1063
from bzrlib import osutils
1065
# TODO: Maybe a progress bar while streaming the tarball?
1066
note("Copying repository content as tarball...")
1067
tar_file = self._get_tarball('bz2')
1068
if tar_file is None:
1070
destination = to_bzrdir.create_repository()
1072
tar = tarfile.open('repository', fileobj=tar_file,
1074
tmpdir = osutils.mkdtemp()
1076
_extract_tar(tar, tmpdir)
1077
tmp_bzrdir = BzrDir.open(tmpdir)
1078
tmp_repo = tmp_bzrdir.open_repository()
1079
tmp_repo.copy_content_into(destination, revision_id)
1081
osutils.rmtree(tmpdir)
1085
# TODO: Suggestion from john: using external tar is much faster than
1086
# python's tarfile library, but it may not work on windows.
1089
def inventories(self):
1090
"""Decorate the real repository for now.
1092
In the long term a full blown network facility is needed to
1093
avoid creating a real repository object locally.
1096
return self._real_repository.inventories
1100
"""Compress the data within the repository.
1102
This is not currently implemented within the smart server.
1105
return self._real_repository.pack()
1108
def revisions(self):
1109
"""Decorate the real repository for now.
1111
In the short term this should become a real object to intercept graph
1114
In the long term a full blown network facility is needed.
1117
return self._real_repository.revisions
1119
def set_make_working_trees(self, new_value):
1121
self._real_repository.set_make_working_trees(new_value)
1124
def signatures(self):
1125
"""Decorate the real repository for now.
1127
In the long term a full blown network facility is needed to avoid
1128
creating a real repository object locally.
1131
return self._real_repository.signatures
1134
def sign_revision(self, revision_id, gpg_strategy):
1136
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1140
"""Decorate the real repository for now.
1142
In the long term a full blown network facility is needed to avoid
1143
creating a real repository object locally.
1146
return self._real_repository.texts
1149
def get_revisions(self, revision_ids):
1151
return self._real_repository.get_revisions(revision_ids)
1153
def supports_rich_root(self):
1155
return self._real_repository.supports_rich_root()
1157
def iter_reverse_revision_history(self, revision_id):
1159
return self._real_repository.iter_reverse_revision_history(revision_id)
1162
def _serializer(self):
1164
return self._real_repository._serializer
1166
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1168
return self._real_repository.store_revision_signature(
1169
gpg_strategy, plaintext, revision_id)
1171
def add_signature_text(self, revision_id, signature):
1173
return self._real_repository.add_signature_text(revision_id, signature)
1175
def has_signature_for_revision_id(self, revision_id):
1177
return self._real_repository.has_signature_for_revision_id(revision_id)
1179
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1181
return self._real_repository.item_keys_introduced_by(revision_ids,
1182
_files_pb=_files_pb)
1184
def revision_graph_can_have_wrong_parents(self):
1185
# The answer depends on the remote repo format.
1187
return self._real_repository.revision_graph_can_have_wrong_parents()
1189
def _find_inconsistent_revision_parents(self):
1191
return self._real_repository._find_inconsistent_revision_parents()
1193
def _check_for_inconsistent_revision_parents(self):
1195
return self._real_repository._check_for_inconsistent_revision_parents()
1197
def _make_parents_provider(self):
1200
def _serialise_search_recipe(self, recipe):
1201
"""Serialise a graph search recipe.
1203
:param recipe: A search recipe (start, stop, count).
1204
:return: Serialised bytes.
1206
start_keys = ' '.join(recipe[0])
1207
stop_keys = ' '.join(recipe[1])
1208
count = str(recipe[2])
1209
return '\n'.join((start_keys, stop_keys, count))
1212
path = self.bzrdir._path_for_remote_call(self._client)
1214
response = self._client.call('PackRepository.autopack', path)
1215
except errors.ErrorFromSmartServer, err:
1216
self._translate_error(err)
1217
except errors.UnknownSmartMethod:
1219
self._real_repository._pack_collection.autopack()
1221
if self._real_repository is not None:
1222
# Reset the real repository's cache of pack names.
1223
self._real_repository._pack_collection.reload_pack_names()
1224
if response != ('ok',):
1225
raise errors.UnexpectedSmartServerResponse(response)
1228
class RemoteBranchLockableFiles(LockableFiles):
1229
"""A 'LockableFiles' implementation that talks to a smart server.
1231
This is not a public interface class.
1234
def __init__(self, bzrdir, _client):
1235
self.bzrdir = bzrdir
1236
self._client = _client
1237
self._need_find_modes = True
1238
LockableFiles.__init__(
1239
self, bzrdir.get_branch_transport(None),
1240
'lock', lockdir.LockDir)
1242
def _find_modes(self):
1243
# RemoteBranches don't let the client set the mode of control files.
1244
self._dir_mode = None
1245
self._file_mode = None
1248
class RemoteBranchFormat(branch.BranchFormat):
1250
def __eq__(self, other):
1251
return (isinstance(other, RemoteBranchFormat) and
1252
self.__dict__ == other.__dict__)
1254
def get_format_description(self):
1255
return 'Remote BZR Branch'
1257
def get_format_string(self):
1258
return 'Remote BZR Branch'
1260
def open(self, a_bzrdir):
1261
return a_bzrdir.open_branch()
1263
def initialize(self, a_bzrdir):
1264
return a_bzrdir.create_branch()
1266
def supports_tags(self):
1267
# Remote branches might support tags, but we won't know until we
1268
# access the real remote branch.
1272
class RemoteBranch(branch.Branch):
1273
"""Branch stored on a server accessed by HPSS RPC.
1275
At the moment most operations are mapped down to simple file operations.
1278
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1280
"""Create a RemoteBranch instance.
1282
:param real_branch: An optional local implementation of the branch
1283
format, usually accessing the data via the VFS.
1284
:param _client: Private parameter for testing.
1286
# We intentionally don't call the parent class's __init__, because it
1287
# will try to assign to self.tags, which is a property in this subclass.
1288
# And the parent's __init__ doesn't do much anyway.
1289
self._revision_id_to_revno_cache = None
1290
self._revision_history_cache = None
1291
self._last_revision_info_cache = None
1292
self.bzrdir = remote_bzrdir
1293
if _client is not None:
1294
self._client = _client
1296
self._client = remote_bzrdir._client
1297
self.repository = remote_repository
1298
if real_branch is not None:
1299
self._real_branch = real_branch
1300
# Give the remote repository the matching real repo.
1301
real_repo = self._real_branch.repository
1302
if isinstance(real_repo, RemoteRepository):
1303
real_repo._ensure_real()
1304
real_repo = real_repo._real_repository
1305
self.repository._set_real_repository(real_repo)
1306
# Give the branch the remote repository to let fast-pathing happen.
1307
self._real_branch.repository = self.repository
1309
self._real_branch = None
1310
# Fill out expected attributes of branch for bzrlib api users.
1311
self._format = RemoteBranchFormat()
1312
self.base = self.bzrdir.root_transport.base
1313
self._control_files = None
1314
self._lock_mode = None
1315
self._lock_token = None
1316
self._repo_lock_token = None
1317
self._lock_count = 0
1318
self._leave_lock = False
1319
# The base class init is not called, so we duplicate this:
1320
hooks = branch.Branch.hooks['open']
1323
self._setup_stacking()
1325
def _setup_stacking(self):
1326
# configure stacking into the remote repository, by reading it from
1329
fallback_url = self.get_stacked_on_url()
1330
except (errors.NotStacked, errors.UnstackableBranchFormat,
1331
errors.UnstackableRepositoryFormat), e:
1333
# it's relative to this branch...
1334
fallback_url = urlutils.join(self.base, fallback_url)
1335
transports = [self.bzrdir.root_transport]
1336
if self._real_branch is not None:
1337
transports.append(self._real_branch._transport)
1338
fallback_bzrdir = BzrDir.open(fallback_url, transports)
1339
fallback_repo = fallback_bzrdir.open_repository()
1340
self.repository.add_fallback_repository(fallback_repo)
1342
def _get_real_transport(self):
1343
# if we try vfs access, return the real branch's vfs transport
1345
return self._real_branch._transport
1347
_transport = property(_get_real_transport)
1350
return "%s(%s)" % (self.__class__.__name__, self.base)
1354
def _ensure_real(self):
1355
"""Ensure that there is a _real_branch set.
1357
Used before calls to self._real_branch.
1359
if self._real_branch is None:
1360
if not vfs.vfs_enabled():
1361
raise AssertionError('smart server vfs must be enabled '
1362
'to use vfs implementation')
1363
self.bzrdir._ensure_real()
1364
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1365
if self.repository._real_repository is None:
1366
# Give the remote repository the matching real repo.
1367
real_repo = self._real_branch.repository
1368
if isinstance(real_repo, RemoteRepository):
1369
real_repo._ensure_real()
1370
real_repo = real_repo._real_repository
1371
self.repository._set_real_repository(real_repo)
1372
# Give the real branch the remote repository to let fast-pathing
1374
self._real_branch.repository = self.repository
1375
if self._lock_mode == 'r':
1376
self._real_branch.lock_read()
1377
elif self._lock_mode == 'w':
1378
self._real_branch.lock_write(token=self._lock_token)
1380
def _translate_error(self, err, **context):
1381
self.repository._translate_error(err, branch=self, **context)
1383
def _clear_cached_state(self):
1384
super(RemoteBranch, self)._clear_cached_state()
1385
if self._real_branch is not None:
1386
self._real_branch._clear_cached_state()
1388
def _clear_cached_state_of_remote_branch_only(self):
1389
"""Like _clear_cached_state, but doesn't clear the cache of
1392
This is useful when falling back to calling a method of
1393
self._real_branch that changes state. In that case the underlying
1394
branch changes, so we need to invalidate this RemoteBranch's cache of
1395
it. However, there's no need to invalidate the _real_branch's cache
1396
too, in fact doing so might harm performance.
1398
super(RemoteBranch, self)._clear_cached_state()
1401
def control_files(self):
1402
# Defer actually creating RemoteBranchLockableFiles until its needed,
1403
# because it triggers an _ensure_real that we otherwise might not need.
1404
if self._control_files is None:
1405
self._control_files = RemoteBranchLockableFiles(
1406
self.bzrdir, self._client)
1407
return self._control_files
1409
def _get_checkout_format(self):
1411
return self._real_branch._get_checkout_format()
1413
def get_physical_lock_status(self):
1414
"""See Branch.get_physical_lock_status()."""
1415
# should be an API call to the server, as branches must be lockable.
1417
return self._real_branch.get_physical_lock_status()
1419
def get_stacked_on_url(self):
1420
"""Get the URL this branch is stacked against.
1422
:raises NotStacked: If the branch is not stacked.
1423
:raises UnstackableBranchFormat: If the branch does not support
1425
:raises UnstackableRepositoryFormat: If the repository does not support
1429
response = self._client.call('Branch.get_stacked_on_url',
1430
self._remote_path())
1431
if response[0] != 'ok':
1432
raise errors.UnexpectedSmartServerResponse(response)
1434
except errors.ErrorFromSmartServer, err:
1435
# there may not be a repository yet, so we can't call through
1436
# its _translate_error
1437
_translate_error(err, branch=self)
1438
except errors.UnknownSmartMethod, err:
1440
return self._real_branch.get_stacked_on_url()
1442
def lock_read(self):
1443
self.repository.lock_read()
1444
if not self._lock_mode:
1445
self._lock_mode = 'r'
1446
self._lock_count = 1
1447
if self._real_branch is not None:
1448
self._real_branch.lock_read()
1450
self._lock_count += 1
1452
def _remote_lock_write(self, token):
1454
branch_token = repo_token = ''
1456
branch_token = token
1457
repo_token = self.repository.lock_write()
1458
self.repository.unlock()
1460
response = self._client.call(
1461
'Branch.lock_write', self._remote_path(),
1462
branch_token, repo_token or '')
1463
except errors.ErrorFromSmartServer, err:
1464
self._translate_error(err, token=token)
1465
if response[0] != 'ok':
1466
raise errors.UnexpectedSmartServerResponse(response)
1467
ok, branch_token, repo_token = response
1468
return branch_token, repo_token
1470
def lock_write(self, token=None):
1471
if not self._lock_mode:
1472
# Lock the branch and repo in one remote call.
1473
remote_tokens = self._remote_lock_write(token)
1474
self._lock_token, self._repo_lock_token = remote_tokens
1475
if not self._lock_token:
1476
raise SmartProtocolError('Remote server did not return a token!')
1477
# Tell the self.repository object that it is locked.
1478
self.repository.lock_write(
1479
self._repo_lock_token, _skip_rpc=True)
1481
if self._real_branch is not None:
1482
self._real_branch.lock_write(token=self._lock_token)
1483
if token is not None:
1484
self._leave_lock = True
1486
self._leave_lock = False
1487
self._lock_mode = 'w'
1488
self._lock_count = 1
1489
elif self._lock_mode == 'r':
1490
raise errors.ReadOnlyTransaction
1492
if token is not None:
1493
# A token was given to lock_write, and we're relocking, so
1494
# check that the given token actually matches the one we
1496
if token != self._lock_token:
1497
raise errors.TokenMismatch(token, self._lock_token)
1498
self._lock_count += 1
1499
# Re-lock the repository too.
1500
self.repository.lock_write(self._repo_lock_token)
1501
return self._lock_token or None
1503
def _unlock(self, branch_token, repo_token):
1505
response = self._client.call('Branch.unlock', self._remote_path(), branch_token,
1507
except errors.ErrorFromSmartServer, err:
1508
self._translate_error(err, token=str((branch_token, repo_token)))
1509
if response == ('ok',):
1511
raise errors.UnexpectedSmartServerResponse(response)
1515
self._lock_count -= 1
1516
if not self._lock_count:
1517
self._clear_cached_state()
1518
mode = self._lock_mode
1519
self._lock_mode = None
1520
if self._real_branch is not None:
1521
if (not self._leave_lock and mode == 'w' and
1522
self._repo_lock_token):
1523
# If this RemoteBranch will remove the physical lock
1524
# for the repository, make sure the _real_branch
1525
# doesn't do it first. (Because the _real_branch's
1526
# repository is set to be the RemoteRepository.)
1527
self._real_branch.repository.leave_lock_in_place()
1528
self._real_branch.unlock()
1530
# Only write-locked branched need to make a remote method
1531
# call to perfom the unlock.
1533
if not self._lock_token:
1534
raise AssertionError('Locked, but no token!')
1535
branch_token = self._lock_token
1536
repo_token = self._repo_lock_token
1537
self._lock_token = None
1538
self._repo_lock_token = None
1539
if not self._leave_lock:
1540
self._unlock(branch_token, repo_token)
1542
self.repository.unlock()
1544
def break_lock(self):
1546
return self._real_branch.break_lock()
1548
def leave_lock_in_place(self):
1549
if not self._lock_token:
1550
raise NotImplementedError(self.leave_lock_in_place)
1551
self._leave_lock = True
1553
def dont_leave_lock_in_place(self):
1554
if not self._lock_token:
1555
raise NotImplementedError(self.dont_leave_lock_in_place)
1556
self._leave_lock = False
1558
def _last_revision_info(self):
1559
response = self._client.call('Branch.last_revision_info', self._remote_path())
1560
if response[0] != 'ok':
1561
raise SmartProtocolError('unexpected response code %s' % (response,))
1562
revno = int(response[1])
1563
last_revision = response[2]
1564
return (revno, last_revision)
1566
def _gen_revision_history(self):
1567
"""See Branch._gen_revision_history()."""
1568
response_tuple, response_handler = self._client.call_expecting_body(
1569
'Branch.revision_history', self._remote_path())
1570
if response_tuple[0] != 'ok':
1571
raise errors.UnexpectedSmartServerResponse(response_tuple)
1572
result = response_handler.read_body_bytes().split('\x00')
1577
def _remote_path(self):
1578
return self.bzrdir._path_for_remote_call(self._client)
1580
def _set_last_revision_descendant(self, revision_id, other_branch,
1581
allow_diverged=False, allow_overwrite_descendant=False):
1583
response = self._client.call('Branch.set_last_revision_ex',
1584
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id,
1585
int(allow_diverged), int(allow_overwrite_descendant))
1586
except errors.ErrorFromSmartServer, err:
1587
self._translate_error(err, other_branch=other_branch)
1588
self._clear_cached_state()
1589
if len(response) != 3 and response[0] != 'ok':
1590
raise errors.UnexpectedSmartServerResponse(response)
1591
new_revno, new_revision_id = response[1:]
1592
self._last_revision_info_cache = new_revno, new_revision_id
1593
if self._real_branch is not None:
1594
cache = new_revno, new_revision_id
1595
self._real_branch._last_revision_info_cache = cache
1597
def _set_last_revision(self, revision_id):
1598
self._clear_cached_state()
1600
response = self._client.call('Branch.set_last_revision',
1601
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id)
1602
except errors.ErrorFromSmartServer, err:
1603
self._translate_error(err)
1604
if response != ('ok',):
1605
raise errors.UnexpectedSmartServerResponse(response)
1608
def set_revision_history(self, rev_history):
1609
# Send just the tip revision of the history; the server will generate
1610
# the full history from that. If the revision doesn't exist in this
1611
# branch, NoSuchRevision will be raised.
1612
if rev_history == []:
1615
rev_id = rev_history[-1]
1616
self._set_last_revision(rev_id)
1617
self._cache_revision_history(rev_history)
1619
def get_parent(self):
1621
return self._real_branch.get_parent()
1623
def set_parent(self, url):
1625
return self._real_branch.set_parent(url)
1627
def set_stacked_on_url(self, stacked_location):
1628
"""Set the URL this branch is stacked against.
1630
:raises UnstackableBranchFormat: If the branch does not support
1632
:raises UnstackableRepositoryFormat: If the repository does not support
1636
return self._real_branch.set_stacked_on_url(stacked_location)
1638
def sprout(self, to_bzrdir, revision_id=None):
1639
# Like Branch.sprout, except that it sprouts a branch in the default
1640
# format, because RemoteBranches can't be created at arbitrary URLs.
1641
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1642
# to_bzrdir.create_branch...
1644
result = self._real_branch._format.initialize(to_bzrdir)
1645
self.copy_content_into(result, revision_id=revision_id)
1646
result.set_parent(self.bzrdir.root_transport.base)
1650
def pull(self, source, overwrite=False, stop_revision=None,
1652
self._clear_cached_state_of_remote_branch_only()
1654
return self._real_branch.pull(
1655
source, overwrite=overwrite, stop_revision=stop_revision,
1656
_override_hook_target=self, **kwargs)
1659
def push(self, target, overwrite=False, stop_revision=None):
1661
return self._real_branch.push(
1662
target, overwrite=overwrite, stop_revision=stop_revision,
1663
_override_hook_source_branch=self)
1665
def is_locked(self):
1666
return self._lock_count >= 1
1669
def revision_id_to_revno(self, revision_id):
1671
return self._real_branch.revision_id_to_revno(revision_id)
1674
def set_last_revision_info(self, revno, revision_id):
1675
revision_id = ensure_null(revision_id)
1677
response = self._client.call('Branch.set_last_revision_info',
1678
self._remote_path(), self._lock_token, self._repo_lock_token, str(revno), revision_id)
1679
except errors.UnknownSmartMethod:
1681
self._clear_cached_state_of_remote_branch_only()
1682
self._real_branch.set_last_revision_info(revno, revision_id)
1683
self._last_revision_info_cache = revno, revision_id
1685
except errors.ErrorFromSmartServer, err:
1686
self._translate_error(err)
1687
if response == ('ok',):
1688
self._clear_cached_state()
1689
self._last_revision_info_cache = revno, revision_id
1690
# Update the _real_branch's cache too.
1691
if self._real_branch is not None:
1692
cache = self._last_revision_info_cache
1693
self._real_branch._last_revision_info_cache = cache
1695
raise errors.UnexpectedSmartServerResponse(response)
1698
def generate_revision_history(self, revision_id, last_rev=None,
1700
medium = self._client._medium
1701
if not medium._is_remote_before((1, 6)):
1703
self._set_last_revision_descendant(revision_id, other_branch,
1704
allow_diverged=True, allow_overwrite_descendant=True)
1706
except errors.UnknownSmartMethod:
1707
medium._remember_remote_is_before((1, 6))
1708
self._clear_cached_state_of_remote_branch_only()
1710
self._real_branch.generate_revision_history(
1711
revision_id, last_rev=last_rev, other_branch=other_branch)
1716
return self._real_branch.tags
1718
def set_push_location(self, location):
1720
return self._real_branch.set_push_location(location)
1723
def update_revisions(self, other, stop_revision=None, overwrite=False,
1725
"""See Branch.update_revisions."""
1728
if stop_revision is None:
1729
stop_revision = other.last_revision()
1730
if revision.is_null(stop_revision):
1731
# if there are no commits, we're done.
1733
self.fetch(other, stop_revision)
1736
# Just unconditionally set the new revision. We don't care if
1737
# the branches have diverged.
1738
self._set_last_revision(stop_revision)
1740
medium = self._client._medium
1741
if not medium._is_remote_before((1, 6)):
1743
self._set_last_revision_descendant(stop_revision, other)
1745
except errors.UnknownSmartMethod:
1746
medium._remember_remote_is_before((1, 6))
1747
# Fallback for pre-1.6 servers: check for divergence
1748
# client-side, then do _set_last_revision.
1749
last_rev = revision.ensure_null(self.last_revision())
1751
graph = self.repository.get_graph()
1752
if self._check_if_descendant_or_diverged(
1753
stop_revision, last_rev, graph, other):
1754
# stop_revision is a descendant of last_rev, but we aren't
1755
# overwriting, so we're done.
1757
self._set_last_revision(stop_revision)
1762
def _extract_tar(tar, to_dir):
1763
"""Extract all the contents of a tarfile object.
1765
A replacement for extractall, which is not present in python2.4
1768
tar.extract(tarinfo, to_dir)
1771
def _translate_error(err, **context):
1772
"""Translate an ErrorFromSmartServer into a more useful error.
1774
Possible context keys:
1781
If the error from the server doesn't match a known pattern, then
1782
UnknownErrorFromSmartServer is raised.
1786
return context[name]
1787
except KeyError, keyErr:
1788
mutter('Missing key %r in context %r', keyErr.args[0], context)
1790
if err.error_verb == 'NoSuchRevision':
1791
raise NoSuchRevision(find('branch'), err.error_args[0])
1792
elif err.error_verb == 'nosuchrevision':
1793
raise NoSuchRevision(find('repository'), err.error_args[0])
1794
elif err.error_tuple == ('nobranch',):
1795
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1796
elif err.error_verb == 'norepository':
1797
raise errors.NoRepositoryPresent(find('bzrdir'))
1798
elif err.error_verb == 'LockContention':
1799
raise errors.LockContention('(remote lock)')
1800
elif err.error_verb == 'UnlockableTransport':
1801
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1802
elif err.error_verb == 'LockFailed':
1803
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1804
elif err.error_verb == 'TokenMismatch':
1805
raise errors.TokenMismatch(find('token'), '(remote token)')
1806
elif err.error_verb == 'Diverged':
1807
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1808
elif err.error_verb == 'TipChangeRejected':
1809
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
1810
elif err.error_verb == 'UnstackableBranchFormat':
1811
raise errors.UnstackableBranchFormat(*err.error_args)
1812
elif err.error_verb == 'UnstackableRepositoryFormat':
1813
raise errors.UnstackableRepositoryFormat(*err.error_args)
1814
elif err.error_verb == 'NotStacked':
1815
raise errors.NotStacked(branch=find('branch'))
1816
elif err.error_verb == 'NotPackRepository':
1817
# There's no specific exception to raise for this, because it shouldn't
1818
# happen unless something has changed the remote repo's format between
1820
raise errors.InternalBzrError(
1821
'Tried to use PackRepository verb, but remote side says '
1822
'%s is not a pack repository.' % (find('repository')))
1823
raise errors.UnknownErrorFromSmartServer(err)