1
# Copyright (C) 2006, 2007 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.
20
from cStringIO import StringIO
22
from bzrlib import branch, errors, lockdir, repository
23
from bzrlib.branch import BranchReferenceFormat
24
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
25
from bzrlib.config import BranchConfig, TreeConfig
26
from bzrlib.decorators import needs_read_lock, needs_write_lock
27
from bzrlib.errors import NoSuchRevision
28
from bzrlib.lockable_files import LockableFiles
29
from bzrlib.revision import NULL_REVISION
30
from bzrlib.smart import client, vfs
31
from bzrlib.trace import note
33
# Note: RemoteBzrDirFormat is in bzrdir.py
35
class RemoteBzrDir(BzrDir):
36
"""Control directory on a remote server, accessed via bzr:// or similar."""
38
def __init__(self, transport, _client=None):
39
"""Construct a RemoteBzrDir.
41
:param _client: Private parameter for testing. Disables probing and the
44
BzrDir.__init__(self, transport, RemoteBzrDirFormat())
45
# this object holds a delegated bzrdir that uses file-level operations
46
# to talk to the other side
47
self._real_bzrdir = None
50
self._medium = transport.get_smart_client()
51
self._client = client._SmartClient(self._medium)
53
self._client = _client
57
path = self._path_for_remote_call(self._client)
58
response = self._client.call('BzrDir.open', path)
59
if response not in [('yes',), ('no',)]:
60
raise errors.UnexpectedSmartServerResponse(response)
61
if response == ('no',):
62
raise errors.NotBranchError(path=transport.base)
64
def _ensure_real(self):
65
"""Ensure that there is a _real_bzrdir set.
67
Used before calls to self._real_bzrdir.
69
if not self._real_bzrdir:
70
self._real_bzrdir = BzrDir.open_from_transport(
71
self.root_transport, _server_formats=False)
73
def create_repository(self, shared=False):
75
self._real_bzrdir.create_repository(shared=shared)
76
return self.open_repository()
78
def create_branch(self):
80
real_branch = self._real_bzrdir.create_branch()
81
return RemoteBranch(self, self.find_repository(), real_branch)
83
def create_workingtree(self, revision_id=None):
84
raise errors.NotLocalUrl(self.transport.base)
86
def find_branch_format(self):
87
"""Find the branch 'format' for this bzrdir.
89
This might be a synthetic object for e.g. RemoteBranch and SVN.
91
b = self.open_branch()
94
def get_branch_reference(self):
95
"""See BzrDir.get_branch_reference()."""
96
path = self._path_for_remote_call(self._client)
97
response = self._client.call('BzrDir.open_branch', path)
98
if response[0] == 'ok':
100
# branch at this location.
103
# a branch reference, use the existing BranchReference logic.
105
elif response == ('nobranch',):
106
raise errors.NotBranchError(path=self.root_transport.base)
108
assert False, 'unexpected response code %r' % (response,)
110
def open_branch(self, _unsupported=False):
111
assert _unsupported == False, 'unsupported flag support not implemented yet.'
112
reference_url = self.get_branch_reference()
113
if reference_url is None:
114
# branch at this location.
115
return RemoteBranch(self, self.find_repository())
117
# a branch reference, use the existing BranchReference logic.
118
format = BranchReferenceFormat()
119
return format.open(self, _found=True, location=reference_url)
121
def open_repository(self):
122
path = self._path_for_remote_call(self._client)
123
response = self._client.call('BzrDir.find_repository', path)
124
assert response[0] in ('ok', 'norepository'), \
125
'unexpected response code %s' % (response,)
126
if response[0] == 'norepository':
127
raise errors.NoRepositoryPresent(self)
128
assert len(response) == 4, 'incorrect response length %s' % (response,)
129
if response[1] == '':
130
format = RemoteRepositoryFormat()
131
format.rich_root_data = (response[2] == 'yes')
132
format.supports_tree_reference = (response[3] == 'yes')
133
return RemoteRepository(self, format)
135
raise errors.NoRepositoryPresent(self)
137
def open_workingtree(self, recommend_upgrade=True):
139
if self._real_bzrdir.has_workingtree():
140
raise errors.NotLocalUrl(self.root_transport)
142
raise errors.NoWorkingTree(self.root_transport.base)
144
def _path_for_remote_call(self, client):
145
"""Return the path to be used for this bzrdir in a remote call."""
146
return client.remote_path_from_transport(self.root_transport)
148
def get_branch_transport(self, branch_format):
150
return self._real_bzrdir.get_branch_transport(branch_format)
152
def get_repository_transport(self, repository_format):
154
return self._real_bzrdir.get_repository_transport(repository_format)
156
def get_workingtree_transport(self, workingtree_format):
158
return self._real_bzrdir.get_workingtree_transport(workingtree_format)
160
def can_convert_format(self):
161
"""Upgrading of remote bzrdirs is not supported yet."""
164
def needs_format_conversion(self, format=None):
165
"""Upgrading of remote bzrdirs is not supported yet."""
168
def clone(self, url, revision_id=None, force_new_repo=False):
170
return self._real_bzrdir.clone(url, revision_id=revision_id,
171
force_new_repo=force_new_repo)
174
class RemoteRepositoryFormat(repository.RepositoryFormat):
175
"""Format for repositories accessed over a _SmartClient.
177
Instances of this repository are represented by RemoteRepository
180
The RemoteRepositoryFormat is parameterised during construction
181
to reflect the capabilities of the real, remote format. Specifically
182
the attributes rich_root_data and supports_tree_reference are set
183
on a per instance basis, and are not set (and should not be) at
187
_matchingbzrdir = RemoteBzrDirFormat
189
def initialize(self, a_bzrdir, shared=False):
190
assert isinstance(a_bzrdir, RemoteBzrDir), \
191
'%r is not a RemoteBzrDir' % (a_bzrdir,)
192
return a_bzrdir.create_repository(shared=shared)
194
def open(self, a_bzrdir):
195
assert isinstance(a_bzrdir, RemoteBzrDir)
196
return a_bzrdir.open_repository()
198
def get_format_description(self):
199
return 'bzr remote repository'
201
def __eq__(self, other):
202
return self.__class__ == other.__class__
204
def check_conversion_target(self, target_format):
205
if self.rich_root_data and not target_format.rich_root_data:
206
raise errors.BadConversionTarget(
207
'Does not support rich root data.', target_format)
208
if (self.supports_tree_reference and
209
not getattr(target_format, 'supports_tree_reference', False)):
210
raise errors.BadConversionTarget(
211
'Does not support nested trees', target_format)
214
class RemoteRepository(object):
215
"""Repository accessed over rpc.
217
For the moment most operations are performed using local transport-backed
221
def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
222
"""Create a RemoteRepository instance.
224
:param remote_bzrdir: The bzrdir hosting this repository.
225
:param format: The RemoteFormat object to use.
226
:param real_repository: If not None, a local implementation of the
227
repository logic for the repository, usually accessing the data
229
:param _client: Private testing parameter - override the smart client
230
to be used by the repository.
233
self._real_repository = real_repository
235
self._real_repository = None
236
self.bzrdir = remote_bzrdir
238
self._client = client._SmartClient(self.bzrdir._medium)
240
self._client = _client
241
self._format = format
242
self._lock_mode = None
243
self._lock_token = None
245
self._leave_lock = False
247
def _ensure_real(self):
248
"""Ensure that there is a _real_repository set.
250
Used before calls to self._real_repository.
252
if not self._real_repository:
253
self.bzrdir._ensure_real()
254
#self._real_repository = self.bzrdir._real_bzrdir.open_repository()
255
self._set_real_repository(self.bzrdir._real_bzrdir.open_repository())
257
def get_revision_graph(self, revision_id=None):
258
"""See Repository.get_revision_graph()."""
259
if revision_id is None:
261
elif revision_id == NULL_REVISION:
264
path = self.bzrdir._path_for_remote_call(self._client)
265
assert type(revision_id) is str
266
response = self._client.call_expecting_body(
267
'Repository.get_revision_graph', path, revision_id)
268
if response[0][0] not in ['ok', 'nosuchrevision']:
269
raise errors.UnexpectedSmartServerResponse(response[0])
270
if response[0][0] == 'ok':
271
coded = response[1].read_body_bytes()
273
# no revisions in this repository!
275
lines = coded.split('\n')
278
d = list(line.split())
279
revision_graph[d[0]] = d[1:]
281
return revision_graph
283
response_body = response[1].read_body_bytes()
284
assert response_body == ''
285
raise NoSuchRevision(self, revision_id)
287
def has_revision(self, revision_id):
288
"""See Repository.has_revision()."""
289
if revision_id is None:
290
# The null revision is always present.
292
path = self.bzrdir._path_for_remote_call(self._client)
293
response = self._client.call('Repository.has_revision', path, revision_id)
294
assert response[0] in ('yes', 'no'), 'unexpected response code %s' % (response,)
295
return response[0] == 'yes'
297
def gather_stats(self, revid=None, committers=None):
298
"""See Repository.gather_stats()."""
299
path = self.bzrdir._path_for_remote_call(self._client)
300
if revid in (None, NULL_REVISION):
304
if committers is None or not committers:
305
fmt_committers = 'no'
307
fmt_committers = 'yes'
308
response = self._client.call_expecting_body(
309
'Repository.gather_stats', path, fmt_revid, fmt_committers)
310
assert response[0][0] == 'ok', \
311
'unexpected response code %s' % (response[0],)
313
body = response[1].read_body_bytes()
315
for line in body.split('\n'):
318
key, val_text = line.split(':')
319
if key in ('revisions', 'size', 'committers'):
320
result[key] = int(val_text)
321
elif key in ('firstrev', 'latestrev'):
322
values = val_text.split(' ')[1:]
323
result[key] = (float(values[0]), long(values[1]))
327
def get_physical_lock_status(self):
328
"""See Repository.get_physical_lock_status()."""
332
"""See Repository.is_shared()."""
333
path = self.bzrdir._path_for_remote_call(self._client)
334
response = self._client.call('Repository.is_shared', path)
335
assert response[0] in ('yes', 'no'), 'unexpected response code %s' % (response,)
336
return response[0] == 'yes'
339
# wrong eventually - want a local lock cache context
340
if not self._lock_mode:
341
self._lock_mode = 'r'
343
if self._real_repository is not None:
344
self._real_repository.lock_read()
346
self._lock_count += 1
348
def _remote_lock_write(self, token):
349
path = self.bzrdir._path_for_remote_call(self._client)
352
response = self._client.call('Repository.lock_write', path, token)
353
if response[0] == 'ok':
356
elif response[0] == 'LockContention':
357
raise errors.LockContention('(remote lock)')
358
elif response[0] == 'UnlockableTransport':
359
raise errors.UnlockableTransport(self.bzrdir.root_transport)
361
assert False, 'unexpected response code %s' % (response,)
363
def lock_write(self, token=None):
364
if not self._lock_mode:
365
self._lock_token = self._remote_lock_write(token)
366
assert self._lock_token, 'Remote server did not return a token!'
367
if self._real_repository is not None:
368
self._real_repository.lock_write(token=self._lock_token)
369
if token is not None:
370
self._leave_lock = True
372
self._leave_lock = False
373
self._lock_mode = 'w'
375
elif self._lock_mode == 'r':
376
raise errors.ReadOnlyError(self)
378
self._lock_count += 1
379
return self._lock_token
381
def leave_lock_in_place(self):
382
self._leave_lock = True
384
def dont_leave_lock_in_place(self):
385
self._leave_lock = False
387
def _set_real_repository(self, repository):
388
"""Set the _real_repository for this repository.
390
:param repository: The repository to fallback to for non-hpss
391
implemented operations.
393
assert not isinstance(repository, RemoteRepository)
394
self._real_repository = repository
395
if self._lock_mode == 'w':
396
# if we are already locked, the real repository must be able to
397
# acquire the lock with our token.
398
self._real_repository.lock_write(self._lock_token)
399
elif self._lock_mode == 'r':
400
self._real_repository.lock_read()
402
def _unlock(self, token):
403
path = self.bzrdir._path_for_remote_call(self._client)
404
response = self._client.call('Repository.unlock', path, token)
405
if response == ('ok',):
407
elif response[0] == 'TokenMismatch':
408
raise errors.TokenMismatch(token, '(remote token)')
410
assert False, 'unexpected response code %s' % (response,)
413
self._lock_count -= 1
414
if not self._lock_count:
415
mode = self._lock_mode
416
self._lock_mode = None
417
if self._real_repository is not None:
418
self._real_repository.unlock()
420
# Only write-locked repositories need to make a remote method
421
# call to perfom the unlock.
423
assert self._lock_token, 'Locked, but no token!'
424
token = self._lock_token
425
self._lock_token = None
426
if not self._leave_lock:
429
def break_lock(self):
430
# should hand off to the network
432
return self._real_repository.break_lock()
434
def _get_tarball(self, compression):
435
"""Return a TemporaryFile containing a repository tarball"""
437
path = self.bzrdir._path_for_remote_call(self._client)
438
response, protocol = self._client.call_expecting_body(
439
'Repository.tarball', path, compression)
440
assert response[0] in ('ok', 'failure'), \
441
'unexpected response code %s' % (response,)
442
if response[0] == 'ok':
443
# Extract the tarball and return it
444
t = tempfile.NamedTemporaryFile()
445
# TODO: rpc layer should read directly into it...
446
t.write(protocol.read_body_bytes())
450
raise errors.SmartServerError(error_code=response)
452
def sprout(self, to_bzrdir, revision_id=None):
453
# TODO: Option to control what format is created?
454
to_repo = to_bzrdir.create_repository()
455
self._copy_repository_tarball(to_repo, revision_id)
458
### These methods are just thin shims to the VFS object for now.
460
def revision_tree(self, revision_id):
462
return self._real_repository.revision_tree(revision_id)
464
def get_commit_builder(self, branch, parents, config, timestamp=None,
465
timezone=None, committer=None, revprops=None,
467
# FIXME: It ought to be possible to call this without immediately
468
# triggering _ensure_real. For now it's the easiest thing to do.
470
builder = self._real_repository.get_commit_builder(branch, parents,
471
config, timestamp=timestamp, timezone=timezone,
472
committer=committer, revprops=revprops, revision_id=revision_id)
473
# Make the builder use this RemoteRepository rather than the real one.
474
builder.repository = self
478
def add_inventory(self, revid, inv, parents):
480
return self._real_repository.add_inventory(revid, inv, parents)
483
def add_revision(self, rev_id, rev, inv=None, config=None):
485
return self._real_repository.add_revision(
486
rev_id, rev, inv=inv, config=config)
489
def get_inventory(self, revision_id):
491
return self._real_repository.get_inventory(revision_id)
494
def get_revision(self, revision_id):
496
return self._real_repository.get_revision(revision_id)
499
def weave_store(self):
501
return self._real_repository.weave_store
503
def get_transaction(self):
505
return self._real_repository.get_transaction()
508
def clone(self, a_bzrdir, revision_id=None):
510
return self._real_repository.clone(a_bzrdir, revision_id=revision_id)
512
def make_working_trees(self):
513
"""RemoteRepositories never create working trees by default."""
516
def fetch(self, source, revision_id=None, pb=None):
518
return self._real_repository.fetch(
519
source, revision_id=revision_id, pb=pb)
522
def control_weaves(self):
524
return self._real_repository.control_weaves
527
def get_ancestry(self, revision_id):
529
return self._real_repository.get_ancestry(revision_id)
532
def get_inventory_weave(self):
534
return self._real_repository.get_inventory_weave()
536
def fileids_altered_by_revision_ids(self, revision_ids):
538
return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
541
def get_signature_text(self, revision_id):
543
return self._real_repository.get_signature_text(revision_id)
546
def get_revision_graph_with_ghosts(self, revision_ids=None):
548
return self._real_repository.get_revision_graph_with_ghosts(
549
revision_ids=revision_ids)
552
def get_inventory_xml(self, revision_id):
554
return self._real_repository.get_inventory_xml(revision_id)
556
def deserialise_inventory(self, revision_id, xml):
558
return self._real_repository.deserialise_inventory(revision_id, xml)
560
def reconcile(self, other=None, thorough=False):
562
return self._real_repository.reconcile(other=other, thorough=thorough)
564
def all_revision_ids(self):
566
return self._real_repository.all_revision_ids()
569
def get_deltas_for_revisions(self, revisions):
571
return self._real_repository.get_deltas_for_revisions(revisions)
574
def get_revision_delta(self, revision_id):
576
return self._real_repository.get_revision_delta(revision_id)
579
def revision_trees(self, revision_ids):
581
return self._real_repository.revision_trees(revision_ids)
584
def get_revision_reconcile(self, revision_id):
586
return self._real_repository.get_revision_reconcile(revision_id)
589
def check(self, revision_ids):
591
return self._real_repository.check(revision_ids)
593
def copy_content_into(self, destination, revision_id=None):
595
return self._real_repository.copy_content_into(
596
destination, revision_id=revision_id)
598
def _copy_repository_tarball(self, destination, revision_id=None):
599
# get a tarball of the remote repository, and copy from that into the
601
from bzrlib import osutils
604
from StringIO import StringIO
605
# TODO: Maybe a progress bar while streaming the tarball?
606
note("Copying repository content as tarball...")
607
tar_file = self._get_tarball('bz2')
609
tar = tarfile.open('repository', fileobj=tar_file,
611
tmpdir = tempfile.mkdtemp()
613
_extract_tar(tar, tmpdir)
614
tmp_bzrdir = BzrDir.open(tmpdir)
615
tmp_repo = tmp_bzrdir.open_repository()
616
tmp_repo.copy_content_into(destination, revision_id)
618
osutils.rmtree(tmpdir)
621
# TODO: if the server doesn't support this operation, maybe do it the
622
# slow way using the _real_repository?
624
# TODO: Suggestion from john: using external tar is much faster than
625
# python's tarfile library, but it may not work on windows.
627
def set_make_working_trees(self, new_value):
628
raise NotImplementedError(self.set_make_working_trees)
631
def sign_revision(self, revision_id, gpg_strategy):
633
return self._real_repository.sign_revision(revision_id, gpg_strategy)
636
def get_revisions(self, revision_ids):
638
return self._real_repository.get_revisions(revision_ids)
640
def supports_rich_root(self):
642
return self._real_repository.supports_rich_root()
644
def iter_reverse_revision_history(self, revision_id):
646
return self._real_repository.iter_reverse_revision_history(revision_id)
649
def _serializer(self):
651
return self._real_repository._serializer
653
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
655
return self._real_repository.store_revision_signature(
656
gpg_strategy, plaintext, revision_id)
658
def has_signature_for_revision_id(self, revision_id):
660
return self._real_repository.has_signature_for_revision_id(revision_id)
663
class RemoteBranchLockableFiles(LockableFiles):
664
"""A 'LockableFiles' implementation that talks to a smart server.
666
This is not a public interface class.
669
def __init__(self, bzrdir, _client):
671
self._client = _client
672
self._need_find_modes = True
673
LockableFiles.__init__(
674
self, bzrdir.get_branch_transport(None),
675
'lock', lockdir.LockDir)
677
def _find_modes(self):
678
# RemoteBranches don't let the client set the mode of control files.
679
self._dir_mode = None
680
self._file_mode = None
683
"""'get' a remote path as per the LockableFiles interface.
685
:param path: the file to 'get'. If this is 'branch.conf', we do not
686
just retrieve a file, instead we ask the smart server to generate
687
a configuration for us - which is retrieved as an INI file.
689
if path == 'branch.conf':
690
path = self.bzrdir._path_for_remote_call(self._client)
691
response = self._client.call_expecting_body(
692
'Branch.get_config_file', path)
693
assert response[0][0] == 'ok', \
694
'unexpected response code %s' % (response[0],)
695
return StringIO(response[1].read_body_bytes())
698
return LockableFiles.get(self, path)
701
class RemoteBranchFormat(branch.BranchFormat):
703
def __eq__(self, other):
704
return (isinstance(other, RemoteBranchFormat) and
705
self.__dict__ == other.__dict__)
707
def get_format_description(self):
708
return 'Remote BZR Branch'
710
def get_format_string(self):
711
return 'Remote BZR Branch'
713
def open(self, a_bzrdir):
714
assert isinstance(a_bzrdir, RemoteBzrDir)
715
return a_bzrdir.open_branch()
717
def initialize(self, a_bzrdir):
718
assert isinstance(a_bzrdir, RemoteBzrDir)
719
return a_bzrdir.create_branch()
722
class RemoteBranch(branch.Branch):
723
"""Branch stored on a server accessed by HPSS RPC.
725
At the moment most operations are mapped down to simple file operations.
728
def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
730
"""Create a RemoteBranch instance.
732
:param real_branch: An optional local implementation of the branch
733
format, usually accessing the data via the VFS.
734
:param _client: Private parameter for testing.
736
# We intentionally don't call the parent class's __init__, because it
737
# will try to assign to self.tags, which is a property in this subclass.
738
# And the parent's __init__ doesn't do much anyway.
739
self._revision_history_cache = None
740
self.bzrdir = remote_bzrdir
741
if _client is not None:
742
self._client = _client
744
self._client = client._SmartClient(self.bzrdir._medium)
745
self.repository = remote_repository
746
if real_branch is not None:
747
self._real_branch = real_branch
748
# Give the remote repository the matching real repo.
749
real_repo = self._real_branch.repository
750
if isinstance(real_repo, RemoteRepository):
751
real_repo._ensure_real()
752
real_repo = real_repo._real_repository
753
self.repository._set_real_repository(real_repo)
754
# Give the branch the remote repository to let fast-pathing happen.
755
self._real_branch.repository = self.repository
757
self._real_branch = None
758
# Fill out expected attributes of branch for bzrlib api users.
759
self._format = RemoteBranchFormat()
760
self.base = self.bzrdir.root_transport.base
761
self._control_files = None
762
self._lock_mode = None
763
self._lock_token = None
765
self._leave_lock = False
767
def _ensure_real(self):
768
"""Ensure that there is a _real_branch set.
770
Used before calls to self._real_branch.
772
if not self._real_branch:
773
assert vfs.vfs_enabled()
774
self.bzrdir._ensure_real()
775
self._real_branch = self.bzrdir._real_bzrdir.open_branch()
776
# Give the remote repository the matching real repo.
777
real_repo = self._real_branch.repository
778
if isinstance(real_repo, RemoteRepository):
779
real_repo._ensure_real()
780
real_repo = real_repo._real_repository
781
self.repository._set_real_repository(real_repo)
782
# Give the branch the remote repository to let fast-pathing happen.
783
self._real_branch.repository = self.repository
784
# XXX: deal with _lock_mode == 'w'
785
if self._lock_mode == 'r':
786
self._real_branch.lock_read()
789
def control_files(self):
790
# Defer actually creating RemoteBranchLockableFiles until its needed,
791
# because it triggers an _ensure_real that we otherwise might not need.
792
if self._control_files is None:
793
self._control_files = RemoteBranchLockableFiles(
794
self.bzrdir, self._client)
795
return self._control_files
797
def _get_checkout_format(self):
799
return self._real_branch._get_checkout_format()
801
def get_physical_lock_status(self):
802
"""See Branch.get_physical_lock_status()."""
803
# should be an API call to the server, as branches must be lockable.
805
return self._real_branch.get_physical_lock_status()
808
if not self._lock_mode:
809
self._lock_mode = 'r'
811
if self._real_branch is not None:
812
self._real_branch.lock_read()
814
self._lock_count += 1
816
def _remote_lock_write(self, token):
818
branch_token = repo_token = ''
821
repo_token = self.repository.lock_write()
822
self.repository.unlock()
823
path = self.bzrdir._path_for_remote_call(self._client)
824
response = self._client.call('Branch.lock_write', path, branch_token,
826
if response[0] == 'ok':
827
ok, branch_token, repo_token = response
828
return branch_token, repo_token
829
elif response[0] == 'LockContention':
830
raise errors.LockContention('(remote lock)')
831
elif response[0] == 'TokenMismatch':
832
raise errors.TokenMismatch(token, '(remote token)')
833
elif response[0] == 'UnlockableTransport':
834
raise errors.UnlockableTransport(self.bzrdir.root_transport)
835
elif response[0] == 'ReadOnlyError':
836
raise errors.ReadOnlyError(self)
838
assert False, 'unexpected response code %r' % (response,)
840
def lock_write(self, token=None):
841
if not self._lock_mode:
842
remote_tokens = self._remote_lock_write(token)
843
self._lock_token, self._repo_lock_token = remote_tokens
844
assert self._lock_token, 'Remote server did not return a token!'
845
# TODO: We really, really, really don't want to call _ensure_real
846
# here, but it's the easiest way to ensure coherency between the
847
# state of the RemoteBranch and RemoteRepository objects and the
848
# physical locks. If we don't materialise the real objects here,
849
# then getting everything in the right state later is complex, so
850
# for now we just do it the lazy way.
851
# -- Andrew Bennetts, 2007-02-22.
853
if self._real_branch is not None:
854
self._real_branch.repository.lock_write(
855
token=self._repo_lock_token)
857
self._real_branch.lock_write(token=self._lock_token)
859
self._real_branch.repository.unlock()
860
if token is not None:
861
self._leave_lock = True
863
# XXX: this case seems to be unreachable; token cannot be None.
864
self._leave_lock = False
865
self._lock_mode = 'w'
867
elif self._lock_mode == 'r':
868
raise errors.ReadOnlyTransaction
870
if token is not None:
871
# A token was given to lock_write, and we're relocking, so check
872
# that the given token actually matches the one we already have.
873
if token != self._lock_token:
874
raise errors.TokenMismatch(token, self._lock_token)
875
self._lock_count += 1
876
return self._lock_token
878
def _unlock(self, branch_token, repo_token):
879
path = self.bzrdir._path_for_remote_call(self._client)
880
response = self._client.call('Branch.unlock', path, branch_token,
882
if response == ('ok',):
884
elif response[0] == 'TokenMismatch':
885
raise errors.TokenMismatch(
886
str((branch_token, repo_token)), '(remote tokens)')
888
assert False, 'unexpected response code %s' % (response,)
891
self._lock_count -= 1
892
if not self._lock_count:
893
self._clear_cached_state()
894
mode = self._lock_mode
895
self._lock_mode = None
896
if self._real_branch is not None:
897
if not self._leave_lock:
898
# If this RemoteBranch will remove the physical lock for the
899
# repository, make sure the _real_branch doesn't do it
900
# first. (Because the _real_branch's repository is set to
901
# be the RemoteRepository.)
902
self._real_branch.repository.leave_lock_in_place()
903
self._real_branch.unlock()
905
# Only write-locked branched need to make a remote method call
906
# to perfom the unlock.
908
assert self._lock_token, 'Locked, but no token!'
909
branch_token = self._lock_token
910
repo_token = self._repo_lock_token
911
self._lock_token = None
912
self._repo_lock_token = None
913
if not self._leave_lock:
914
self._unlock(branch_token, repo_token)
916
def break_lock(self):
918
return self._real_branch.break_lock()
920
def leave_lock_in_place(self):
921
self._leave_lock = True
923
def dont_leave_lock_in_place(self):
924
self._leave_lock = False
926
def last_revision_info(self):
927
"""See Branch.last_revision_info()."""
928
path = self.bzrdir._path_for_remote_call(self._client)
929
response = self._client.call('Branch.last_revision_info', path)
930
assert response[0] == 'ok', 'unexpected response code %s' % (response,)
931
revno = int(response[1])
932
last_revision = response[2]
933
return (revno, last_revision)
935
def _gen_revision_history(self):
936
"""See Branch._gen_revision_history()."""
937
path = self.bzrdir._path_for_remote_call(self._client)
938
response = self._client.call_expecting_body(
939
'Branch.revision_history', path)
940
assert response[0][0] == 'ok', ('unexpected response code %s'
942
result = response[1].read_body_bytes().split('\x00')
948
def set_revision_history(self, rev_history):
949
# Send just the tip revision of the history; the server will generate
950
# the full history from that. If the revision doesn't exist in this
951
# branch, NoSuchRevision will be raised.
952
path = self.bzrdir._path_for_remote_call(self._client)
953
if rev_history == []:
956
rev_id = rev_history[-1]
957
self._clear_cached_state()
958
response = self._client.call('Branch.set_last_revision',
959
path, self._lock_token, self._repo_lock_token, rev_id)
960
if response[0] == 'NoSuchRevision':
961
raise NoSuchRevision(self, rev_id)
963
assert response == ('ok',), (
964
'unexpected response code %r' % (response,))
965
self._cache_revision_history(rev_history)
967
def get_parent(self):
969
return self._real_branch.get_parent()
971
def set_parent(self, url):
973
return self._real_branch.set_parent(url)
975
def get_config(self):
976
return RemoteBranchConfig(self)
978
def sprout(self, to_bzrdir, revision_id=None):
979
# Like Branch.sprout, except that it sprouts a branch in the default
980
# format, because RemoteBranches can't be created at arbitrary URLs.
981
# XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
982
# to_bzrdir.create_branch...
983
result = branch.BranchFormat.get_default_format().initialize(to_bzrdir)
984
self.copy_content_into(result, revision_id=revision_id)
985
result.set_parent(self.bzrdir.root_transport.base)
989
def append_revision(self, *revision_ids):
991
return self._real_branch.append_revision(*revision_ids)
994
def pull(self, source, overwrite=False, stop_revision=None):
996
self._real_branch.pull(
997
source, overwrite=overwrite, stop_revision=stop_revision)
1000
def push(self, target, overwrite=False, stop_revision=None):
1002
return self._real_branch.push(
1003
target, overwrite=overwrite, stop_revision=stop_revision)
1005
def is_locked(self):
1006
return self._lock_count >= 1
1008
def set_last_revision_info(self, revno, revision_id):
1010
self._clear_cached_state()
1011
return self._real_branch.set_last_revision_info(revno, revision_id)
1013
def generate_revision_history(self, revision_id, last_rev=None,
1016
return self._real_branch.generate_revision_history(
1017
revision_id, last_rev=last_rev, other_branch=other_branch)
1022
return self._real_branch.tags
1024
def set_push_location(self, location):
1026
return self._real_branch.set_push_location(location)
1028
def update_revisions(self, other, stop_revision=None):
1030
return self._real_branch.update_revisions(
1031
other, stop_revision=stop_revision)
1034
class RemoteBranchConfig(BranchConfig):
1037
self.branch._ensure_real()
1038
return self.branch._real_branch.get_config().username()
1040
def _get_branch_data_config(self):
1041
self.branch._ensure_real()
1042
if self._branch_data_config is None:
1043
self._branch_data_config = TreeConfig(self.branch._real_branch)
1044
return self._branch_data_config
1047
def _extract_tar(tar, to_dir):
1048
"""Extract all the contents of a tarfile object.
1050
A replacement for extractall, which is not present in python2.4
1053
tar.extract(tarinfo, to_dir)