1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# TODO: At some point, handle upgrades by just passing the whole request
18
# across to run on the server.
21
from cStringIO import StringIO
34
from bzrlib.branch import BranchReferenceFormat
35
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
36
from bzrlib.config import BranchConfig, TreeConfig
37
from bzrlib.decorators import needs_read_lock, needs_write_lock
38
from bzrlib.errors import (
42
from bzrlib.lockable_files import LockableFiles
43
from bzrlib.pack import ContainerPushParser
44
from bzrlib.smart import client, vfs
45
from bzrlib.symbol_versioning import (
49
from bzrlib.revision import ensure_null, NULL_REVISION
50
from bzrlib.trace import mutter, note, warning
53
# Note: RemoteBzrDirFormat is in bzrdir.py
55
class RemoteBzrDir(BzrDir):
56
"""Control directory on a remote server, accessed via bzr:// or similar."""
58
def __init__(self, transport, _client=None):
59
"""Construct a RemoteBzrDir.
61
:param _client: Private parameter for testing. Disables probing and the
64
BzrDir.__init__(self, transport, RemoteBzrDirFormat())
65
# this object holds a delegated bzrdir that uses file-level operations
66
# to talk to the other side
67
self._real_bzrdir = None
70
medium = transport.get_smart_medium()
71
self._client = client._SmartClient(medium)
73
self._client = _client
76
path = self._path_for_remote_call(self._client)
77
response = self._client.call('BzrDir.open', path)
78
if response not in [('yes',), ('no',)]:
79
raise errors.UnexpectedSmartServerResponse(response)
80
if response == ('no',):
81
raise errors.NotBranchError(path=transport.base)
83
def _ensure_real(self):
84
"""Ensure that there is a _real_bzrdir set.
86
Used before calls to self._real_bzrdir.
88
if not self._real_bzrdir:
89
self._real_bzrdir = BzrDir.open_from_transport(
90
self.root_transport, _server_formats=False)
92
def cloning_metadir(self, stacked=False):
94
return self._real_bzrdir.cloning_metadir(stacked)
96
def _translate_error(self, err, **context):
97
_translate_error(err, bzrdir=self, **context)
99
def create_repository(self, shared=False):
101
self._real_bzrdir.create_repository(shared=shared)
102
return self.open_repository()
104
def destroy_repository(self):
105
"""See BzrDir.destroy_repository"""
107
self._real_bzrdir.destroy_repository()
109
def create_branch(self):
111
real_branch = self._real_bzrdir.create_branch()
112
return RemoteBranch(self, self.find_repository(), real_branch)
114
def destroy_branch(self):
115
"""See BzrDir.destroy_branch"""
117
self._real_bzrdir.destroy_branch()
119
def create_workingtree(self, revision_id=None, from_branch=None):
120
raise errors.NotLocalUrl(self.transport.base)
122
def find_branch_format(self):
123
"""Find the branch 'format' for this bzrdir.
125
This might be a synthetic object for e.g. RemoteBranch and SVN.
127
b = self.open_branch()
130
def get_branch_reference(self):
131
"""See BzrDir.get_branch_reference()."""
132
path = self._path_for_remote_call(self._client)
134
response = self._client.call('BzrDir.open_branch', path)
135
except errors.ErrorFromSmartServer, err:
136
self._translate_error(err)
137
if response[0] == 'ok':
138
if response[1] == '':
139
# branch at this location.
142
# a branch reference, use the existing BranchReference logic.
145
raise errors.UnexpectedSmartServerResponse(response)
147
def _get_tree_branch(self):
148
"""See BzrDir._get_tree_branch()."""
149
return None, self.open_branch()
151
def open_branch(self, _unsupported=False):
153
raise NotImplementedError('unsupported flag support not implemented yet.')
154
reference_url = self.get_branch_reference()
155
if reference_url is None:
156
# branch at this location.
157
return RemoteBranch(self, self.find_repository())
159
# a branch reference, use the existing BranchReference logic.
160
format = BranchReferenceFormat()
161
return format.open(self, _found=True, location=reference_url)
163
def open_repository(self):
164
path = self._path_for_remote_call(self._client)
165
verb = 'BzrDir.find_repositoryV2'
168
response = self._client.call(verb, path)
169
except errors.UnknownSmartMethod:
170
verb = 'BzrDir.find_repository'
171
response = self._client.call(verb, path)
172
except errors.ErrorFromSmartServer, err:
173
self._translate_error(err)
174
if response[0] != 'ok':
175
raise errors.UnexpectedSmartServerResponse(response)
176
if verb == 'BzrDir.find_repository':
177
# servers that don't support the V2 method don't support external
179
response = response + ('no', )
180
if not (len(response) == 5):
181
raise SmartProtocolError('incorrect response length %s' % (response,))
182
if response[1] == '':
183
format = RemoteRepositoryFormat()
184
format.rich_root_data = (response[2] == 'yes')
185
format.supports_tree_reference = (response[3] == 'yes')
186
# No wire format to check this yet.
187
format.supports_external_lookups = (response[4] == 'yes')
188
# Used to support creating a real format instance when needed.
189
format._creating_bzrdir = self
190
return RemoteRepository(self, format)
192
raise errors.NoRepositoryPresent(self)
194
def open_workingtree(self, recommend_upgrade=True):
196
if self._real_bzrdir.has_workingtree():
197
raise errors.NotLocalUrl(self.root_transport)
199
raise errors.NoWorkingTree(self.root_transport.base)
201
def _path_for_remote_call(self, client):
202
"""Return the path to be used for this bzrdir in a remote call."""
203
return client.remote_path_from_transport(self.root_transport)
205
def get_branch_transport(self, branch_format):
207
return self._real_bzrdir.get_branch_transport(branch_format)
209
def get_repository_transport(self, repository_format):
211
return self._real_bzrdir.get_repository_transport(repository_format)
213
def get_workingtree_transport(self, workingtree_format):
215
return self._real_bzrdir.get_workingtree_transport(workingtree_format)
217
def can_convert_format(self):
218
"""Upgrading of remote bzrdirs is not supported yet."""
221
def needs_format_conversion(self, format=None):
222
"""Upgrading of remote bzrdirs is not supported yet."""
225
def clone(self, url, revision_id=None, force_new_repo=False,
226
preserve_stacking=False):
228
return self._real_bzrdir.clone(url, revision_id=revision_id,
229
force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
231
def get_config(self):
233
return self._real_bzrdir.get_config()
236
class RemoteRepositoryFormat(repository.RepositoryFormat):
237
"""Format for repositories accessed over a _SmartClient.
239
Instances of this repository are represented by RemoteRepository
242
The RemoteRepositoryFormat is parameterized during construction
243
to reflect the capabilities of the real, remote format. Specifically
244
the attributes rich_root_data and supports_tree_reference are set
245
on a per instance basis, and are not set (and should not be) at
249
_matchingbzrdir = RemoteBzrDirFormat()
251
def initialize(self, a_bzrdir, shared=False):
252
if not isinstance(a_bzrdir, RemoteBzrDir):
253
prior_repo = self._creating_bzrdir.open_repository()
254
prior_repo._ensure_real()
255
return prior_repo._real_repository._format.initialize(
256
a_bzrdir, shared=shared)
257
return a_bzrdir.create_repository(shared=shared)
259
def open(self, a_bzrdir):
260
if not isinstance(a_bzrdir, RemoteBzrDir):
261
raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
262
return a_bzrdir.open_repository()
264
def get_format_description(self):
265
return 'bzr remote repository'
267
def __eq__(self, other):
268
return self.__class__ == other.__class__
270
def check_conversion_target(self, target_format):
271
if self.rich_root_data and not target_format.rich_root_data:
272
raise errors.BadConversionTarget(
273
'Does not support rich root data.', target_format)
274
if (self.supports_tree_reference and
275
not getattr(target_format, 'supports_tree_reference', False)):
276
raise errors.BadConversionTarget(
277
'Does not support nested trees', target_format)
280
class RemoteRepository(object):
281
"""Repository accessed over rpc.
283
For the moment most operations are performed using local transport-backed
287
def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
288
"""Create a RemoteRepository instance.
290
:param remote_bzrdir: The bzrdir hosting this repository.
291
:param format: The RemoteFormat object to use.
292
:param real_repository: If not None, a local implementation of the
293
repository logic for the repository, usually accessing the data
295
:param _client: Private testing parameter - override the smart client
296
to be used by the repository.
299
self._real_repository = real_repository
301
self._real_repository = None
302
self.bzrdir = remote_bzrdir
304
self._client = remote_bzrdir._client
306
self._client = _client
307
self._format = format
308
self._lock_mode = None
309
self._lock_token = None
311
self._leave_lock = False
312
# A cache of looked up revision parent data; reset at unlock time.
313
self._parents_map = None
314
if 'hpss' in debug.debug_flags:
315
self._requested_parents = None
317
# These depend on the actual remote format, so force them off for
318
# maximum compatibility. XXX: In future these should depend on the
319
# remote repository instance, but this is irrelevant until we perform
320
# reconcile via an RPC call.
321
self._reconcile_does_inventory_gc = False
322
self._reconcile_fixes_text_parents = False
323
self._reconcile_backsup_inventory = False
324
self.base = self.bzrdir.transport.base
325
# Additional places to query for data.
326
self._fallback_repositories = []
329
return "%s(%s)" % (self.__class__.__name__, self.base)
333
def abort_write_group(self):
334
"""Complete a write group on the decorated repository.
336
Smart methods peform operations in a single step so this api
337
is not really applicable except as a compatibility thunk
338
for older plugins that don't use e.g. the CommitBuilder
342
return self._real_repository.abort_write_group()
344
def commit_write_group(self):
345
"""Complete a write group on the decorated repository.
347
Smart methods peform operations in a single step so this api
348
is not really applicable except as a compatibility thunk
349
for older plugins that don't use e.g. the CommitBuilder
353
return self._real_repository.commit_write_group()
355
def _ensure_real(self):
356
"""Ensure that there is a _real_repository set.
358
Used before calls to self._real_repository.
360
if not self._real_repository:
361
self.bzrdir._ensure_real()
362
#self._real_repository = self.bzrdir._real_bzrdir.open_repository()
363
self._set_real_repository(self.bzrdir._real_bzrdir.open_repository())
365
def _translate_error(self, err, **context):
366
self.bzrdir._translate_error(err, repository=self, **context)
368
def find_text_key_references(self):
369
"""Find the text key references within the repository.
371
:return: a dictionary mapping (file_id, revision_id) tuples to altered file-ids to an iterable of
372
revision_ids. Each altered file-ids has the exact revision_ids that
373
altered it listed explicitly.
374
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
375
to whether they were referred to by the inventory of the
376
revision_id that they contain. The inventory texts from all present
377
revision ids are assessed to generate this report.
380
return self._real_repository.find_text_key_references()
382
def _generate_text_key_index(self):
383
"""Generate a new text key index for the repository.
385
This is an expensive function that will take considerable time to run.
387
:return: A dict mapping (file_id, revision_id) tuples to a list of
388
parents, also (file_id, revision_id) tuples.
391
return self._real_repository._generate_text_key_index()
393
@symbol_versioning.deprecated_method(symbol_versioning.one_four)
394
def get_revision_graph(self, revision_id=None):
395
"""See Repository.get_revision_graph()."""
396
return self._get_revision_graph(revision_id)
398
def _get_revision_graph(self, revision_id):
399
"""Private method for using with old (< 1.2) servers to fallback."""
400
if revision_id is None:
402
elif revision.is_null(revision_id):
405
path = self.bzrdir._path_for_remote_call(self._client)
407
response = self._client.call_expecting_body(
408
'Repository.get_revision_graph', path, revision_id)
409
except errors.ErrorFromSmartServer, err:
410
self._translate_error(err)
411
response_tuple, response_handler = response
412
if response_tuple[0] != 'ok':
413
raise errors.UnexpectedSmartServerResponse(response_tuple)
414
coded = response_handler.read_body_bytes()
416
# no revisions in this repository!
418
lines = coded.split('\n')
421
d = tuple(line.split())
422
revision_graph[d[0]] = d[1:]
424
return revision_graph
426
def has_revision(self, revision_id):
427
"""See Repository.has_revision()."""
428
if revision_id == NULL_REVISION:
429
# The null revision is always present.
431
path = self.bzrdir._path_for_remote_call(self._client)
432
response = self._client.call(
433
'Repository.has_revision', path, revision_id)
434
if response[0] not in ('yes', 'no'):
435
raise errors.UnexpectedSmartServerResponse(response)
436
if response[0] == 'yes':
438
for fallback_repo in self._fallback_repositories:
439
if fallback_repo.has_revision(revision_id):
443
def has_revisions(self, revision_ids):
444
"""See Repository.has_revisions()."""
445
# FIXME: This does many roundtrips, particularly when there are
446
# fallback repositories. -- mbp 20080905
448
for revision_id in revision_ids:
449
if self.has_revision(revision_id):
450
result.add(revision_id)
453
def has_same_location(self, other):
454
return (self.__class__ == other.__class__ and
455
self.bzrdir.transport.base == other.bzrdir.transport.base)
457
def get_graph(self, other_repository=None):
458
"""Return the graph for this repository format"""
459
parents_provider = self
460
if (other_repository is not None and
461
other_repository.bzrdir.transport.base !=
462
self.bzrdir.transport.base):
463
parents_provider = graph._StackedParentsProvider(
464
[parents_provider, other_repository._make_parents_provider()])
465
return graph.Graph(parents_provider)
467
def gather_stats(self, revid=None, committers=None):
468
"""See Repository.gather_stats()."""
469
path = self.bzrdir._path_for_remote_call(self._client)
470
# revid can be None to indicate no revisions, not just NULL_REVISION
471
if revid is None or revision.is_null(revid):
475
if committers is None or not committers:
476
fmt_committers = 'no'
478
fmt_committers = 'yes'
479
response_tuple, response_handler = self._client.call_expecting_body(
480
'Repository.gather_stats', path, fmt_revid, fmt_committers)
481
if response_tuple[0] != 'ok':
482
raise errors.UnexpectedSmartServerResponse(response_tuple)
484
body = response_handler.read_body_bytes()
486
for line in body.split('\n'):
489
key, val_text = line.split(':')
490
if key in ('revisions', 'size', 'committers'):
491
result[key] = int(val_text)
492
elif key in ('firstrev', 'latestrev'):
493
values = val_text.split(' ')[1:]
494
result[key] = (float(values[0]), long(values[1]))
498
def find_branches(self, using=False):
499
"""See Repository.find_branches()."""
500
# should be an API call to the server.
502
return self._real_repository.find_branches(using=using)
504
def get_physical_lock_status(self):
505
"""See Repository.get_physical_lock_status()."""
506
# should be an API call to the server.
508
return self._real_repository.get_physical_lock_status()
510
def is_in_write_group(self):
511
"""Return True if there is an open write group.
513
write groups are only applicable locally for the smart server..
515
if self._real_repository:
516
return self._real_repository.is_in_write_group()
519
return self._lock_count >= 1
522
"""See Repository.is_shared()."""
523
path = self.bzrdir._path_for_remote_call(self._client)
524
response = self._client.call('Repository.is_shared', path)
525
if response[0] not in ('yes', 'no'):
526
raise SmartProtocolError('unexpected response code %s' % (response,))
527
return response[0] == 'yes'
529
def is_write_locked(self):
530
return self._lock_mode == 'w'
533
# wrong eventually - want a local lock cache context
534
if not self._lock_mode:
535
self._lock_mode = 'r'
537
self._parents_map = {}
538
if 'hpss' in debug.debug_flags:
539
self._requested_parents = set()
540
if self._real_repository is not None:
541
self._real_repository.lock_read()
543
self._lock_count += 1
545
def _remote_lock_write(self, token):
546
path = self.bzrdir._path_for_remote_call(self._client)
550
response = self._client.call('Repository.lock_write', path, token)
551
except errors.ErrorFromSmartServer, err:
552
self._translate_error(err, token=token)
554
if response[0] == 'ok':
558
raise errors.UnexpectedSmartServerResponse(response)
560
def lock_write(self, token=None):
561
if not self._lock_mode:
562
self._lock_token = self._remote_lock_write(token)
563
# if self._lock_token is None, then this is something like packs or
564
# svn where we don't get to lock the repo, or a weave style repository
565
# where we cannot lock it over the wire and attempts to do so will
567
if self._real_repository is not None:
568
self._real_repository.lock_write(token=self._lock_token)
569
if token is not None:
570
self._leave_lock = True
572
self._leave_lock = False
573
self._lock_mode = 'w'
575
self._parents_map = {}
576
if 'hpss' in debug.debug_flags:
577
self._requested_parents = set()
578
elif self._lock_mode == 'r':
579
raise errors.ReadOnlyError(self)
581
self._lock_count += 1
582
return self._lock_token or None
584
def leave_lock_in_place(self):
585
if not self._lock_token:
586
raise NotImplementedError(self.leave_lock_in_place)
587
self._leave_lock = True
589
def dont_leave_lock_in_place(self):
590
if not self._lock_token:
591
raise NotImplementedError(self.dont_leave_lock_in_place)
592
self._leave_lock = False
594
def _set_real_repository(self, repository):
595
"""Set the _real_repository for this repository.
597
:param repository: The repository to fallback to for non-hpss
598
implemented operations.
600
if isinstance(repository, RemoteRepository):
601
raise AssertionError()
602
self._real_repository = repository
603
if self._lock_mode == 'w':
604
# if we are already locked, the real repository must be able to
605
# acquire the lock with our token.
606
self._real_repository.lock_write(self._lock_token)
607
elif self._lock_mode == 'r':
608
self._real_repository.lock_read()
610
def start_write_group(self):
611
"""Start a write group on the decorated repository.
613
Smart methods peform operations in a single step so this api
614
is not really applicable except as a compatibility thunk
615
for older plugins that don't use e.g. the CommitBuilder
619
return self._real_repository.start_write_group()
621
def _unlock(self, token):
622
path = self.bzrdir._path_for_remote_call(self._client)
624
# with no token the remote repository is not persistently locked.
627
response = self._client.call('Repository.unlock', path, token)
628
except errors.ErrorFromSmartServer, err:
629
self._translate_error(err, token=token)
630
if response == ('ok',):
633
raise errors.UnexpectedSmartServerResponse(response)
636
self._lock_count -= 1
637
if self._lock_count > 0:
639
self._parents_map = None
640
if 'hpss' in debug.debug_flags:
641
self._requested_parents = None
642
old_mode = self._lock_mode
643
self._lock_mode = None
645
# The real repository is responsible at present for raising an
646
# exception if it's in an unfinished write group. However, it
647
# normally will *not* actually remove the lock from disk - that's
648
# done by the server on receiving the Repository.unlock call.
649
# This is just to let the _real_repository stay up to date.
650
if self._real_repository is not None:
651
self._real_repository.unlock()
653
# The rpc-level lock should be released even if there was a
654
# problem releasing the vfs-based lock.
656
# Only write-locked repositories need to make a remote method
657
# call to perfom the unlock.
658
old_token = self._lock_token
659
self._lock_token = None
660
if not self._leave_lock:
661
self._unlock(old_token)
663
def break_lock(self):
664
# should hand off to the network
666
return self._real_repository.break_lock()
668
def _get_tarball(self, compression):
669
"""Return a TemporaryFile containing a repository tarball.
671
Returns None if the server does not support sending tarballs.
674
path = self.bzrdir._path_for_remote_call(self._client)
676
response, protocol = self._client.call_expecting_body(
677
'Repository.tarball', path, compression)
678
except errors.UnknownSmartMethod:
679
protocol.cancel_read_body()
681
if response[0] == 'ok':
682
# Extract the tarball and return it
683
t = tempfile.NamedTemporaryFile()
684
# TODO: rpc layer should read directly into it...
685
t.write(protocol.read_body_bytes())
688
raise errors.UnexpectedSmartServerResponse(response)
690
def sprout(self, to_bzrdir, revision_id=None):
691
# TODO: Option to control what format is created?
693
dest_repo = self._real_repository._format.initialize(to_bzrdir,
695
dest_repo.fetch(self, revision_id=revision_id)
698
### These methods are just thin shims to the VFS object for now.
700
def revision_tree(self, revision_id):
702
return self._real_repository.revision_tree(revision_id)
704
def get_serializer_format(self):
706
return self._real_repository.get_serializer_format()
708
def get_commit_builder(self, branch, parents, config, timestamp=None,
709
timezone=None, committer=None, revprops=None,
711
# FIXME: It ought to be possible to call this without immediately
712
# triggering _ensure_real. For now it's the easiest thing to do.
714
builder = self._real_repository.get_commit_builder(branch, parents,
715
config, timestamp=timestamp, timezone=timezone,
716
committer=committer, revprops=revprops, revision_id=revision_id)
719
def add_fallback_repository(self, repository):
720
"""Add a repository to use for looking up data not held locally.
722
:param repository: A repository.
724
if not self._format.supports_external_lookups:
725
raise errors.UnstackableRepositoryFormat(self._format, self.base)
726
# We need to accumulate additional repositories here, to pass them in
728
self._fallback_repositories.append(repository)
730
def add_inventory(self, revid, inv, parents):
732
return self._real_repository.add_inventory(revid, inv, parents)
734
def add_revision(self, rev_id, rev, inv=None, config=None):
736
return self._real_repository.add_revision(
737
rev_id, rev, inv=inv, config=config)
740
def get_inventory(self, revision_id):
742
return self._real_repository.get_inventory(revision_id)
744
def iter_inventories(self, revision_ids):
746
return self._real_repository.iter_inventories(revision_ids)
749
def get_revision(self, revision_id):
751
return self._real_repository.get_revision(revision_id)
753
def get_transaction(self):
755
return self._real_repository.get_transaction()
758
def clone(self, a_bzrdir, revision_id=None):
760
return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
762
def make_working_trees(self):
763
"""See Repository.make_working_trees"""
765
return self._real_repository.make_working_trees()
767
def revision_ids_to_search_result(self, result_set):
768
"""Convert a set of revision ids to a graph SearchResult."""
769
result_parents = set()
770
for parents in self.get_graph().get_parent_map(
771
result_set).itervalues():
772
result_parents.update(parents)
773
included_keys = result_set.intersection(result_parents)
774
start_keys = result_set.difference(included_keys)
775
exclude_keys = result_parents.difference(result_set)
776
result = graph.SearchResult(start_keys, exclude_keys,
777
len(result_set), result_set)
781
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
782
"""Return the revision ids that other has that this does not.
784
These are returned in topological order.
786
revision_id: only return revision ids included by revision_id.
788
return repository.InterRepository.get(
789
other, self).search_missing_revision_ids(revision_id, find_ghosts)
791
def fetch(self, source, revision_id=None, pb=None):
792
if self.has_same_location(source):
793
# check that last_revision is in 'from' and then return a
795
if (revision_id is not None and
796
not revision.is_null(revision_id)):
797
self.get_revision(revision_id)
800
return self._real_repository.fetch(
801
source, revision_id=revision_id, pb=pb)
803
def create_bundle(self, target, base, fileobj, format=None):
805
self._real_repository.create_bundle(target, base, fileobj, format)
808
def get_ancestry(self, revision_id, topo_sorted=True):
810
return self._real_repository.get_ancestry(revision_id, topo_sorted)
812
def fileids_altered_by_revision_ids(self, revision_ids):
814
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
816
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
818
return self._real_repository._get_versioned_file_checker(
819
revisions, revision_versions_cache)
821
def iter_files_bytes(self, desired_files):
822
"""See Repository.iter_file_bytes.
825
return self._real_repository.iter_files_bytes(desired_files)
828
def _fetch_order(self):
829
"""Decorate the real repository for now.
831
In the long term getting this back from the remote repository as part
832
of open would be more efficient.
835
return self._real_repository._fetch_order
838
def _fetch_uses_deltas(self):
839
"""Decorate the real repository for now.
841
In the long term getting this back from the remote repository as part
842
of open would be more efficient.
845
return self._real_repository._fetch_uses_deltas
848
def _fetch_reconcile(self):
849
"""Decorate the real repository for now.
851
In the long term getting this back from the remote repository as part
852
of open would be more efficient.
855
return self._real_repository._fetch_reconcile
857
def get_parent_map(self, keys):
858
"""See bzrlib.Graph.get_parent_map()."""
859
# Hack to build up the caching logic.
860
ancestry = self._parents_map
862
# Repository is not locked, so there's no cache.
863
missing_revisions = set(keys)
866
missing_revisions = set(key for key in keys if key not in ancestry)
867
if missing_revisions:
868
parent_map = self._get_parent_map(missing_revisions)
869
if 'hpss' in debug.debug_flags:
870
mutter('retransmitted revisions: %d of %d',
871
len(set(ancestry).intersection(parent_map)),
873
ancestry.update(parent_map)
874
present_keys = [k for k in keys if k in ancestry]
875
if 'hpss' in debug.debug_flags:
876
if self._requested_parents is not None and len(ancestry) != 0:
877
self._requested_parents.update(present_keys)
878
mutter('Current RemoteRepository graph hit rate: %d%%',
879
100.0 * len(self._requested_parents) / len(ancestry))
880
return dict((k, ancestry[k]) for k in present_keys)
882
def _get_parent_map(self, keys):
883
"""Helper for get_parent_map that performs the RPC."""
884
medium = self._client._medium
885
if medium._is_remote_before((1, 2)):
886
# We already found out that the server can't understand
887
# Repository.get_parent_map requests, so just fetch the whole
889
# XXX: Note that this will issue a deprecation warning. This is ok
890
# :- its because we're working with a deprecated server anyway, and
891
# the user will almost certainly have seen a warning about the
892
# server version already.
893
rg = self.get_revision_graph()
894
# There is an api discrepency between get_parent_map and
895
# get_revision_graph. Specifically, a "key:()" pair in
896
# get_revision_graph just means a node has no parents. For
897
# "get_parent_map" it means the node is a ghost. So fix up the
898
# graph to correct this.
899
# https://bugs.launchpad.net/bzr/+bug/214894
900
# There is one other "bug" which is that ghosts in
901
# get_revision_graph() are not returned at all. But we won't worry
902
# about that for now.
903
for node_id, parent_ids in rg.iteritems():
905
rg[node_id] = (NULL_REVISION,)
906
rg[NULL_REVISION] = ()
911
raise ValueError('get_parent_map(None) is not valid')
912
if NULL_REVISION in keys:
913
keys.discard(NULL_REVISION)
914
found_parents = {NULL_REVISION:()}
919
# TODO(Needs analysis): We could assume that the keys being requested
920
# from get_parent_map are in a breadth first search, so typically they
921
# will all be depth N from some common parent, and we don't have to
922
# have the server iterate from the root parent, but rather from the
923
# keys we're searching; and just tell the server the keyspace we
924
# already have; but this may be more traffic again.
926
# Transform self._parents_map into a search request recipe.
927
# TODO: Manage this incrementally to avoid covering the same path
928
# repeatedly. (The server will have to on each request, but the less
929
# work done the better).
930
parents_map = self._parents_map
931
if parents_map is None:
932
# Repository is not locked, so there's no cache.
934
start_set = set(parents_map)
935
result_parents = set()
936
for parents in parents_map.itervalues():
937
result_parents.update(parents)
938
stop_keys = result_parents.difference(start_set)
939
included_keys = start_set.intersection(result_parents)
940
start_set.difference_update(included_keys)
941
recipe = (start_set, stop_keys, len(parents_map))
942
body = self._serialise_search_recipe(recipe)
943
path = self.bzrdir._path_for_remote_call(self._client)
945
if type(key) is not str:
947
"key %r not a plain string" % (key,))
948
verb = 'Repository.get_parent_map'
949
args = (path,) + tuple(keys)
951
response = self._client.call_with_body_bytes_expecting_body(
952
verb, args, self._serialise_search_recipe(recipe))
953
except errors.UnknownSmartMethod:
954
# Server does not support this method, so get the whole graph.
955
# Worse, we have to force a disconnection, because the server now
956
# doesn't realise it has a body on the wire to consume, so the
957
# only way to recover is to abandon the connection.
959
'Server is too old for fast get_parent_map, reconnecting. '
960
'(Upgrade the server to Bazaar 1.2 to avoid this)')
962
# To avoid having to disconnect repeatedly, we keep track of the
963
# fact the server doesn't understand remote methods added in 1.2.
964
medium._remember_remote_is_before((1, 2))
965
return self.get_revision_graph(None)
966
response_tuple, response_handler = response
967
if response_tuple[0] not in ['ok']:
968
response_handler.cancel_read_body()
969
raise errors.UnexpectedSmartServerResponse(response_tuple)
970
if response_tuple[0] == 'ok':
971
coded = bz2.decompress(response_handler.read_body_bytes())
975
lines = coded.split('\n')
978
d = tuple(line.split())
980
revision_graph[d[0]] = d[1:]
982
# No parents - so give the Graph result (NULL_REVISION,).
983
revision_graph[d[0]] = (NULL_REVISION,)
984
return revision_graph
987
def get_signature_text(self, revision_id):
989
return self._real_repository.get_signature_text(revision_id)
992
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
993
def get_revision_graph_with_ghosts(self, revision_ids=None):
995
return self._real_repository.get_revision_graph_with_ghosts(
996
revision_ids=revision_ids)
999
def get_inventory_xml(self, revision_id):
1001
return self._real_repository.get_inventory_xml(revision_id)
1003
def deserialise_inventory(self, revision_id, xml):
1005
return self._real_repository.deserialise_inventory(revision_id, xml)
1007
def reconcile(self, other=None, thorough=False):
1009
return self._real_repository.reconcile(other=other, thorough=thorough)
1011
def all_revision_ids(self):
1013
return self._real_repository.all_revision_ids()
1016
def get_deltas_for_revisions(self, revisions):
1018
return self._real_repository.get_deltas_for_revisions(revisions)
1021
def get_revision_delta(self, revision_id):
1023
return self._real_repository.get_revision_delta(revision_id)
1026
def revision_trees(self, revision_ids):
1028
return self._real_repository.revision_trees(revision_ids)
1031
def get_revision_reconcile(self, revision_id):
1033
return self._real_repository.get_revision_reconcile(revision_id)
1036
def check(self, revision_ids=None):
1038
return self._real_repository.check(revision_ids=revision_ids)
1040
def copy_content_into(self, destination, revision_id=None):
1042
return self._real_repository.copy_content_into(
1043
destination, revision_id=revision_id)
1045
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1046
# get a tarball of the remote repository, and copy from that into the
1048
from bzrlib import osutils
1050
# TODO: Maybe a progress bar while streaming the tarball?
1051
note("Copying repository content as tarball...")
1052
tar_file = self._get_tarball('bz2')
1053
if tar_file is None:
1055
destination = to_bzrdir.create_repository()
1057
tar = tarfile.open('repository', fileobj=tar_file,
1059
tmpdir = osutils.mkdtemp()
1061
_extract_tar(tar, tmpdir)
1062
tmp_bzrdir = BzrDir.open(tmpdir)
1063
tmp_repo = tmp_bzrdir.open_repository()
1064
tmp_repo.copy_content_into(destination, revision_id)
1066
osutils.rmtree(tmpdir)
1070
# TODO: Suggestion from john: using external tar is much faster than
1071
# python's tarfile library, but it may not work on windows.
1074
def inventories(self):
1075
"""Decorate the real repository for now.
1077
In the long term a full blown network facility is needed to
1078
avoid creating a real repository object locally.
1081
return self._real_repository.inventories
1085
"""Compress the data within the repository.
1087
This is not currently implemented within the smart server.
1090
return self._real_repository.pack()
1093
def revisions(self):
1094
"""Decorate the real repository for now.
1096
In the short term this should become a real object to intercept graph
1099
In the long term a full blown network facility is needed.
1102
return self._real_repository.revisions
1104
def set_make_working_trees(self, new_value):
1106
self._real_repository.set_make_working_trees(new_value)
1109
def signatures(self):
1110
"""Decorate the real repository for now.
1112
In the long term a full blown network facility is needed to avoid
1113
creating a real repository object locally.
1116
return self._real_repository.signatures
1119
def sign_revision(self, revision_id, gpg_strategy):
1121
return self._real_repository.sign_revision(revision_id, gpg_strategy)
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.texts
1134
def get_revisions(self, revision_ids):
1136
return self._real_repository.get_revisions(revision_ids)
1138
def supports_rich_root(self):
1140
return self._real_repository.supports_rich_root()
1142
def iter_reverse_revision_history(self, revision_id):
1144
return self._real_repository.iter_reverse_revision_history(revision_id)
1147
def _serializer(self):
1149
return self._real_repository._serializer
1151
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1153
return self._real_repository.store_revision_signature(
1154
gpg_strategy, plaintext, revision_id)
1156
def add_signature_text(self, revision_id, signature):
1158
return self._real_repository.add_signature_text(revision_id, signature)
1160
def has_signature_for_revision_id(self, revision_id):
1162
return self._real_repository.has_signature_for_revision_id(revision_id)
1164
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1166
return self._real_repository.item_keys_introduced_by(revision_ids,
1167
_files_pb=_files_pb)
1169
def revision_graph_can_have_wrong_parents(self):
1170
# The answer depends on the remote repo format.
1172
return self._real_repository.revision_graph_can_have_wrong_parents()
1174
def _find_inconsistent_revision_parents(self):
1176
return self._real_repository._find_inconsistent_revision_parents()
1178
def _check_for_inconsistent_revision_parents(self):
1180
return self._real_repository._check_for_inconsistent_revision_parents()
1182
def _make_parents_provider(self):
1185
def _serialise_search_recipe(self, recipe):
1186
"""Serialise a graph search recipe.
1188
:param recipe: A search recipe (start, stop, count).
1189
:return: Serialised bytes.
1191
start_keys = ' '.join(recipe[0])
1192
stop_keys = ' '.join(recipe[1])
1193
count = str(recipe[2])
1194
return '\n'.join((start_keys, stop_keys, count))
1197
class RemoteBranchLockableFiles(LockableFiles):
1198
"""A 'LockableFiles' implementation that talks to a smart server.
1200
This is not a public interface class.
1203
def __init__(self, bzrdir, _client):
1204
self.bzrdir = bzrdir
1205
self._client = _client
1206
self._need_find_modes = True
1207
LockableFiles.__init__(
1208
self, bzrdir.get_branch_transport(None),
1209
'lock', lockdir.LockDir)
1211
def _find_modes(self):
1212
# RemoteBranches don't let the client set the mode of control files.
1213
self._dir_mode = None
1214
self._file_mode = None
1217
class RemoteBranchFormat(branch.BranchFormat):
1219
def __eq__(self, other):
1220
return (isinstance(other, RemoteBranchFormat) and
1221
self.__dict__ == other.__dict__)
1223
def get_format_description(self):
1224
return 'Remote BZR Branch'
1226
def get_format_string(self):
1227
return 'Remote BZR Branch'
1229
def open(self, a_bzrdir):
1230
return a_bzrdir.open_branch()
1232
def initialize(self, a_bzrdir):
1233
return a_bzrdir.create_branch()
1235
def supports_tags(self):
1236
# Remote branches might support tags, but we won't know until we
1237
# access the real remote branch.
1241
class RemoteBranch(branch.Branch):
1242
"""Branch stored on a server accessed by HPSS RPC.
1244
At the moment most operations are mapped down to simple file operations.
1247
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1249
"""Create a RemoteBranch instance.
1251
:param real_branch: An optional local implementation of the branch
1252
format, usually accessing the data via the VFS.
1253
:param _client: Private parameter for testing.
1255
# We intentionally don't call the parent class's __init__, because it
1256
# will try to assign to self.tags, which is a property in this subclass.
1257
# And the parent's __init__ doesn't do much anyway.
1258
self._revision_id_to_revno_cache = None
1259
self._revision_history_cache = None
1260
self._last_revision_info_cache = None
1261
self.bzrdir = remote_bzrdir
1262
if _client is not None:
1263
self._client = _client
1265
self._client = remote_bzrdir._client
1266
self.repository = remote_repository
1267
if real_branch is not None:
1268
self._real_branch = real_branch
1269
# Give the remote repository the matching real repo.
1270
real_repo = self._real_branch.repository
1271
if isinstance(real_repo, RemoteRepository):
1272
real_repo._ensure_real()
1273
real_repo = real_repo._real_repository
1274
self.repository._set_real_repository(real_repo)
1275
# Give the branch the remote repository to let fast-pathing happen.
1276
self._real_branch.repository = self.repository
1278
self._real_branch = None
1279
# Fill out expected attributes of branch for bzrlib api users.
1280
self._format = RemoteBranchFormat()
1281
self.base = self.bzrdir.root_transport.base
1282
self._control_files = None
1283
self._lock_mode = None
1284
self._lock_token = None
1285
self._repo_lock_token = None
1286
self._lock_count = 0
1287
self._leave_lock = False
1288
self._setup_stacking()
1290
def _setup_stacking(self):
1291
# configure stacking into the remote repository, by reading it from
1292
# the vfs branch. note that this currently implicitly creates a
1293
# _real_branch so will block getting rid of vfs until the operation is
1294
# done at a higher level.
1296
fallback_url = self.get_stacked_on_url()
1297
# it's relative to this branch...
1298
fallback_url = urlutils.join(self.base, fallback_url)
1299
fallback_repo = BzrDir.open(fallback_url,
1300
[self.bzrdir.root_transport,
1301
self._real_branch._transport]).open_repository()
1302
self.repository.add_fallback_repository(fallback_repo)
1303
except (errors.NotStacked, errors.UnstackableBranchFormat,
1304
errors.UnstackableRepositoryFormat), e:
1307
def _get_real_transport(self):
1308
# if we try vfs access, return the real branch's vfs transport
1310
return self._real_branch._transport
1312
_transport = property(_get_real_transport)
1315
return "%s(%s)" % (self.__class__.__name__, self.base)
1319
def _ensure_real(self):
1320
"""Ensure that there is a _real_branch set.
1322
Used before calls to self._real_branch.
1324
if self._real_branch is None:
1325
if not vfs.vfs_enabled():
1326
raise AssertionError('smart server vfs must be enabled '
1327
'to use vfs implementation')
1328
self.bzrdir._ensure_real()
1329
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1330
# Give the remote repository the matching real repo.
1331
real_repo = self._real_branch.repository
1332
if isinstance(real_repo, RemoteRepository):
1333
real_repo._ensure_real()
1334
real_repo = real_repo._real_repository
1335
self.repository._set_real_repository(real_repo)
1336
# Give the branch the remote repository to let fast-pathing happen.
1337
self._real_branch.repository = self.repository
1338
# XXX: deal with _lock_mode == 'w'
1339
if self._lock_mode == 'r':
1340
self._real_branch.lock_read()
1342
def _translate_error(self, err, **context):
1343
self.repository._translate_error(err, branch=self, **context)
1345
def _clear_cached_state(self):
1346
super(RemoteBranch, self)._clear_cached_state()
1347
if self._real_branch is not None:
1348
self._real_branch._clear_cached_state()
1350
def _clear_cached_state_of_remote_branch_only(self):
1351
"""Like _clear_cached_state, but doesn't clear the cache of
1354
This is useful when falling back to calling a method of
1355
self._real_branch that changes state. In that case the underlying
1356
branch changes, so we need to invalidate this RemoteBranch's cache of
1357
it. However, there's no need to invalidate the _real_branch's cache
1358
too, in fact doing so might harm performance.
1360
super(RemoteBranch, self)._clear_cached_state()
1363
def control_files(self):
1364
# Defer actually creating RemoteBranchLockableFiles until its needed,
1365
# because it triggers an _ensure_real that we otherwise might not need.
1366
if self._control_files is None:
1367
self._control_files = RemoteBranchLockableFiles(
1368
self.bzrdir, self._client)
1369
return self._control_files
1371
def _get_checkout_format(self):
1373
return self._real_branch._get_checkout_format()
1375
def get_physical_lock_status(self):
1376
"""See Branch.get_physical_lock_status()."""
1377
# should be an API call to the server, as branches must be lockable.
1379
return self._real_branch.get_physical_lock_status()
1381
def get_stacked_on_url(self):
1382
"""Get the URL this branch is stacked against.
1384
:raises NotStacked: If the branch is not stacked.
1385
:raises UnstackableBranchFormat: If the branch does not support
1387
:raises UnstackableRepositoryFormat: If the repository does not support
1391
return self._real_branch.get_stacked_on_url()
1393
def lock_read(self):
1394
if not self._lock_mode:
1395
self._lock_mode = 'r'
1396
self._lock_count = 1
1397
if self._real_branch is not None:
1398
self._real_branch.lock_read()
1400
self._lock_count += 1
1402
def _remote_lock_write(self, token):
1404
branch_token = repo_token = ''
1406
branch_token = token
1407
repo_token = self.repository.lock_write()
1408
self.repository.unlock()
1409
path = self.bzrdir._path_for_remote_call(self._client)
1411
response = self._client.call(
1412
'Branch.lock_write', path, branch_token, repo_token or '')
1413
except errors.ErrorFromSmartServer, err:
1414
self._translate_error(err, token=token)
1415
if response[0] != 'ok':
1416
raise errors.UnexpectedSmartServerResponse(response)
1417
ok, branch_token, repo_token = response
1418
return branch_token, repo_token
1420
def lock_write(self, token=None):
1421
if not self._lock_mode:
1422
remote_tokens = self._remote_lock_write(token)
1423
self._lock_token, self._repo_lock_token = remote_tokens
1424
if not self._lock_token:
1425
raise SmartProtocolError('Remote server did not return a token!')
1426
# TODO: We really, really, really don't want to call _ensure_real
1427
# here, but it's the easiest way to ensure coherency between the
1428
# state of the RemoteBranch and RemoteRepository objects and the
1429
# physical locks. If we don't materialise the real objects here,
1430
# then getting everything in the right state later is complex, so
1431
# for now we just do it the lazy way.
1432
# -- Andrew Bennetts, 2007-02-22.
1434
if self._real_branch is not None:
1435
self._real_branch.repository.lock_write(
1436
token=self._repo_lock_token)
1438
self._real_branch.lock_write(token=self._lock_token)
1440
self._real_branch.repository.unlock()
1441
if token is not None:
1442
self._leave_lock = True
1444
# XXX: this case seems to be unreachable; token cannot be None.
1445
self._leave_lock = False
1446
self._lock_mode = 'w'
1447
self._lock_count = 1
1448
elif self._lock_mode == 'r':
1449
raise errors.ReadOnlyTransaction
1451
if token is not None:
1452
# A token was given to lock_write, and we're relocking, so check
1453
# that the given token actually matches the one we already have.
1454
if token != self._lock_token:
1455
raise errors.TokenMismatch(token, self._lock_token)
1456
self._lock_count += 1
1457
return self._lock_token or None
1459
def _unlock(self, branch_token, repo_token):
1460
path = self.bzrdir._path_for_remote_call(self._client)
1462
response = self._client.call('Branch.unlock', path, branch_token,
1464
except errors.ErrorFromSmartServer, err:
1465
self._translate_error(err, token=str((branch_token, repo_token)))
1466
if response == ('ok',):
1468
raise errors.UnexpectedSmartServerResponse(response)
1471
self._lock_count -= 1
1472
if not self._lock_count:
1473
self._clear_cached_state()
1474
mode = self._lock_mode
1475
self._lock_mode = None
1476
if self._real_branch is not None:
1477
if (not self._leave_lock and mode == 'w' and
1478
self._repo_lock_token):
1479
# If this RemoteBranch will remove the physical lock for the
1480
# repository, make sure the _real_branch doesn't do it
1481
# first. (Because the _real_branch's repository is set to
1482
# be the RemoteRepository.)
1483
self._real_branch.repository.leave_lock_in_place()
1484
self._real_branch.unlock()
1486
# Only write-locked branched need to make a remote method call
1487
# to perfom the unlock.
1489
if not self._lock_token:
1490
raise AssertionError('Locked, but no token!')
1491
branch_token = self._lock_token
1492
repo_token = self._repo_lock_token
1493
self._lock_token = None
1494
self._repo_lock_token = None
1495
if not self._leave_lock:
1496
self._unlock(branch_token, repo_token)
1498
def break_lock(self):
1500
return self._real_branch.break_lock()
1502
def leave_lock_in_place(self):
1503
if not self._lock_token:
1504
raise NotImplementedError(self.leave_lock_in_place)
1505
self._leave_lock = True
1507
def dont_leave_lock_in_place(self):
1508
if not self._lock_token:
1509
raise NotImplementedError(self.dont_leave_lock_in_place)
1510
self._leave_lock = False
1512
def _last_revision_info(self):
1513
path = self.bzrdir._path_for_remote_call(self._client)
1514
response = self._client.call('Branch.last_revision_info', path)
1515
if response[0] != 'ok':
1516
raise SmartProtocolError('unexpected response code %s' % (response,))
1517
revno = int(response[1])
1518
last_revision = response[2]
1519
return (revno, last_revision)
1521
def _gen_revision_history(self):
1522
"""See Branch._gen_revision_history()."""
1523
path = self.bzrdir._path_for_remote_call(self._client)
1524
response_tuple, response_handler = self._client.call_expecting_body(
1525
'Branch.revision_history', path)
1526
if response_tuple[0] != 'ok':
1527
raise errors.UnexpectedSmartServerResponse(response_tuple)
1528
result = response_handler.read_body_bytes().split('\x00')
1533
def _set_last_revision_descendant(self, revision_id, other_branch,
1534
allow_diverged=False, allow_overwrite_descendant=False):
1535
path = self.bzrdir._path_for_remote_call(self._client)
1537
response = self._client.call('Branch.set_last_revision_ex',
1538
path, self._lock_token, self._repo_lock_token, revision_id,
1539
int(allow_diverged), int(allow_overwrite_descendant))
1540
except errors.ErrorFromSmartServer, err:
1541
self._translate_error(err, other_branch=other_branch)
1542
self._clear_cached_state()
1543
if len(response) != 3 and response[0] != 'ok':
1544
raise errors.UnexpectedSmartServerResponse(response)
1545
new_revno, new_revision_id = response[1:]
1546
self._last_revision_info_cache = new_revno, new_revision_id
1547
self._real_branch._last_revision_info_cache = new_revno, new_revision_id
1549
def _set_last_revision(self, revision_id):
1550
path = self.bzrdir._path_for_remote_call(self._client)
1551
self._clear_cached_state()
1553
response = self._client.call('Branch.set_last_revision',
1554
path, self._lock_token, self._repo_lock_token, revision_id)
1555
except errors.ErrorFromSmartServer, err:
1556
self._translate_error(err)
1557
if response != ('ok',):
1558
raise errors.UnexpectedSmartServerResponse(response)
1561
def set_revision_history(self, rev_history):
1562
# Send just the tip revision of the history; the server will generate
1563
# the full history from that. If the revision doesn't exist in this
1564
# branch, NoSuchRevision will be raised.
1565
if rev_history == []:
1568
rev_id = rev_history[-1]
1569
self._set_last_revision(rev_id)
1570
self._cache_revision_history(rev_history)
1572
def get_parent(self):
1574
return self._real_branch.get_parent()
1576
def set_parent(self, url):
1578
return self._real_branch.set_parent(url)
1580
def set_stacked_on_url(self, stacked_location):
1581
"""Set the URL this branch is stacked against.
1583
:raises UnstackableBranchFormat: If the branch does not support
1585
:raises UnstackableRepositoryFormat: If the repository does not support
1589
return self._real_branch.set_stacked_on_url(stacked_location)
1591
def sprout(self, to_bzrdir, revision_id=None):
1592
# Like Branch.sprout, except that it sprouts a branch in the default
1593
# format, because RemoteBranches can't be created at arbitrary URLs.
1594
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1595
# to_bzrdir.create_branch...
1597
result = self._real_branch._format.initialize(to_bzrdir)
1598
self.copy_content_into(result, revision_id=revision_id)
1599
result.set_parent(self.bzrdir.root_transport.base)
1603
def pull(self, source, overwrite=False, stop_revision=None,
1605
self._clear_cached_state_of_remote_branch_only()
1607
return self._real_branch.pull(
1608
source, overwrite=overwrite, stop_revision=stop_revision,
1609
_override_hook_target=self, **kwargs)
1612
def push(self, target, overwrite=False, stop_revision=None):
1614
return self._real_branch.push(
1615
target, overwrite=overwrite, stop_revision=stop_revision,
1616
_override_hook_source_branch=self)
1618
def is_locked(self):
1619
return self._lock_count >= 1
1622
def revision_id_to_revno(self, revision_id):
1624
return self._real_branch.revision_id_to_revno(revision_id)
1627
def set_last_revision_info(self, revno, revision_id):
1628
revision_id = ensure_null(revision_id)
1629
path = self.bzrdir._path_for_remote_call(self._client)
1631
response = self._client.call('Branch.set_last_revision_info',
1632
path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
1633
except errors.UnknownSmartMethod:
1635
self._clear_cached_state_of_remote_branch_only()
1636
self._real_branch.set_last_revision_info(revno, revision_id)
1637
self._last_revision_info_cache = revno, revision_id
1639
except errors.ErrorFromSmartServer, err:
1640
self._translate_error(err)
1641
if response == ('ok',):
1642
self._clear_cached_state()
1643
self._last_revision_info_cache = revno, revision_id
1644
# Update the _real_branch's cache too.
1645
if self._real_branch is not None:
1646
cache = self._last_revision_info_cache
1647
self._real_branch._last_revision_info_cache = cache
1649
raise errors.UnexpectedSmartServerResponse(response)
1652
def generate_revision_history(self, revision_id, last_rev=None,
1654
medium = self._client._medium
1655
if not medium._is_remote_before((1, 6)):
1657
self._set_last_revision_descendant(revision_id, other_branch,
1658
allow_diverged=True, allow_overwrite_descendant=True)
1660
except errors.UnknownSmartMethod:
1661
medium._remember_remote_is_before((1, 6))
1662
self._clear_cached_state_of_remote_branch_only()
1664
self._real_branch.generate_revision_history(
1665
revision_id, last_rev=last_rev, other_branch=other_branch)
1670
return self._real_branch.tags
1672
def set_push_location(self, location):
1674
return self._real_branch.set_push_location(location)
1677
def update_revisions(self, other, stop_revision=None, overwrite=False,
1679
"""See Branch.update_revisions."""
1682
if stop_revision is None:
1683
stop_revision = other.last_revision()
1684
if revision.is_null(stop_revision):
1685
# if there are no commits, we're done.
1687
self.fetch(other, stop_revision)
1690
# Just unconditionally set the new revision. We don't care if
1691
# the branches have diverged.
1692
self._set_last_revision(stop_revision)
1694
medium = self._client._medium
1695
if not medium._is_remote_before((1, 6)):
1697
self._set_last_revision_descendant(stop_revision, other)
1699
except errors.UnknownSmartMethod:
1700
medium._remember_remote_is_before((1, 6))
1701
# Fallback for pre-1.6 servers: check for divergence
1702
# client-side, then do _set_last_revision.
1703
last_rev = revision.ensure_null(self.last_revision())
1705
graph = self.repository.get_graph()
1706
if self._check_if_descendant_or_diverged(
1707
stop_revision, last_rev, graph, other):
1708
# stop_revision is a descendant of last_rev, but we aren't
1709
# overwriting, so we're done.
1711
self._set_last_revision(stop_revision)
1716
def _extract_tar(tar, to_dir):
1717
"""Extract all the contents of a tarfile object.
1719
A replacement for extractall, which is not present in python2.4
1722
tar.extract(tarinfo, to_dir)
1725
def _translate_error(err, **context):
1726
"""Translate an ErrorFromSmartServer into a more useful error.
1728
Possible context keys:
1737
return context[name]
1738
except KeyError, keyErr:
1739
mutter('Missing key %r in context %r', keyErr.args[0], context)
1741
if err.error_verb == 'NoSuchRevision':
1742
raise NoSuchRevision(find('branch'), err.error_args[0])
1743
elif err.error_verb == 'nosuchrevision':
1744
raise NoSuchRevision(find('repository'), err.error_args[0])
1745
elif err.error_tuple == ('nobranch',):
1746
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1747
elif err.error_verb == 'norepository':
1748
raise errors.NoRepositoryPresent(find('bzrdir'))
1749
elif err.error_verb == 'LockContention':
1750
raise errors.LockContention('(remote lock)')
1751
elif err.error_verb == 'UnlockableTransport':
1752
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1753
elif err.error_verb == 'LockFailed':
1754
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1755
elif err.error_verb == 'TokenMismatch':
1756
raise errors.TokenMismatch(find('token'), '(remote token)')
1757
elif err.error_verb == 'Diverged':
1758
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1759
elif err.error_verb == 'TipChangeRejected':
1760
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))