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
# for fb in self._fallback_repositories:
604
# self._real_repository.add_fallback_repository(fb)
605
if self._lock_mode == 'w':
606
# if we are already locked, the real repository must be able to
607
# acquire the lock with our token.
608
self._real_repository.lock_write(self._lock_token)
609
elif self._lock_mode == 'r':
610
self._real_repository.lock_read()
612
def start_write_group(self):
613
"""Start a write group on the decorated repository.
615
Smart methods peform operations in a single step so this api
616
is not really applicable except as a compatibility thunk
617
for older plugins that don't use e.g. the CommitBuilder
621
return self._real_repository.start_write_group()
623
def _unlock(self, token):
624
path = self.bzrdir._path_for_remote_call(self._client)
626
# with no token the remote repository is not persistently locked.
629
response = self._client.call('Repository.unlock', path, token)
630
except errors.ErrorFromSmartServer, err:
631
self._translate_error(err, token=token)
632
if response == ('ok',):
635
raise errors.UnexpectedSmartServerResponse(response)
638
self._lock_count -= 1
639
if self._lock_count > 0:
641
self._parents_map = None
642
if 'hpss' in debug.debug_flags:
643
self._requested_parents = None
644
old_mode = self._lock_mode
645
self._lock_mode = None
647
# The real repository is responsible at present for raising an
648
# exception if it's in an unfinished write group. However, it
649
# normally will *not* actually remove the lock from disk - that's
650
# done by the server on receiving the Repository.unlock call.
651
# This is just to let the _real_repository stay up to date.
652
if self._real_repository is not None:
653
self._real_repository.unlock()
655
# The rpc-level lock should be released even if there was a
656
# problem releasing the vfs-based lock.
658
# Only write-locked repositories need to make a remote method
659
# call to perfom the unlock.
660
old_token = self._lock_token
661
self._lock_token = None
662
if not self._leave_lock:
663
self._unlock(old_token)
665
def break_lock(self):
666
# should hand off to the network
668
return self._real_repository.break_lock()
670
def _get_tarball(self, compression):
671
"""Return a TemporaryFile containing a repository tarball.
673
Returns None if the server does not support sending tarballs.
676
path = self.bzrdir._path_for_remote_call(self._client)
678
response, protocol = self._client.call_expecting_body(
679
'Repository.tarball', path, compression)
680
except errors.UnknownSmartMethod:
681
protocol.cancel_read_body()
683
if response[0] == 'ok':
684
# Extract the tarball and return it
685
t = tempfile.NamedTemporaryFile()
686
# TODO: rpc layer should read directly into it...
687
t.write(protocol.read_body_bytes())
690
raise errors.UnexpectedSmartServerResponse(response)
692
def sprout(self, to_bzrdir, revision_id=None):
693
# TODO: Option to control what format is created?
695
dest_repo = self._real_repository._format.initialize(to_bzrdir,
697
dest_repo.fetch(self, revision_id=revision_id)
700
### These methods are just thin shims to the VFS object for now.
702
def revision_tree(self, revision_id):
704
return self._real_repository.revision_tree(revision_id)
706
def get_serializer_format(self):
708
return self._real_repository.get_serializer_format()
710
def get_commit_builder(self, branch, parents, config, timestamp=None,
711
timezone=None, committer=None, revprops=None,
713
# FIXME: It ought to be possible to call this without immediately
714
# triggering _ensure_real. For now it's the easiest thing to do.
716
builder = self._real_repository.get_commit_builder(branch, parents,
717
config, timestamp=timestamp, timezone=timezone,
718
committer=committer, revprops=revprops, revision_id=revision_id)
721
def add_fallback_repository(self, repository):
722
"""Add a repository to use for looking up data not held locally.
724
:param repository: A repository.
726
if not self._format.supports_external_lookups:
727
raise errors.UnstackableRepositoryFormat(self._format, self.base)
728
# We need to accumulate additional repositories here, to pass them in
730
self._fallback_repositories.append(repository)
731
# They are also seen by the fallback repository. If it doesn't exist
732
# yet they'll be added then.
733
## if self._real_repository is not None:
734
## self._real_repository.add_fallback_repository(repository)
736
def add_inventory(self, revid, inv, parents):
738
return self._real_repository.add_inventory(revid, inv, parents)
740
def add_revision(self, rev_id, rev, inv=None, config=None):
742
return self._real_repository.add_revision(
743
rev_id, rev, inv=inv, config=config)
746
def get_inventory(self, revision_id):
748
return self._real_repository.get_inventory(revision_id)
750
def iter_inventories(self, revision_ids):
752
return self._real_repository.iter_inventories(revision_ids)
755
def get_revision(self, revision_id):
757
return self._real_repository.get_revision(revision_id)
759
def get_transaction(self):
761
return self._real_repository.get_transaction()
764
def clone(self, a_bzrdir, revision_id=None):
766
return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
768
def make_working_trees(self):
769
"""See Repository.make_working_trees"""
771
return self._real_repository.make_working_trees()
773
def revision_ids_to_search_result(self, result_set):
774
"""Convert a set of revision ids to a graph SearchResult."""
775
result_parents = set()
776
for parents in self.get_graph().get_parent_map(
777
result_set).itervalues():
778
result_parents.update(parents)
779
included_keys = result_set.intersection(result_parents)
780
start_keys = result_set.difference(included_keys)
781
exclude_keys = result_parents.difference(result_set)
782
result = graph.SearchResult(start_keys, exclude_keys,
783
len(result_set), result_set)
787
def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
788
"""Return the revision ids that other has that this does not.
790
These are returned in topological order.
792
revision_id: only return revision ids included by revision_id.
794
return repository.InterRepository.get(
795
other, self).search_missing_revision_ids(revision_id, find_ghosts)
797
def fetch(self, source, revision_id=None, pb=None):
798
if self.has_same_location(source):
799
# check that last_revision is in 'from' and then return a
801
if (revision_id is not None and
802
not revision.is_null(revision_id)):
803
self.get_revision(revision_id)
806
return self._real_repository.fetch(
807
source, revision_id=revision_id, pb=pb)
809
def create_bundle(self, target, base, fileobj, format=None):
811
self._real_repository.create_bundle(target, base, fileobj, format)
814
def get_ancestry(self, revision_id, topo_sorted=True):
816
return self._real_repository.get_ancestry(revision_id, topo_sorted)
818
def fileids_altered_by_revision_ids(self, revision_ids):
820
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
822
def _get_versioned_file_checker(self, revisions, revision_versions_cache):
824
return self._real_repository._get_versioned_file_checker(
825
revisions, revision_versions_cache)
827
def iter_files_bytes(self, desired_files):
828
"""See Repository.iter_file_bytes.
831
return self._real_repository.iter_files_bytes(desired_files)
834
def _fetch_order(self):
835
"""Decorate the real repository for now.
837
In the long term getting this back from the remote repository as part
838
of open would be more efficient.
841
return self._real_repository._fetch_order
844
def _fetch_uses_deltas(self):
845
"""Decorate the real repository for now.
847
In the long term getting this back from the remote repository as part
848
of open would be more efficient.
851
return self._real_repository._fetch_uses_deltas
854
def _fetch_reconcile(self):
855
"""Decorate the real repository for now.
857
In the long term getting this back from the remote repository as part
858
of open would be more efficient.
861
return self._real_repository._fetch_reconcile
863
def get_parent_map(self, keys):
864
"""See bzrlib.Graph.get_parent_map()."""
865
# Hack to build up the caching logic.
866
ancestry = self._parents_map
868
# Repository is not locked, so there's no cache.
869
missing_revisions = set(keys)
872
missing_revisions = set(key for key in keys if key not in ancestry)
873
if missing_revisions:
874
parent_map = self._get_parent_map(missing_revisions)
875
if 'hpss' in debug.debug_flags:
876
mutter('retransmitted revisions: %d of %d',
877
len(set(ancestry).intersection(parent_map)),
879
ancestry.update(parent_map)
880
present_keys = [k for k in keys if k in ancestry]
881
if 'hpss' in debug.debug_flags:
882
if self._requested_parents is not None and len(ancestry) != 0:
883
self._requested_parents.update(present_keys)
884
mutter('Current RemoteRepository graph hit rate: %d%%',
885
100.0 * len(self._requested_parents) / len(ancestry))
886
return dict((k, ancestry[k]) for k in present_keys)
888
def _get_parent_map(self, keys):
889
"""Helper for get_parent_map that performs the RPC."""
890
medium = self._client._medium
891
if medium._is_remote_before((1, 2)):
892
# We already found out that the server can't understand
893
# Repository.get_parent_map requests, so just fetch the whole
895
# XXX: Note that this will issue a deprecation warning. This is ok
896
# :- its because we're working with a deprecated server anyway, and
897
# the user will almost certainly have seen a warning about the
898
# server version already.
899
rg = self.get_revision_graph()
900
# There is an api discrepency between get_parent_map and
901
# get_revision_graph. Specifically, a "key:()" pair in
902
# get_revision_graph just means a node has no parents. For
903
# "get_parent_map" it means the node is a ghost. So fix up the
904
# graph to correct this.
905
# https://bugs.launchpad.net/bzr/+bug/214894
906
# There is one other "bug" which is that ghosts in
907
# get_revision_graph() are not returned at all. But we won't worry
908
# about that for now.
909
for node_id, parent_ids in rg.iteritems():
911
rg[node_id] = (NULL_REVISION,)
912
rg[NULL_REVISION] = ()
917
raise ValueError('get_parent_map(None) is not valid')
918
if NULL_REVISION in keys:
919
keys.discard(NULL_REVISION)
920
found_parents = {NULL_REVISION:()}
925
# TODO(Needs analysis): We could assume that the keys being requested
926
# from get_parent_map are in a breadth first search, so typically they
927
# will all be depth N from some common parent, and we don't have to
928
# have the server iterate from the root parent, but rather from the
929
# keys we're searching; and just tell the server the keyspace we
930
# already have; but this may be more traffic again.
932
# Transform self._parents_map into a search request recipe.
933
# TODO: Manage this incrementally to avoid covering the same path
934
# repeatedly. (The server will have to on each request, but the less
935
# work done the better).
936
parents_map = self._parents_map
937
if parents_map is None:
938
# Repository is not locked, so there's no cache.
940
start_set = set(parents_map)
941
result_parents = set()
942
for parents in parents_map.itervalues():
943
result_parents.update(parents)
944
stop_keys = result_parents.difference(start_set)
945
included_keys = start_set.intersection(result_parents)
946
start_set.difference_update(included_keys)
947
recipe = (start_set, stop_keys, len(parents_map))
948
body = self._serialise_search_recipe(recipe)
949
path = self.bzrdir._path_for_remote_call(self._client)
951
if type(key) is not str:
953
"key %r not a plain string" % (key,))
954
verb = 'Repository.get_parent_map'
955
args = (path,) + tuple(keys)
957
response = self._client.call_with_body_bytes_expecting_body(
958
verb, args, self._serialise_search_recipe(recipe))
959
except errors.UnknownSmartMethod:
960
# Server does not support this method, so get the whole graph.
961
# Worse, we have to force a disconnection, because the server now
962
# doesn't realise it has a body on the wire to consume, so the
963
# only way to recover is to abandon the connection.
965
'Server is too old for fast get_parent_map, reconnecting. '
966
'(Upgrade the server to Bazaar 1.2 to avoid this)')
968
# To avoid having to disconnect repeatedly, we keep track of the
969
# fact the server doesn't understand remote methods added in 1.2.
970
medium._remember_remote_is_before((1, 2))
971
return self.get_revision_graph(None)
972
response_tuple, response_handler = response
973
if response_tuple[0] not in ['ok']:
974
response_handler.cancel_read_body()
975
raise errors.UnexpectedSmartServerResponse(response_tuple)
976
if response_tuple[0] == 'ok':
977
coded = bz2.decompress(response_handler.read_body_bytes())
981
lines = coded.split('\n')
984
d = tuple(line.split())
986
revision_graph[d[0]] = d[1:]
988
# No parents - so give the Graph result (NULL_REVISION,).
989
revision_graph[d[0]] = (NULL_REVISION,)
990
return revision_graph
993
def get_signature_text(self, revision_id):
995
return self._real_repository.get_signature_text(revision_id)
998
@symbol_versioning.deprecated_method(symbol_versioning.one_three)
999
def get_revision_graph_with_ghosts(self, revision_ids=None):
1001
return self._real_repository.get_revision_graph_with_ghosts(
1002
revision_ids=revision_ids)
1005
def get_inventory_xml(self, revision_id):
1007
return self._real_repository.get_inventory_xml(revision_id)
1009
def deserialise_inventory(self, revision_id, xml):
1011
return self._real_repository.deserialise_inventory(revision_id, xml)
1013
def reconcile(self, other=None, thorough=False):
1015
return self._real_repository.reconcile(other=other, thorough=thorough)
1017
def all_revision_ids(self):
1019
return self._real_repository.all_revision_ids()
1022
def get_deltas_for_revisions(self, revisions):
1024
return self._real_repository.get_deltas_for_revisions(revisions)
1027
def get_revision_delta(self, revision_id):
1029
return self._real_repository.get_revision_delta(revision_id)
1032
def revision_trees(self, revision_ids):
1034
return self._real_repository.revision_trees(revision_ids)
1037
def get_revision_reconcile(self, revision_id):
1039
return self._real_repository.get_revision_reconcile(revision_id)
1042
def check(self, revision_ids=None):
1044
return self._real_repository.check(revision_ids=revision_ids)
1046
def copy_content_into(self, destination, revision_id=None):
1048
return self._real_repository.copy_content_into(
1049
destination, revision_id=revision_id)
1051
def _copy_repository_tarball(self, to_bzrdir, revision_id=None):
1052
# get a tarball of the remote repository, and copy from that into the
1054
from bzrlib import osutils
1056
# TODO: Maybe a progress bar while streaming the tarball?
1057
note("Copying repository content as tarball...")
1058
tar_file = self._get_tarball('bz2')
1059
if tar_file is None:
1061
destination = to_bzrdir.create_repository()
1063
tar = tarfile.open('repository', fileobj=tar_file,
1065
tmpdir = osutils.mkdtemp()
1067
_extract_tar(tar, tmpdir)
1068
tmp_bzrdir = BzrDir.open(tmpdir)
1069
tmp_repo = tmp_bzrdir.open_repository()
1070
tmp_repo.copy_content_into(destination, revision_id)
1072
osutils.rmtree(tmpdir)
1076
# TODO: Suggestion from john: using external tar is much faster than
1077
# python's tarfile library, but it may not work on windows.
1080
def inventories(self):
1081
"""Decorate the real repository for now.
1083
In the long term a full blown network facility is needed to
1084
avoid creating a real repository object locally.
1087
return self._real_repository.inventories
1091
"""Compress the data within the repository.
1093
This is not currently implemented within the smart server.
1096
return self._real_repository.pack()
1099
def revisions(self):
1100
"""Decorate the real repository for now.
1102
In the short term this should become a real object to intercept graph
1105
In the long term a full blown network facility is needed.
1108
return self._real_repository.revisions
1110
def set_make_working_trees(self, new_value):
1112
self._real_repository.set_make_working_trees(new_value)
1115
def signatures(self):
1116
"""Decorate the real repository for now.
1118
In the long term a full blown network facility is needed to avoid
1119
creating a real repository object locally.
1122
return self._real_repository.signatures
1125
def sign_revision(self, revision_id, gpg_strategy):
1127
return self._real_repository.sign_revision(revision_id, gpg_strategy)
1131
"""Decorate the real repository for now.
1133
In the long term a full blown network facility is needed to avoid
1134
creating a real repository object locally.
1137
return self._real_repository.texts
1140
def get_revisions(self, revision_ids):
1142
return self._real_repository.get_revisions(revision_ids)
1144
def supports_rich_root(self):
1146
return self._real_repository.supports_rich_root()
1148
def iter_reverse_revision_history(self, revision_id):
1150
return self._real_repository.iter_reverse_revision_history(revision_id)
1153
def _serializer(self):
1155
return self._real_repository._serializer
1157
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1159
return self._real_repository.store_revision_signature(
1160
gpg_strategy, plaintext, revision_id)
1162
def add_signature_text(self, revision_id, signature):
1164
return self._real_repository.add_signature_text(revision_id, signature)
1166
def has_signature_for_revision_id(self, revision_id):
1168
return self._real_repository.has_signature_for_revision_id(revision_id)
1170
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1172
return self._real_repository.item_keys_introduced_by(revision_ids,
1173
_files_pb=_files_pb)
1175
def revision_graph_can_have_wrong_parents(self):
1176
# The answer depends on the remote repo format.
1178
return self._real_repository.revision_graph_can_have_wrong_parents()
1180
def _find_inconsistent_revision_parents(self):
1182
return self._real_repository._find_inconsistent_revision_parents()
1184
def _check_for_inconsistent_revision_parents(self):
1186
return self._real_repository._check_for_inconsistent_revision_parents()
1188
def _make_parents_provider(self):
1191
def _serialise_search_recipe(self, recipe):
1192
"""Serialise a graph search recipe.
1194
:param recipe: A search recipe (start, stop, count).
1195
:return: Serialised bytes.
1197
start_keys = ' '.join(recipe[0])
1198
stop_keys = ' '.join(recipe[1])
1199
count = str(recipe[2])
1200
return '\n'.join((start_keys, stop_keys, count))
1203
class RemoteBranchLockableFiles(LockableFiles):
1204
"""A 'LockableFiles' implementation that talks to a smart server.
1206
This is not a public interface class.
1209
def __init__(self, bzrdir, _client):
1210
self.bzrdir = bzrdir
1211
self._client = _client
1212
self._need_find_modes = True
1213
LockableFiles.__init__(
1214
self, bzrdir.get_branch_transport(None),
1215
'lock', lockdir.LockDir)
1217
def _find_modes(self):
1218
# RemoteBranches don't let the client set the mode of control files.
1219
self._dir_mode = None
1220
self._file_mode = None
1223
class RemoteBranchFormat(branch.BranchFormat):
1225
def __eq__(self, other):
1226
return (isinstance(other, RemoteBranchFormat) and
1227
self.__dict__ == other.__dict__)
1229
def get_format_description(self):
1230
return 'Remote BZR Branch'
1232
def get_format_string(self):
1233
return 'Remote BZR Branch'
1235
def open(self, a_bzrdir):
1236
return a_bzrdir.open_branch()
1238
def initialize(self, a_bzrdir):
1239
return a_bzrdir.create_branch()
1241
def supports_tags(self):
1242
# Remote branches might support tags, but we won't know until we
1243
# access the real remote branch.
1247
class RemoteBranch(branch.Branch):
1248
"""Branch stored on a server accessed by HPSS RPC.
1250
At the moment most operations are mapped down to simple file operations.
1253
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1255
"""Create a RemoteBranch instance.
1257
:param real_branch: An optional local implementation of the branch
1258
format, usually accessing the data via the VFS.
1259
:param _client: Private parameter for testing.
1261
# We intentionally don't call the parent class's __init__, because it
1262
# will try to assign to self.tags, which is a property in this subclass.
1263
# And the parent's __init__ doesn't do much anyway.
1264
self._revision_id_to_revno_cache = None
1265
self._revision_history_cache = None
1266
self._last_revision_info_cache = None
1267
self.bzrdir = remote_bzrdir
1268
if _client is not None:
1269
self._client = _client
1271
self._client = remote_bzrdir._client
1272
self.repository = remote_repository
1273
if real_branch is not None:
1274
self._real_branch = real_branch
1275
# Give the remote repository the matching real repo.
1276
real_repo = self._real_branch.repository
1277
if isinstance(real_repo, RemoteRepository):
1278
real_repo._ensure_real()
1279
real_repo = real_repo._real_repository
1280
self.repository._set_real_repository(real_repo)
1281
# Give the branch the remote repository to let fast-pathing happen.
1282
self._real_branch.repository = self.repository
1284
self._real_branch = None
1285
# Fill out expected attributes of branch for bzrlib api users.
1286
self._format = RemoteBranchFormat()
1287
self.base = self.bzrdir.root_transport.base
1288
self._control_files = None
1289
self._lock_mode = None
1290
self._lock_token = None
1291
self._repo_lock_token = None
1292
self._lock_count = 0
1293
self._leave_lock = False
1294
## self._setup_stacking()
1296
def _setup_stacking(self):
1297
# configure stacking into the remote repository, by reading it from
1300
fallback_url = self.get_stacked_on_url()
1301
if fallback_url is None:
1303
# it's relative to this branch...
1304
fallback_url = urlutils.join(self.base, fallback_url)
1305
transports = [self.bzrdir.root_transport]
1306
if self._real_branch is not None:
1307
transports.append(self._real_branch._transport)
1308
fallback_bzrdir = BzrDir.open(fallback_url, transports)
1309
fallback_repo = fallback_bzrdir.open_repository()
1310
self.repository.add_fallback_repository(fallback_repo)
1311
except (errors.NotStacked, errors.UnstackableBranchFormat,
1312
errors.UnstackableRepositoryFormat), e:
1315
def _get_real_transport(self):
1316
# if we try vfs access, return the real branch's vfs transport
1318
return self._real_branch._transport
1320
_transport = property(_get_real_transport)
1323
return "%s(%s)" % (self.__class__.__name__, self.base)
1327
def _ensure_real(self):
1328
"""Ensure that there is a _real_branch set.
1330
Used before calls to self._real_branch.
1332
if self._real_branch is None:
1333
if not vfs.vfs_enabled():
1334
raise AssertionError('smart server vfs must be enabled '
1335
'to use vfs implementation')
1336
self.bzrdir._ensure_real()
1337
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1338
# Give the remote repository the matching real repo.
1339
real_repo = self._real_branch.repository
1340
if isinstance(real_repo, RemoteRepository):
1341
real_repo._ensure_real()
1342
real_repo = real_repo._real_repository
1343
self.repository._set_real_repository(real_repo)
1344
# Give the branch the remote repository to let fast-pathing happen.
1345
self._real_branch.repository = self.repository
1346
# XXX: deal with _lock_mode == 'w'
1347
if self._lock_mode == 'r':
1348
self._real_branch.lock_read()
1350
def _translate_error(self, err, **context):
1351
self.repository._translate_error(err, branch=self, **context)
1353
def _clear_cached_state(self):
1354
super(RemoteBranch, self)._clear_cached_state()
1355
if self._real_branch is not None:
1356
self._real_branch._clear_cached_state()
1358
def _clear_cached_state_of_remote_branch_only(self):
1359
"""Like _clear_cached_state, but doesn't clear the cache of
1362
This is useful when falling back to calling a method of
1363
self._real_branch that changes state. In that case the underlying
1364
branch changes, so we need to invalidate this RemoteBranch's cache of
1365
it. However, there's no need to invalidate the _real_branch's cache
1366
too, in fact doing so might harm performance.
1368
super(RemoteBranch, self)._clear_cached_state()
1371
def control_files(self):
1372
# Defer actually creating RemoteBranchLockableFiles until its needed,
1373
# because it triggers an _ensure_real that we otherwise might not need.
1374
if self._control_files is None:
1375
self._control_files = RemoteBranchLockableFiles(
1376
self.bzrdir, self._client)
1377
return self._control_files
1379
def _get_checkout_format(self):
1381
return self._real_branch._get_checkout_format()
1383
def get_physical_lock_status(self):
1384
"""See Branch.get_physical_lock_status()."""
1385
# should be an API call to the server, as branches must be lockable.
1387
return self._real_branch.get_physical_lock_status()
1389
def get_stacked_on_url(self):
1390
"""Get the URL this branch is stacked against.
1392
:raises NotStacked: If the branch is not stacked.
1393
:raises UnstackableBranchFormat: If the branch does not support
1395
:raises UnstackableRepositoryFormat: If the repository does not support
1400
return self._real_branch.get_stacked_on_url()
1403
response = self._client.call('Branch.get_stacked_on_url',
1404
self._remote_path())
1405
except errors.ErrorFromSmartServer, err:
1406
self._translate_error(err)
1407
if response[0] != 'ok':
1408
raise errors.UnexpectedSmartServerResponse(response)
1411
def lock_read(self):
1412
if not self._lock_mode:
1413
self._lock_mode = 'r'
1414
self._lock_count = 1
1415
if self._real_branch is not None:
1416
self._real_branch.lock_read()
1418
self._lock_count += 1
1420
def _remote_lock_write(self, token):
1422
branch_token = repo_token = ''
1424
branch_token = token
1425
repo_token = self.repository.lock_write()
1426
self.repository.unlock()
1428
response = self._client.call(
1429
'Branch.lock_write', self._remote_path(),
1430
branch_token, repo_token or '')
1431
except errors.ErrorFromSmartServer, err:
1432
self._translate_error(err, token=token)
1433
if response[0] != 'ok':
1434
raise errors.UnexpectedSmartServerResponse(response)
1435
ok, branch_token, repo_token = response
1436
return branch_token, repo_token
1438
def lock_write(self, token=None):
1439
if not self._lock_mode:
1440
remote_tokens = self._remote_lock_write(token)
1441
self._lock_token, self._repo_lock_token = remote_tokens
1442
if not self._lock_token:
1443
raise SmartProtocolError('Remote server did not return a token!')
1444
# TODO: We really, really, really don't want to call _ensure_real
1445
# here, but it's the easiest way to ensure coherency between the
1446
# state of the RemoteBranch and RemoteRepository objects and the
1447
# physical locks. If we don't materialise the real objects here,
1448
# then getting everything in the right state later is complex, so
1449
# for now we just do it the lazy way.
1450
# -- Andrew Bennetts, 2007-02-22.
1452
if self._real_branch is not None:
1453
self._real_branch.repository.lock_write(
1454
token=self._repo_lock_token)
1456
self._real_branch.lock_write(token=self._lock_token)
1458
self._real_branch.repository.unlock()
1459
if token is not None:
1460
self._leave_lock = True
1462
# XXX: this case seems to be unreachable; token cannot be None.
1463
self._leave_lock = False
1464
self._lock_mode = 'w'
1465
self._lock_count = 1
1466
elif self._lock_mode == 'r':
1467
raise errors.ReadOnlyTransaction
1469
if token is not None:
1470
# A token was given to lock_write, and we're relocking, so check
1471
# that the given token actually matches the one we already have.
1472
if token != self._lock_token:
1473
raise errors.TokenMismatch(token, self._lock_token)
1474
self._lock_count += 1
1475
return self._lock_token or None
1477
def _unlock(self, branch_token, repo_token):
1479
response = self._client.call('Branch.unlock', self._remote_path(), branch_token,
1481
except errors.ErrorFromSmartServer, err:
1482
self._translate_error(err, token=str((branch_token, repo_token)))
1483
if response == ('ok',):
1485
raise errors.UnexpectedSmartServerResponse(response)
1488
self._lock_count -= 1
1489
if not self._lock_count:
1490
self._clear_cached_state()
1491
mode = self._lock_mode
1492
self._lock_mode = None
1493
if self._real_branch is not None:
1494
if (not self._leave_lock and mode == 'w' and
1495
self._repo_lock_token):
1496
# If this RemoteBranch will remove the physical lock for the
1497
# repository, make sure the _real_branch doesn't do it
1498
# first. (Because the _real_branch's repository is set to
1499
# be the RemoteRepository.)
1500
self._real_branch.repository.leave_lock_in_place()
1501
self._real_branch.unlock()
1503
# Only write-locked branched need to make a remote method call
1504
# to perfom the unlock.
1506
if not self._lock_token:
1507
raise AssertionError('Locked, but no token!')
1508
branch_token = self._lock_token
1509
repo_token = self._repo_lock_token
1510
self._lock_token = None
1511
self._repo_lock_token = None
1512
if not self._leave_lock:
1513
self._unlock(branch_token, repo_token)
1515
def break_lock(self):
1517
return self._real_branch.break_lock()
1519
def leave_lock_in_place(self):
1520
if not self._lock_token:
1521
raise NotImplementedError(self.leave_lock_in_place)
1522
self._leave_lock = True
1524
def dont_leave_lock_in_place(self):
1525
if not self._lock_token:
1526
raise NotImplementedError(self.dont_leave_lock_in_place)
1527
self._leave_lock = False
1529
def _last_revision_info(self):
1530
response = self._client.call('Branch.last_revision_info', self._remote_path())
1531
if response[0] != 'ok':
1532
raise SmartProtocolError('unexpected response code %s' % (response,))
1533
revno = int(response[1])
1534
last_revision = response[2]
1535
return (revno, last_revision)
1537
def _gen_revision_history(self):
1538
"""See Branch._gen_revision_history()."""
1539
response_tuple, response_handler = self._client.call_expecting_body(
1540
'Branch.revision_history', self._remote_path())
1541
if response_tuple[0] != 'ok':
1542
raise errors.UnexpectedSmartServerResponse(response_tuple)
1543
result = response_handler.read_body_bytes().split('\x00')
1548
def _remote_path(self):
1549
return self.bzrdir._path_for_remote_call(self._client)
1551
def _set_last_revision_descendant(self, revision_id, other_branch,
1552
allow_diverged=False, allow_overwrite_descendant=False):
1554
response = self._client.call('Branch.set_last_revision_ex',
1555
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id,
1556
int(allow_diverged), int(allow_overwrite_descendant))
1557
except errors.ErrorFromSmartServer, err:
1558
self._translate_error(err, other_branch=other_branch)
1559
self._clear_cached_state()
1560
if len(response) != 3 and response[0] != 'ok':
1561
raise errors.UnexpectedSmartServerResponse(response)
1562
new_revno, new_revision_id = response[1:]
1563
self._last_revision_info_cache = new_revno, new_revision_id
1564
self._real_branch._last_revision_info_cache = new_revno, new_revision_id
1566
def _set_last_revision(self, revision_id):
1567
self._clear_cached_state()
1569
response = self._client.call('Branch.set_last_revision',
1570
self._remote_path(), self._lock_token, self._repo_lock_token, revision_id)
1571
except errors.ErrorFromSmartServer, err:
1572
self._translate_error(err)
1573
if response != ('ok',):
1574
raise errors.UnexpectedSmartServerResponse(response)
1577
def set_revision_history(self, rev_history):
1578
# Send just the tip revision of the history; the server will generate
1579
# the full history from that. If the revision doesn't exist in this
1580
# branch, NoSuchRevision will be raised.
1581
if rev_history == []:
1584
rev_id = rev_history[-1]
1585
self._set_last_revision(rev_id)
1586
self._cache_revision_history(rev_history)
1588
def get_parent(self):
1590
return self._real_branch.get_parent()
1592
def set_parent(self, url):
1594
return self._real_branch.set_parent(url)
1596
def set_stacked_on_url(self, stacked_location):
1597
"""Set the URL this branch is stacked against.
1599
:raises UnstackableBranchFormat: If the branch does not support
1601
:raises UnstackableRepositoryFormat: If the repository does not support
1605
return self._real_branch.set_stacked_on_url(stacked_location)
1607
def sprout(self, to_bzrdir, revision_id=None):
1608
# Like Branch.sprout, except that it sprouts a branch in the default
1609
# format, because RemoteBranches can't be created at arbitrary URLs.
1610
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1611
# to_bzrdir.create_branch...
1613
result = self._real_branch._format.initialize(to_bzrdir)
1614
self.copy_content_into(result, revision_id=revision_id)
1615
result.set_parent(self.bzrdir.root_transport.base)
1619
def pull(self, source, overwrite=False, stop_revision=None,
1621
self._clear_cached_state_of_remote_branch_only()
1623
return self._real_branch.pull(
1624
source, overwrite=overwrite, stop_revision=stop_revision,
1625
_override_hook_target=self, **kwargs)
1628
def push(self, target, overwrite=False, stop_revision=None):
1630
return self._real_branch.push(
1631
target, overwrite=overwrite, stop_revision=stop_revision,
1632
_override_hook_source_branch=self)
1634
def is_locked(self):
1635
return self._lock_count >= 1
1638
def revision_id_to_revno(self, revision_id):
1640
return self._real_branch.revision_id_to_revno(revision_id)
1643
def set_last_revision_info(self, revno, revision_id):
1644
revision_id = ensure_null(revision_id)
1646
response = self._client.call('Branch.set_last_revision_info',
1647
self._remote_path(), self._lock_token, self._repo_lock_token, str(revno), revision_id)
1648
except errors.UnknownSmartMethod:
1650
self._clear_cached_state_of_remote_branch_only()
1651
self._real_branch.set_last_revision_info(revno, revision_id)
1652
self._last_revision_info_cache = revno, revision_id
1654
except errors.ErrorFromSmartServer, err:
1655
self._translate_error(err)
1656
if response == ('ok',):
1657
self._clear_cached_state()
1658
self._last_revision_info_cache = revno, revision_id
1659
# Update the _real_branch's cache too.
1660
if self._real_branch is not None:
1661
cache = self._last_revision_info_cache
1662
self._real_branch._last_revision_info_cache = cache
1664
raise errors.UnexpectedSmartServerResponse(response)
1667
def generate_revision_history(self, revision_id, last_rev=None,
1669
medium = self._client._medium
1670
if not medium._is_remote_before((1, 6)):
1672
self._set_last_revision_descendant(revision_id, other_branch,
1673
allow_diverged=True, allow_overwrite_descendant=True)
1675
except errors.UnknownSmartMethod:
1676
medium._remember_remote_is_before((1, 6))
1677
self._clear_cached_state_of_remote_branch_only()
1679
self._real_branch.generate_revision_history(
1680
revision_id, last_rev=last_rev, other_branch=other_branch)
1685
return self._real_branch.tags
1687
def set_push_location(self, location):
1689
return self._real_branch.set_push_location(location)
1692
def update_revisions(self, other, stop_revision=None, overwrite=False,
1694
"""See Branch.update_revisions."""
1697
if stop_revision is None:
1698
stop_revision = other.last_revision()
1699
if revision.is_null(stop_revision):
1700
# if there are no commits, we're done.
1702
self.fetch(other, stop_revision)
1705
# Just unconditionally set the new revision. We don't care if
1706
# the branches have diverged.
1707
self._set_last_revision(stop_revision)
1709
medium = self._client._medium
1710
if not medium._is_remote_before((1, 6)):
1712
self._set_last_revision_descendant(stop_revision, other)
1714
except errors.UnknownSmartMethod:
1715
medium._remember_remote_is_before((1, 6))
1716
# Fallback for pre-1.6 servers: check for divergence
1717
# client-side, then do _set_last_revision.
1718
last_rev = revision.ensure_null(self.last_revision())
1720
graph = self.repository.get_graph()
1721
if self._check_if_descendant_or_diverged(
1722
stop_revision, last_rev, graph, other):
1723
# stop_revision is a descendant of last_rev, but we aren't
1724
# overwriting, so we're done.
1726
self._set_last_revision(stop_revision)
1731
def _extract_tar(tar, to_dir):
1732
"""Extract all the contents of a tarfile object.
1734
A replacement for extractall, which is not present in python2.4
1737
tar.extract(tarinfo, to_dir)
1740
def _translate_error(err, **context):
1741
"""Translate an ErrorFromSmartServer into a more useful error.
1743
Possible context keys:
1752
return context[name]
1753
except KeyError, keyErr:
1754
mutter('Missing key %r in context %r', keyErr.args[0], context)
1756
if err.error_verb == 'NoSuchRevision':
1757
raise NoSuchRevision(find('branch'), err.error_args[0])
1758
elif err.error_verb == 'nosuchrevision':
1759
raise NoSuchRevision(find('repository'), err.error_args[0])
1760
elif err.error_tuple == ('nobranch',):
1761
raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
1762
elif err.error_verb == 'norepository':
1763
raise errors.NoRepositoryPresent(find('bzrdir'))
1764
elif err.error_verb == 'LockContention':
1765
raise errors.LockContention('(remote lock)')
1766
elif err.error_verb == 'UnlockableTransport':
1767
raise errors.UnlockableTransport(find('bzrdir').root_transport)
1768
elif err.error_verb == 'LockFailed':
1769
raise errors.LockFailed(err.error_args[0], err.error_args[1])
1770
elif err.error_verb == 'TokenMismatch':
1771
raise errors.TokenMismatch(find('token'), '(remote token)')
1772
elif err.error_verb == 'Diverged':
1773
raise errors.DivergedBranches(find('branch'), find('other_branch'))
1774
elif err.error_verb == 'TipChangeRejected':
1775
raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
1776
elif err.error_verb == 'UnstackableBranchFormat':
1777
raise errors.UnstackableBranchFormat(*err.error_args)
1778
elif err.error_verb == 'UnstackableRepositoryFormat':
1779
raise errors.UnstackableRepositoryFormat(*err.error_args)
1780
elif err.error_verb == 'NotStacked':
1781
raise errors.NotStacked(branch=find('branch'))