~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/remote.py

  • Committer: Vincent Ladeuil
  • Date: 2009-06-22 12:52:39 UTC
  • mto: (4471.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4472.
  • Revision ID: v.ladeuil+lp@free.fr-20090622125239-kabo9smxt9c3vnir
Use a consistent scheme for naming pyrex source files.

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
# TODO: At some point, handle upgrades by just passing the whole request
18
18
# across to run on the server.
19
19
 
20
20
import bz2
21
 
from cStringIO import StringIO
22
21
 
23
22
from bzrlib import (
 
23
    bencode,
24
24
    branch,
 
25
    bzrdir,
 
26
    config,
25
27
    debug,
26
28
    errors,
27
29
    graph,
28
30
    lockdir,
29
31
    repository,
30
32
    revision,
 
33
    revision as _mod_revision,
31
34
    symbol_versioning,
32
35
)
33
36
from bzrlib.branch import BranchReferenceFormat
34
37
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
35
 
from bzrlib.config import BranchConfig, TreeConfig
36
38
from bzrlib.decorators import needs_read_lock, needs_write_lock
37
39
from bzrlib.errors import (
38
40
    NoSuchRevision,
39
41
    SmartProtocolError,
40
42
    )
41
43
from bzrlib.lockable_files import LockableFiles
42
 
from bzrlib.pack import ContainerPushParser
43
 
from bzrlib.smart import client, vfs
 
44
from bzrlib.smart import client, vfs, repository as smart_repo
44
45
from bzrlib.revision import ensure_null, NULL_REVISION
45
 
from bzrlib.trace import mutter, mutter_callsite, note, warning
 
46
from bzrlib.trace import mutter, note, warning
 
47
 
 
48
 
 
49
class _RpcHelper(object):
 
50
    """Mixin class that helps with issuing RPCs."""
 
51
 
 
52
    def _call(self, method, *args, **err_context):
 
53
        try:
 
54
            return self._client.call(method, *args)
 
55
        except errors.ErrorFromSmartServer, err:
 
56
            self._translate_error(err, **err_context)
 
57
 
 
58
    def _call_expecting_body(self, method, *args, **err_context):
 
59
        try:
 
60
            return self._client.call_expecting_body(method, *args)
 
61
        except errors.ErrorFromSmartServer, err:
 
62
            self._translate_error(err, **err_context)
 
63
 
 
64
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
 
65
                                             **err_context):
 
66
        try:
 
67
            return self._client.call_with_body_bytes_expecting_body(
 
68
                method, args, body_bytes)
 
69
        except errors.ErrorFromSmartServer, err:
 
70
            self._translate_error(err, **err_context)
 
71
 
 
72
 
 
73
def response_tuple_to_repo_format(response):
 
74
    """Convert a response tuple describing a repository format to a format."""
 
75
    format = RemoteRepositoryFormat()
 
76
    format._rich_root_data = (response[0] == 'yes')
 
77
    format._supports_tree_reference = (response[1] == 'yes')
 
78
    format._supports_external_lookups = (response[2] == 'yes')
 
79
    format._network_name = response[3]
 
80
    return format
 
81
 
46
82
 
47
83
# Note: RemoteBzrDirFormat is in bzrdir.py
48
84
 
49
 
class RemoteBzrDir(BzrDir):
 
85
class RemoteBzrDir(BzrDir, _RpcHelper):
50
86
    """Control directory on a remote server, accessed via bzr:// or similar."""
51
87
 
52
 
    def __init__(self, transport, _client=None):
 
88
    def __init__(self, transport, format, _client=None):
53
89
        """Construct a RemoteBzrDir.
54
90
 
55
91
        :param _client: Private parameter for testing. Disables probing and the
56
92
            use of a real bzrdir.
57
93
        """
58
 
        BzrDir.__init__(self, transport, RemoteBzrDirFormat())
 
94
        BzrDir.__init__(self, transport, format)
59
95
        # this object holds a delegated bzrdir that uses file-level operations
60
96
        # to talk to the other side
61
97
        self._real_bzrdir = None
 
98
        # 1-shot cache for the call pattern 'create_branch; open_branch' - see
 
99
        # create_branch for details.
 
100
        self._next_open_branch_result = None
62
101
 
63
102
        if _client is None:
64
103
            medium = transport.get_smart_medium()
68
107
            return
69
108
 
70
109
        path = self._path_for_remote_call(self._client)
71
 
        response = self._client.call('BzrDir.open', path)
 
110
        response = self._call('BzrDir.open', path)
72
111
        if response not in [('yes',), ('no',)]:
73
112
            raise errors.UnexpectedSmartServerResponse(response)
74
113
        if response == ('no',):
82
121
        if not self._real_bzrdir:
83
122
            self._real_bzrdir = BzrDir.open_from_transport(
84
123
                self.root_transport, _server_formats=False)
 
124
            self._format._network_name = \
 
125
                self._real_bzrdir._format.network_name()
 
126
 
 
127
    def _translate_error(self, err, **context):
 
128
        _translate_error(err, bzrdir=self, **context)
 
129
 
 
130
    def break_lock(self):
 
131
        # Prevent aliasing problems in the next_open_branch_result cache.
 
132
        # See create_branch for rationale.
 
133
        self._next_open_branch_result = None
 
134
        return BzrDir.break_lock(self)
 
135
 
 
136
    def _vfs_cloning_metadir(self, require_stacking=False):
 
137
        self._ensure_real()
 
138
        return self._real_bzrdir.cloning_metadir(
 
139
            require_stacking=require_stacking)
 
140
 
 
141
    def cloning_metadir(self, require_stacking=False):
 
142
        medium = self._client._medium
 
143
        if medium._is_remote_before((1, 13)):
 
144
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
145
        verb = 'BzrDir.cloning_metadir'
 
146
        if require_stacking:
 
147
            stacking = 'True'
 
148
        else:
 
149
            stacking = 'False'
 
150
        path = self._path_for_remote_call(self._client)
 
151
        try:
 
152
            response = self._call(verb, path, stacking)
 
153
        except errors.UnknownSmartMethod:
 
154
            medium._remember_remote_is_before((1, 13))
 
155
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
156
        except errors.UnknownErrorFromSmartServer, err:
 
157
            if err.error_tuple != ('BranchReference',):
 
158
                raise
 
159
            # We need to resolve the branch reference to determine the
 
160
            # cloning_metadir.  This causes unnecessary RPCs to open the
 
161
            # referenced branch (and bzrdir, etc) but only when the caller
 
162
            # didn't already resolve the branch reference.
 
163
            referenced_branch = self.open_branch()
 
164
            return referenced_branch.bzrdir.cloning_metadir()
 
165
        if len(response) != 3:
 
166
            raise errors.UnexpectedSmartServerResponse(response)
 
167
        control_name, repo_name, branch_info = response
 
168
        if len(branch_info) != 2:
 
169
            raise errors.UnexpectedSmartServerResponse(response)
 
170
        branch_ref, branch_name = branch_info
 
171
        format = bzrdir.network_format_registry.get(control_name)
 
172
        if repo_name:
 
173
            format.repository_format = repository.network_format_registry.get(
 
174
                repo_name)
 
175
        if branch_ref == 'ref':
 
176
            # XXX: we need possible_transports here to avoid reopening the
 
177
            # connection to the referenced location
 
178
            ref_bzrdir = BzrDir.open(branch_name)
 
179
            branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
 
180
            format.set_branch_format(branch_format)
 
181
        elif branch_ref == 'branch':
 
182
            if branch_name:
 
183
                format.set_branch_format(
 
184
                    branch.network_format_registry.get(branch_name))
 
185
        else:
 
186
            raise errors.UnexpectedSmartServerResponse(response)
 
187
        return format
85
188
 
86
189
    def create_repository(self, shared=False):
87
 
        self._ensure_real()
88
 
        self._real_bzrdir.create_repository(shared=shared)
89
 
        return self.open_repository()
 
190
        # as per meta1 formats - just delegate to the format object which may
 
191
        # be parameterised.
 
192
        result = self._format.repository_format.initialize(self, shared)
 
193
        if not isinstance(result, RemoteRepository):
 
194
            return self.open_repository()
 
195
        else:
 
196
            return result
90
197
 
91
198
    def destroy_repository(self):
92
199
        """See BzrDir.destroy_repository"""
94
201
        self._real_bzrdir.destroy_repository()
95
202
 
96
203
    def create_branch(self):
97
 
        self._ensure_real()
98
 
        real_branch = self._real_bzrdir.create_branch()
99
 
        return RemoteBranch(self, self.find_repository(), real_branch)
 
204
        # as per meta1 formats - just delegate to the format object which may
 
205
        # be parameterised.
 
206
        real_branch = self._format.get_branch_format().initialize(self)
 
207
        if not isinstance(real_branch, RemoteBranch):
 
208
            result = RemoteBranch(self, self.find_repository(), real_branch)
 
209
        else:
 
210
            result = real_branch
 
211
        # BzrDir.clone_on_transport() uses the result of create_branch but does
 
212
        # not return it to its callers; we save approximately 8% of our round
 
213
        # trips by handing the branch we created back to the first caller to
 
214
        # open_branch rather than probing anew. Long term we need a API in
 
215
        # bzrdir that doesn't discard result objects (like result_branch).
 
216
        # RBC 20090225
 
217
        self._next_open_branch_result = result
 
218
        return result
100
219
 
101
220
    def destroy_branch(self):
102
221
        """See BzrDir.destroy_branch"""
103
222
        self._ensure_real()
104
223
        self._real_bzrdir.destroy_branch()
 
224
        self._next_open_branch_result = None
105
225
 
106
226
    def create_workingtree(self, revision_id=None, from_branch=None):
107
227
        raise errors.NotLocalUrl(self.transport.base)
116
236
 
117
237
    def get_branch_reference(self):
118
238
        """See BzrDir.get_branch_reference()."""
 
239
        response = self._get_branch_reference()
 
240
        if response[0] == 'ref':
 
241
            return response[1]
 
242
        else:
 
243
            return None
 
244
 
 
245
    def _get_branch_reference(self):
119
246
        path = self._path_for_remote_call(self._client)
120
 
        try:
121
 
            response = self._client.call('BzrDir.open_branch', path)
122
 
        except errors.ErrorFromSmartServer, err:
123
 
            if err.error_tuple == ('nobranch',):
124
 
                raise errors.NotBranchError(path=self.root_transport.base)
125
 
            raise
126
 
        if response[0] == 'ok':
127
 
            if response[1] == '':
128
 
                # branch at this location.
129
 
                return None
130
 
            else:
131
 
                # a branch reference, use the existing BranchReference logic.
132
 
                return response[1]
133
 
        else:
 
247
        medium = self._client._medium
 
248
        if not medium._is_remote_before((1, 13)):
 
249
            try:
 
250
                response = self._call('BzrDir.open_branchV2', path)
 
251
                if response[0] not in ('ref', 'branch'):
 
252
                    raise errors.UnexpectedSmartServerResponse(response)
 
253
                return response
 
254
            except errors.UnknownSmartMethod:
 
255
                medium._remember_remote_is_before((1, 13))
 
256
        response = self._call('BzrDir.open_branch', path)
 
257
        if response[0] != 'ok':
134
258
            raise errors.UnexpectedSmartServerResponse(response)
 
259
        if response[1] != '':
 
260
            return ('ref', response[1])
 
261
        else:
 
262
            return ('branch', '')
135
263
 
136
264
    def _get_tree_branch(self):
137
265
        """See BzrDir._get_tree_branch()."""
138
266
        return None, self.open_branch()
139
267
 
140
 
    def open_branch(self, _unsupported=False):
 
268
    def open_branch(self, _unsupported=False, ignore_fallbacks=False):
141
269
        if _unsupported:
142
270
            raise NotImplementedError('unsupported flag support not implemented yet.')
143
 
        reference_url = self.get_branch_reference()
144
 
        if reference_url is None:
145
 
            # branch at this location.
146
 
            return RemoteBranch(self, self.find_repository())
147
 
        else:
 
271
        if self._next_open_branch_result is not None:
 
272
            # See create_branch for details.
 
273
            result = self._next_open_branch_result
 
274
            self._next_open_branch_result = None
 
275
            return result
 
276
        response = self._get_branch_reference()
 
277
        if response[0] == 'ref':
148
278
            # a branch reference, use the existing BranchReference logic.
149
279
            format = BranchReferenceFormat()
150
 
            return format.open(self, _found=True, location=reference_url)
151
 
                
 
280
            return format.open(self, _found=True, location=response[1],
 
281
                ignore_fallbacks=ignore_fallbacks)
 
282
        branch_format_name = response[1]
 
283
        if not branch_format_name:
 
284
            branch_format_name = None
 
285
        format = RemoteBranchFormat(network_name=branch_format_name)
 
286
        return RemoteBranch(self, self.find_repository(), format=format,
 
287
            setup_stacking=not ignore_fallbacks)
 
288
 
 
289
    def _open_repo_v1(self, path):
 
290
        verb = 'BzrDir.find_repository'
 
291
        response = self._call(verb, path)
 
292
        if response[0] != 'ok':
 
293
            raise errors.UnexpectedSmartServerResponse(response)
 
294
        # servers that only support the v1 method don't support external
 
295
        # references either.
 
296
        self._ensure_real()
 
297
        repo = self._real_bzrdir.open_repository()
 
298
        response = response + ('no', repo._format.network_name())
 
299
        return response, repo
 
300
 
 
301
    def _open_repo_v2(self, path):
 
302
        verb = 'BzrDir.find_repositoryV2'
 
303
        response = self._call(verb, path)
 
304
        if response[0] != 'ok':
 
305
            raise errors.UnexpectedSmartServerResponse(response)
 
306
        self._ensure_real()
 
307
        repo = self._real_bzrdir.open_repository()
 
308
        response = response + (repo._format.network_name(),)
 
309
        return response, repo
 
310
 
 
311
    def _open_repo_v3(self, path):
 
312
        verb = 'BzrDir.find_repositoryV3'
 
313
        medium = self._client._medium
 
314
        if medium._is_remote_before((1, 13)):
 
315
            raise errors.UnknownSmartMethod(verb)
 
316
        try:
 
317
            response = self._call(verb, path)
 
318
        except errors.UnknownSmartMethod:
 
319
            medium._remember_remote_is_before((1, 13))
 
320
            raise
 
321
        if response[0] != 'ok':
 
322
            raise errors.UnexpectedSmartServerResponse(response)
 
323
        return response, None
 
324
 
152
325
    def open_repository(self):
153
326
        path = self._path_for_remote_call(self._client)
154
 
        verb = 'BzrDir.find_repositoryV2'
155
 
        try:
 
327
        response = None
 
328
        for probe in [self._open_repo_v3, self._open_repo_v2,
 
329
            self._open_repo_v1]:
156
330
            try:
157
 
                response = self._client.call(verb, path)
 
331
                response, real_repo = probe(path)
 
332
                break
158
333
            except errors.UnknownSmartMethod:
159
 
                verb = 'BzrDir.find_repository'
160
 
                response = self._client.call(verb, path)
161
 
        except errors.ErrorFromSmartServer, err:
162
 
            if err.error_verb == 'norepository':
163
 
                raise errors.NoRepositoryPresent(self)
164
 
            raise
 
334
                pass
 
335
        if response is None:
 
336
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
165
337
        if response[0] != 'ok':
166
338
            raise errors.UnexpectedSmartServerResponse(response)
167
 
        if verb == 'BzrDir.find_repository':
168
 
            # servers that don't support the V2 method don't support external
169
 
            # references either.
170
 
            response = response + ('no', )
171
 
        if not (len(response) == 5):
 
339
        if len(response) != 6:
172
340
            raise SmartProtocolError('incorrect response length %s' % (response,))
173
341
        if response[1] == '':
174
 
            format = RemoteRepositoryFormat()
175
 
            format.rich_root_data = (response[2] == 'yes')
176
 
            format.supports_tree_reference = (response[3] == 'yes')
177
 
            # No wire format to check this yet.
178
 
            format.supports_external_lookups = (response[4] == 'yes')
179
 
            return RemoteRepository(self, format)
 
342
            # repo is at this dir.
 
343
            format = response_tuple_to_repo_format(response[2:])
 
344
            # Used to support creating a real format instance when needed.
 
345
            format._creating_bzrdir = self
 
346
            remote_repo = RemoteRepository(self, format)
 
347
            format._creating_repo = remote_repo
 
348
            if real_repo is not None:
 
349
                remote_repo._set_real_repository(real_repo)
 
350
            return remote_repo
180
351
        else:
181
352
            raise errors.NoRepositoryPresent(self)
182
353
 
209
380
 
210
381
    def needs_format_conversion(self, format=None):
211
382
        """Upgrading of remote bzrdirs is not supported yet."""
 
383
        if format is None:
 
384
            symbol_versioning.warn(symbol_versioning.deprecated_in((1, 13, 0))
 
385
                % 'needs_format_conversion(format=None)')
212
386
        return False
213
387
 
214
 
    def clone(self, url, revision_id=None, force_new_repo=False):
 
388
    def clone(self, url, revision_id=None, force_new_repo=False,
 
389
              preserve_stacking=False):
215
390
        self._ensure_real()
216
391
        return self._real_bzrdir.clone(url, revision_id=revision_id,
217
 
            force_new_repo=force_new_repo)
 
392
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
 
393
 
 
394
    def _get_config(self):
 
395
        return RemoteBzrDirConfig(self)
218
396
 
219
397
 
220
398
class RemoteRepositoryFormat(repository.RepositoryFormat):
228
406
    the attributes rich_root_data and supports_tree_reference are set
229
407
    on a per instance basis, and are not set (and should not be) at
230
408
    the class level.
 
409
 
 
410
    :ivar _custom_format: If set, a specific concrete repository format that
 
411
        will be used when initializing a repository with this
 
412
        RemoteRepositoryFormat.
 
413
    :ivar _creating_repo: If set, the repository object that this
 
414
        RemoteRepositoryFormat was created for: it can be called into
 
415
        to obtain data like the network name.
231
416
    """
232
417
 
233
 
    _matchingbzrdir = RemoteBzrDirFormat
 
418
    _matchingbzrdir = RemoteBzrDirFormat()
 
419
 
 
420
    def __init__(self):
 
421
        repository.RepositoryFormat.__init__(self)
 
422
        self._custom_format = None
 
423
        self._network_name = None
 
424
        self._creating_bzrdir = None
 
425
        self._supports_external_lookups = None
 
426
        self._supports_tree_reference = None
 
427
        self._rich_root_data = None
 
428
 
 
429
    @property
 
430
    def fast_deltas(self):
 
431
        self._ensure_real()
 
432
        return self._custom_format.fast_deltas
 
433
 
 
434
    @property
 
435
    def rich_root_data(self):
 
436
        if self._rich_root_data is None:
 
437
            self._ensure_real()
 
438
            self._rich_root_data = self._custom_format.rich_root_data
 
439
        return self._rich_root_data
 
440
 
 
441
    @property
 
442
    def supports_external_lookups(self):
 
443
        if self._supports_external_lookups is None:
 
444
            self._ensure_real()
 
445
            self._supports_external_lookups = \
 
446
                self._custom_format.supports_external_lookups
 
447
        return self._supports_external_lookups
 
448
 
 
449
    @property
 
450
    def supports_tree_reference(self):
 
451
        if self._supports_tree_reference is None:
 
452
            self._ensure_real()
 
453
            self._supports_tree_reference = \
 
454
                self._custom_format.supports_tree_reference
 
455
        return self._supports_tree_reference
 
456
 
 
457
    def _vfs_initialize(self, a_bzrdir, shared):
 
458
        """Helper for common code in initialize."""
 
459
        if self._custom_format:
 
460
            # Custom format requested
 
461
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
 
462
        elif self._creating_bzrdir is not None:
 
463
            # Use the format that the repository we were created to back
 
464
            # has.
 
465
            prior_repo = self._creating_bzrdir.open_repository()
 
466
            prior_repo._ensure_real()
 
467
            result = prior_repo._real_repository._format.initialize(
 
468
                a_bzrdir, shared=shared)
 
469
        else:
 
470
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
 
471
            # support remote initialization.
 
472
            # We delegate to a real object at this point (as RemoteBzrDir
 
473
            # delegate to the repository format which would lead to infinite
 
474
            # recursion if we just called a_bzrdir.create_repository.
 
475
            a_bzrdir._ensure_real()
 
476
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
 
477
        if not isinstance(result, RemoteRepository):
 
478
            return self.open(a_bzrdir)
 
479
        else:
 
480
            return result
234
481
 
235
482
    def initialize(self, a_bzrdir, shared=False):
 
483
        # Being asked to create on a non RemoteBzrDir:
236
484
        if not isinstance(a_bzrdir, RemoteBzrDir):
237
 
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
238
 
        return a_bzrdir.create_repository(shared=shared)
239
 
    
 
485
            return self._vfs_initialize(a_bzrdir, shared)
 
486
        medium = a_bzrdir._client._medium
 
487
        if medium._is_remote_before((1, 13)):
 
488
            return self._vfs_initialize(a_bzrdir, shared)
 
489
        # Creating on a remote bzr dir.
 
490
        # 1) get the network name to use.
 
491
        if self._custom_format:
 
492
            network_name = self._custom_format.network_name()
 
493
        elif self._network_name:
 
494
            network_name = self._network_name
 
495
        else:
 
496
            # Select the current bzrlib default and ask for that.
 
497
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
498
            reference_format = reference_bzrdir_format.repository_format
 
499
            network_name = reference_format.network_name()
 
500
        # 2) try direct creation via RPC
 
501
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
502
        verb = 'BzrDir.create_repository'
 
503
        if shared:
 
504
            shared_str = 'True'
 
505
        else:
 
506
            shared_str = 'False'
 
507
        try:
 
508
            response = a_bzrdir._call(verb, path, network_name, shared_str)
 
509
        except errors.UnknownSmartMethod:
 
510
            # Fallback - use vfs methods
 
511
            medium._remember_remote_is_before((1, 13))
 
512
            return self._vfs_initialize(a_bzrdir, shared)
 
513
        else:
 
514
            # Turn the response into a RemoteRepository object.
 
515
            format = response_tuple_to_repo_format(response[1:])
 
516
            # Used to support creating a real format instance when needed.
 
517
            format._creating_bzrdir = a_bzrdir
 
518
            remote_repo = RemoteRepository(a_bzrdir, format)
 
519
            format._creating_repo = remote_repo
 
520
            return remote_repo
 
521
 
240
522
    def open(self, a_bzrdir):
241
523
        if not isinstance(a_bzrdir, RemoteBzrDir):
242
524
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
243
525
        return a_bzrdir.open_repository()
244
526
 
 
527
    def _ensure_real(self):
 
528
        if self._custom_format is None:
 
529
            self._custom_format = repository.network_format_registry.get(
 
530
                self._network_name)
 
531
 
 
532
    @property
 
533
    def _fetch_order(self):
 
534
        self._ensure_real()
 
535
        return self._custom_format._fetch_order
 
536
 
 
537
    @property
 
538
    def _fetch_uses_deltas(self):
 
539
        self._ensure_real()
 
540
        return self._custom_format._fetch_uses_deltas
 
541
 
 
542
    @property
 
543
    def _fetch_reconcile(self):
 
544
        self._ensure_real()
 
545
        return self._custom_format._fetch_reconcile
 
546
 
245
547
    def get_format_description(self):
246
548
        return 'bzr remote repository'
247
549
 
248
550
    def __eq__(self, other):
249
 
        return self.__class__ == other.__class__
 
551
        return self.__class__ is other.__class__
250
552
 
251
553
    def check_conversion_target(self, target_format):
252
554
        if self.rich_root_data and not target_format.rich_root_data:
257
559
            raise errors.BadConversionTarget(
258
560
                'Does not support nested trees', target_format)
259
561
 
260
 
 
261
 
class RemoteGraph(object):
262
 
 
263
 
    def __init__(self, real_graph, remote_repo):
264
 
        self._real_graph = real_graph
265
 
        self._remote_repo = remote_repo
266
 
 
267
 
    def heads(self, keys):
268
 
        client = self._remote_repo._client
269
 
        path = self._remote_repo.bzrdir._path_for_remote_call(client)
270
 
        return set(client.call('Repository.graph_heads', path, *keys))
271
 
 
272
 
    def find_lca(self, *revisions):
273
 
        return self._real_graph.find_lca(*revisions)
274
 
 
275
 
    def find_difference(self, left_revision, right_revision):
276
 
        return self._real_graph.find_difference(left_revision, right_revision)
277
 
 
278
 
    def find_unique_ancestors(self, unique_revision, common_revisions):
279
 
        return self._real_graph.find_unique_ancestors(
280
 
            unique_revision, common_revisions)
281
 
 
282
 
    def find_unique_lca(self, left_revision, right_revision,
283
 
                        count_steps=False):
284
 
        return self._real_graph.find_unique_lca(
285
 
            left_revision, right_revision, count_steps=count_steps)
286
 
        
287
 
    def get_parents(self, revisions):
288
 
        return self._real_graph.get_parents(revisions)
289
 
 
290
 
    def get_parent_map(self, revisions):
291
 
        return self._real_graph.get_parent_map(revisions)
292
 
 
293
 
    def is_ancestor(self, candidate_ancestor, candidate_descendant):
294
 
        return self._real_graph.is_ancestor(
295
 
            candidate_ancestor, candidate_descendant)
296
 
 
297
 
    def iter_ancestry(self, revision_ids):
298
 
        return self._real_graph.iter_ancestry(revision_ids)
299
 
 
300
 
    def iter_topo_order(self, revisions):
301
 
        return self._real_graph.iter_topo_order(revisions)
302
 
 
303
 
    def _make_breadth_first_searcher(self, revisions):
304
 
        return self._real_graph._make_breadth_first_searcher(revisions)
305
 
 
306
 
 
307
 
class RemoteRepository(object):
 
562
    def network_name(self):
 
563
        if self._network_name:
 
564
            return self._network_name
 
565
        self._creating_repo._ensure_real()
 
566
        return self._creating_repo._real_repository._format.network_name()
 
567
 
 
568
    @property
 
569
    def _serializer(self):
 
570
        self._ensure_real()
 
571
        return self._custom_format._serializer
 
572
 
 
573
 
 
574
class RemoteRepository(_RpcHelper):
308
575
    """Repository accessed over rpc.
309
576
 
310
577
    For the moment most operations are performed using local transport-backed
313
580
 
314
581
    def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
315
582
        """Create a RemoteRepository instance.
316
 
        
 
583
 
317
584
        :param remote_bzrdir: The bzrdir hosting this repository.
318
585
        :param format: The RemoteFormat object to use.
319
586
        :param real_repository: If not None, a local implementation of the
336
603
        self._lock_token = None
337
604
        self._lock_count = 0
338
605
        self._leave_lock = False
339
 
        # A cache of looked up revision parent data; reset at unlock time.
340
 
        self._parents_map = None
341
 
        if 'hpss' in debug.debug_flags:
342
 
            self._requested_parents = None
 
606
        # Cache of revision parents; misses are cached during read locks, and
 
607
        # write locks when no _real_repository has been set.
 
608
        self._unstacked_provider = graph.CachingParentsProvider(
 
609
            get_parent_map=self._get_parent_map_rpc)
 
610
        self._unstacked_provider.disable_cache()
343
611
        # For tests:
344
612
        # These depend on the actual remote format, so force them off for
345
613
        # maximum compatibility. XXX: In future these should depend on the
349
617
        self._reconcile_fixes_text_parents = False
350
618
        self._reconcile_backsup_inventory = False
351
619
        self.base = self.bzrdir.transport.base
 
620
        # Additional places to query for data.
 
621
        self._fallback_repositories = []
352
622
 
353
623
    def __str__(self):
354
624
        return "%s(%s)" % (self.__class__.__name__, self.base)
355
625
 
356
626
    __repr__ = __str__
357
627
 
358
 
    def abort_write_group(self):
 
628
    def abort_write_group(self, suppress_errors=False):
359
629
        """Complete a write group on the decorated repository.
360
 
        
361
 
        Smart methods peform operations in a single step so this api
 
630
 
 
631
        Smart methods perform operations in a single step so this API
362
632
        is not really applicable except as a compatibility thunk
363
633
        for older plugins that don't use e.g. the CommitBuilder
364
634
        facility.
365
 
        """
366
 
        self._ensure_real()
367
 
        return self._real_repository.abort_write_group()
 
635
 
 
636
        :param suppress_errors: see Repository.abort_write_group.
 
637
        """
 
638
        self._ensure_real()
 
639
        return self._real_repository.abort_write_group(
 
640
            suppress_errors=suppress_errors)
 
641
 
 
642
    @property
 
643
    def chk_bytes(self):
 
644
        """Decorate the real repository for now.
 
645
 
 
646
        In the long term a full blown network facility is needed to avoid
 
647
        creating a real repository object locally.
 
648
        """
 
649
        self._ensure_real()
 
650
        return self._real_repository.chk_bytes
368
651
 
369
652
    def commit_write_group(self):
370
653
        """Complete a write group on the decorated repository.
371
 
        
372
 
        Smart methods peform operations in a single step so this api
 
654
 
 
655
        Smart methods perform operations in a single step so this API
373
656
        is not really applicable except as a compatibility thunk
374
657
        for older plugins that don't use e.g. the CommitBuilder
375
658
        facility.
377
660
        self._ensure_real()
378
661
        return self._real_repository.commit_write_group()
379
662
 
 
663
    def resume_write_group(self, tokens):
 
664
        self._ensure_real()
 
665
        return self._real_repository.resume_write_group(tokens)
 
666
 
 
667
    def suspend_write_group(self):
 
668
        self._ensure_real()
 
669
        return self._real_repository.suspend_write_group()
 
670
 
 
671
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
672
        self._ensure_real()
 
673
        return self._real_repository.get_missing_parent_inventories(
 
674
            check_for_missing_texts=check_for_missing_texts)
 
675
 
 
676
    def _get_rev_id_for_revno_vfs(self, revno, known_pair):
 
677
        self._ensure_real()
 
678
        return self._real_repository.get_rev_id_for_revno(
 
679
            revno, known_pair)
 
680
 
 
681
    def get_rev_id_for_revno(self, revno, known_pair):
 
682
        """See Repository.get_rev_id_for_revno."""
 
683
        path = self.bzrdir._path_for_remote_call(self._client)
 
684
        try:
 
685
            if self._client._medium._is_remote_before((1, 17)):
 
686
                return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
687
            response = self._call(
 
688
                'Repository.get_rev_id_for_revno', path, revno, known_pair)
 
689
        except errors.UnknownSmartMethod:
 
690
            self._client._medium._remember_remote_is_before((1, 17))
 
691
            return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
692
        if response[0] == 'ok':
 
693
            return True, response[1]
 
694
        elif response[0] == 'history-incomplete':
 
695
            known_pair = response[1:3]
 
696
            for fallback in self._fallback_repositories:
 
697
                found, result = fallback.get_rev_id_for_revno(revno, known_pair)
 
698
                if found:
 
699
                    return True, result
 
700
                else:
 
701
                    known_pair = result
 
702
            # Not found in any fallbacks
 
703
            return False, known_pair
 
704
        else:
 
705
            raise errors.UnexpectedSmartServerResponse(response)
 
706
 
380
707
    def _ensure_real(self):
381
708
        """Ensure that there is a _real_repository set.
382
709
 
383
710
        Used before calls to self._real_repository.
 
711
 
 
712
        Note that _ensure_real causes many roundtrips to the server which are
 
713
        not desirable, and prevents the use of smart one-roundtrip RPC's to
 
714
        perform complex operations (such as accessing parent data, streaming
 
715
        revisions etc). Adding calls to _ensure_real should only be done when
 
716
        bringing up new functionality, adding fallbacks for smart methods that
 
717
        require a fallback path, and never to replace an existing smart method
 
718
        invocation. If in doubt chat to the bzr network team.
384
719
        """
385
 
        if not self._real_repository:
 
720
        if self._real_repository is None:
 
721
            if 'hpss' in debug.debug_flags:
 
722
                import traceback
 
723
                warning('VFS Repository access triggered\n%s',
 
724
                    ''.join(traceback.format_stack()))
 
725
            self._unstacked_provider.missing_keys.clear()
386
726
            self.bzrdir._ensure_real()
387
 
            #self._real_repository = self.bzrdir._real_bzrdir.open_repository()
388
 
            self._set_real_repository(self.bzrdir._real_bzrdir.open_repository())
 
727
            self._set_real_repository(
 
728
                self.bzrdir._real_bzrdir.open_repository())
 
729
 
 
730
    def _translate_error(self, err, **context):
 
731
        self.bzrdir._translate_error(err, repository=self, **context)
389
732
 
390
733
    def find_text_key_references(self):
391
734
        """Find the text key references within the repository.
412
755
        self._ensure_real()
413
756
        return self._real_repository._generate_text_key_index()
414
757
 
415
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_four)
416
 
    def get_revision_graph(self, revision_id=None):
417
 
        """See Repository.get_revision_graph()."""
418
 
        return self._get_revision_graph(revision_id)
419
 
 
420
758
    def _get_revision_graph(self, revision_id):
421
759
        """Private method for using with old (< 1.2) servers to fallback."""
422
760
        if revision_id is None:
425
763
            return {}
426
764
 
427
765
        path = self.bzrdir._path_for_remote_call(self._client)
428
 
        try:
429
 
            response = self._client.call_expecting_body(
430
 
                'Repository.get_revision_graph', path, revision_id)
431
 
        except errors.ErrorFromSmartServer, err:
432
 
            if err.error_verb == 'nosuchrevision':
433
 
                raise NoSuchRevision(self, revision_id)
434
 
            raise
 
766
        response = self._call_expecting_body(
 
767
            'Repository.get_revision_graph', path, revision_id)
435
768
        response_tuple, response_handler = response
436
769
        if response_tuple[0] != 'ok':
437
770
            raise errors.UnexpectedSmartServerResponse(response_tuple)
444
777
        for line in lines:
445
778
            d = tuple(line.split())
446
779
            revision_graph[d[0]] = d[1:]
447
 
            
 
780
 
448
781
        return revision_graph
449
782
 
 
783
    def _get_sink(self):
 
784
        """See Repository._get_sink()."""
 
785
        return RemoteStreamSink(self)
 
786
 
 
787
    def _get_source(self, to_format):
 
788
        """Return a source for streaming from this repository."""
 
789
        return RemoteStreamSource(self, to_format)
 
790
 
 
791
    @needs_read_lock
450
792
    def has_revision(self, revision_id):
451
 
        """See Repository.has_revision()."""
452
 
        if revision_id == NULL_REVISION:
453
 
            # The null revision is always present.
454
 
            return True
455
 
        path = self.bzrdir._path_for_remote_call(self._client)
456
 
        response = self._client.call(
457
 
            'Repository.has_revision', path, revision_id)
458
 
        if response[0] not in ('yes', 'no'):
459
 
            raise errors.UnexpectedSmartServerResponse(response)
460
 
        return response[0] == 'yes'
 
793
        """True if this repository has a copy of the revision."""
 
794
        # Copy of bzrlib.repository.Repository.has_revision
 
795
        return revision_id in self.has_revisions((revision_id,))
461
796
 
 
797
    @needs_read_lock
462
798
    def has_revisions(self, revision_ids):
463
 
        """See Repository.has_revisions()."""
464
 
        result = set()
465
 
        for revision_id in revision_ids:
466
 
            if self.has_revision(revision_id):
467
 
                result.add(revision_id)
 
799
        """Probe to find out the presence of multiple revisions.
 
800
 
 
801
        :param revision_ids: An iterable of revision_ids.
 
802
        :return: A set of the revision_ids that were present.
 
803
        """
 
804
        # Copy of bzrlib.repository.Repository.has_revisions
 
805
        parent_map = self.get_parent_map(revision_ids)
 
806
        result = set(parent_map)
 
807
        if _mod_revision.NULL_REVISION in revision_ids:
 
808
            result.add(_mod_revision.NULL_REVISION)
468
809
        return result
469
810
 
470
811
    def has_same_location(self, other):
471
 
        return (self.__class__ == other.__class__ and
 
812
        return (self.__class__ is other.__class__ and
472
813
                self.bzrdir.transport.base == other.bzrdir.transport.base)
473
 
        
 
814
 
474
815
    def get_graph(self, other_repository=None):
475
816
        """Return the graph for this repository format"""
476
 
        parents_provider = self
477
 
        if (other_repository is not None and
478
 
            other_repository.bzrdir.transport.base !=
479
 
            self.bzrdir.transport.base):
480
 
            parents_provider = graph._StackedParentsProvider(
481
 
                [parents_provider, other_repository._make_parents_provider()])
482
 
        real_graph = graph.Graph(parents_provider)
483
 
        return RemoteGraph(real_graph, self)
 
817
        parents_provider = self._make_parents_provider(other_repository)
 
818
        return graph.Graph(parents_provider)
484
819
 
485
820
    def gather_stats(self, revid=None, committers=None):
486
821
        """See Repository.gather_stats()."""
494
829
            fmt_committers = 'no'
495
830
        else:
496
831
            fmt_committers = 'yes'
497
 
        response_tuple, response_handler = self._client.call_expecting_body(
 
832
        response_tuple, response_handler = self._call_expecting_body(
498
833
            'Repository.gather_stats', path, fmt_revid, fmt_committers)
499
834
        if response_tuple[0] != 'ok':
500
835
            raise errors.UnexpectedSmartServerResponse(response_tuple)
539
874
    def is_shared(self):
540
875
        """See Repository.is_shared()."""
541
876
        path = self.bzrdir._path_for_remote_call(self._client)
542
 
        response = self._client.call('Repository.is_shared', path)
 
877
        response = self._call('Repository.is_shared', path)
543
878
        if response[0] not in ('yes', 'no'):
544
879
            raise SmartProtocolError('unexpected response code %s' % (response,))
545
880
        return response[0] == 'yes'
552
887
        if not self._lock_mode:
553
888
            self._lock_mode = 'r'
554
889
            self._lock_count = 1
555
 
            self._parents_map = {}
556
 
            if 'hpss' in debug.debug_flags:
557
 
                self._requested_parents = set()
 
890
            self._unstacked_provider.enable_cache(cache_misses=True)
558
891
            if self._real_repository is not None:
559
892
                self._real_repository.lock_read()
 
893
            for repo in self._fallback_repositories:
 
894
                repo.lock_read()
560
895
        else:
561
896
            self._lock_count += 1
562
897
 
564
899
        path = self.bzrdir._path_for_remote_call(self._client)
565
900
        if token is None:
566
901
            token = ''
567
 
        try:
568
 
            response = self._client.call('Repository.lock_write', path, token)
569
 
        except errors.ErrorFromSmartServer, err:
570
 
            if err.error_verb == 'LockContention':
571
 
                raise errors.LockContention('(remote lock)')
572
 
            elif err.error_verb == 'UnlockableTransport':
573
 
                raise errors.UnlockableTransport(self.bzrdir.root_transport)
574
 
            elif err.error_verb == 'LockFailed':
575
 
                raise errors.LockFailed(err.error_args[0], err.error_args[1])
576
 
            raise
577
 
 
 
902
        err_context = {'token': token}
 
903
        response = self._call('Repository.lock_write', path, token,
 
904
                              **err_context)
578
905
        if response[0] == 'ok':
579
906
            ok, token = response
580
907
            return token
581
908
        else:
582
909
            raise errors.UnexpectedSmartServerResponse(response)
583
910
 
584
 
    def lock_write(self, token=None):
 
911
    def lock_write(self, token=None, _skip_rpc=False):
585
912
        if not self._lock_mode:
586
 
            self._lock_token = self._remote_lock_write(token)
 
913
            if _skip_rpc:
 
914
                if self._lock_token is not None:
 
915
                    if token != self._lock_token:
 
916
                        raise errors.TokenMismatch(token, self._lock_token)
 
917
                self._lock_token = token
 
918
            else:
 
919
                self._lock_token = self._remote_lock_write(token)
587
920
            # if self._lock_token is None, then this is something like packs or
588
921
            # svn where we don't get to lock the repo, or a weave style repository
589
922
            # where we cannot lock it over the wire and attempts to do so will
596
929
                self._leave_lock = False
597
930
            self._lock_mode = 'w'
598
931
            self._lock_count = 1
599
 
            self._parents_map = {}
600
 
            if 'hpss' in debug.debug_flags:
601
 
                self._requested_parents = set()
 
932
            cache_misses = self._real_repository is None
 
933
            self._unstacked_provider.enable_cache(cache_misses=cache_misses)
 
934
            for repo in self._fallback_repositories:
 
935
                # Writes don't affect fallback repos
 
936
                repo.lock_read()
602
937
        elif self._lock_mode == 'r':
603
938
            raise errors.ReadOnlyError(self)
604
939
        else:
621
956
        :param repository: The repository to fallback to for non-hpss
622
957
            implemented operations.
623
958
        """
 
959
        if self._real_repository is not None:
 
960
            # Replacing an already set real repository.
 
961
            # We cannot do this [currently] if the repository is locked -
 
962
            # synchronised state might be lost.
 
963
            if self.is_locked():
 
964
                raise AssertionError('_real_repository is already set')
624
965
        if isinstance(repository, RemoteRepository):
625
966
            raise AssertionError()
626
967
        self._real_repository = repository
 
968
        # three code paths happen here:
 
969
        # 1) old servers, RemoteBranch.open() calls _ensure_real before setting
 
970
        # up stacking. In this case self._fallback_repositories is [], and the
 
971
        # real repo is already setup. Preserve the real repo and
 
972
        # RemoteRepository.add_fallback_repository will avoid adding
 
973
        # duplicates.
 
974
        # 2) new servers, RemoteBranch.open() sets up stacking, and when
 
975
        # ensure_real is triggered from a branch, the real repository to
 
976
        # set already has a matching list with separate instances, but
 
977
        # as they are also RemoteRepositories we don't worry about making the
 
978
        # lists be identical.
 
979
        # 3) new servers, RemoteRepository.ensure_real is triggered before
 
980
        # RemoteBranch.ensure real, in this case we get a repo with no fallbacks
 
981
        # and need to populate it.
 
982
        if (self._fallback_repositories and
 
983
            len(self._real_repository._fallback_repositories) !=
 
984
            len(self._fallback_repositories)):
 
985
            if len(self._real_repository._fallback_repositories):
 
986
                raise AssertionError(
 
987
                    "cannot cleanly remove existing _fallback_repositories")
 
988
        for fb in self._fallback_repositories:
 
989
            self._real_repository.add_fallback_repository(fb)
627
990
        if self._lock_mode == 'w':
628
991
            # if we are already locked, the real repository must be able to
629
992
            # acquire the lock with our token.
633
996
 
634
997
    def start_write_group(self):
635
998
        """Start a write group on the decorated repository.
636
 
        
637
 
        Smart methods peform operations in a single step so this api
 
999
 
 
1000
        Smart methods perform operations in a single step so this API
638
1001
        is not really applicable except as a compatibility thunk
639
1002
        for older plugins that don't use e.g. the CommitBuilder
640
1003
        facility.
647
1010
        if not token:
648
1011
            # with no token the remote repository is not persistently locked.
649
1012
            return
650
 
        try:
651
 
            response = self._client.call('Repository.unlock', path, token)
652
 
        except errors.ErrorFromSmartServer, err:
653
 
            if err.error_verb == 'TokenMismatch':
654
 
                raise errors.TokenMismatch(token, '(remote token)')
655
 
            raise
 
1013
        err_context = {'token': token}
 
1014
        response = self._call('Repository.unlock', path, token,
 
1015
                              **err_context)
656
1016
        if response == ('ok',):
657
1017
            return
658
1018
        else:
659
1019
            raise errors.UnexpectedSmartServerResponse(response)
660
1020
 
661
1021
    def unlock(self):
 
1022
        if not self._lock_count:
 
1023
            raise errors.LockNotHeld(self)
662
1024
        self._lock_count -= 1
663
1025
        if self._lock_count > 0:
664
1026
            return
665
 
        self._parents_map = None
666
 
        if 'hpss' in debug.debug_flags:
667
 
            self._requested_parents = None
 
1027
        self._unstacked_provider.disable_cache()
668
1028
        old_mode = self._lock_mode
669
1029
        self._lock_mode = None
670
1030
        try:
680
1040
            # problem releasing the vfs-based lock.
681
1041
            if old_mode == 'w':
682
1042
                # Only write-locked repositories need to make a remote method
683
 
                # call to perfom the unlock.
 
1043
                # call to perform the unlock.
684
1044
                old_token = self._lock_token
685
1045
                self._lock_token = None
686
1046
                if not self._leave_lock:
687
1047
                    self._unlock(old_token)
 
1048
        # Fallbacks are always 'lock_read()' so we don't pay attention to
 
1049
        # self._leave_lock
 
1050
        for repo in self._fallback_repositories:
 
1051
            repo.unlock()
688
1052
 
689
1053
    def break_lock(self):
690
1054
        # should hand off to the network
693
1057
 
694
1058
    def _get_tarball(self, compression):
695
1059
        """Return a TemporaryFile containing a repository tarball.
696
 
        
 
1060
 
697
1061
        Returns None if the server does not support sending tarballs.
698
1062
        """
699
1063
        import tempfile
700
1064
        path = self.bzrdir._path_for_remote_call(self._client)
701
1065
        try:
702
 
            response, protocol = self._client.call_expecting_body(
 
1066
            response, protocol = self._call_expecting_body(
703
1067
                'Repository.tarball', path, compression)
704
1068
        except errors.UnknownSmartMethod:
705
1069
            protocol.cancel_read_body()
737
1101
        # FIXME: It ought to be possible to call this without immediately
738
1102
        # triggering _ensure_real.  For now it's the easiest thing to do.
739
1103
        self._ensure_real()
740
 
        builder = self._real_repository.get_commit_builder(branch, parents,
 
1104
        real_repo = self._real_repository
 
1105
        builder = real_repo.get_commit_builder(branch, parents,
741
1106
                config, timestamp=timestamp, timezone=timezone,
742
1107
                committer=committer, revprops=revprops, revision_id=revision_id)
743
1108
        return builder
744
1109
 
 
1110
    def add_fallback_repository(self, repository):
 
1111
        """Add a repository to use for looking up data not held locally.
 
1112
 
 
1113
        :param repository: A repository.
 
1114
        """
 
1115
        if not self._format.supports_external_lookups:
 
1116
            raise errors.UnstackableRepositoryFormat(
 
1117
                self._format.network_name(), self.base)
 
1118
        # We need to accumulate additional repositories here, to pass them in
 
1119
        # on various RPC's.
 
1120
        #
 
1121
        if self.is_locked():
 
1122
            # We will call fallback.unlock() when we transition to the unlocked
 
1123
            # state, so always add a lock here. If a caller passes us a locked
 
1124
            # repository, they are responsible for unlocking it later.
 
1125
            repository.lock_read()
 
1126
        self._fallback_repositories.append(repository)
 
1127
        # If self._real_repository was parameterised already (e.g. because a
 
1128
        # _real_branch had its get_stacked_on_url method called), then the
 
1129
        # repository to be added may already be in the _real_repositories list.
 
1130
        if self._real_repository is not None:
 
1131
            fallback_locations = [repo.bzrdir.root_transport.base for repo in
 
1132
                self._real_repository._fallback_repositories]
 
1133
            if repository.bzrdir.root_transport.base not in fallback_locations:
 
1134
                self._real_repository.add_fallback_repository(repository)
 
1135
 
745
1136
    def add_inventory(self, revid, inv, parents):
746
1137
        self._ensure_real()
747
1138
        return self._real_repository.add_inventory(revid, inv, parents)
748
1139
 
 
1140
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
 
1141
                               parents):
 
1142
        self._ensure_real()
 
1143
        return self._real_repository.add_inventory_by_delta(basis_revision_id,
 
1144
            delta, new_revision_id, parents)
 
1145
 
749
1146
    def add_revision(self, rev_id, rev, inv=None, config=None):
750
1147
        self._ensure_real()
751
1148
        return self._real_repository.add_revision(
765
1162
        self._ensure_real()
766
1163
        return self._real_repository.get_revision(revision_id)
767
1164
 
768
 
    @property
769
 
    def weave_store(self):
770
 
        self._ensure_real()
771
 
        return self._real_repository.weave_store
772
 
 
773
1165
    def get_transaction(self):
774
1166
        self._ensure_real()
775
1167
        return self._real_repository.get_transaction()
784
1176
        self._ensure_real()
785
1177
        return self._real_repository.make_working_trees()
786
1178
 
 
1179
    def refresh_data(self):
 
1180
        """Re-read any data needed to to synchronise with disk.
 
1181
 
 
1182
        This method is intended to be called after another repository instance
 
1183
        (such as one used by a smart server) has inserted data into the
 
1184
        repository. It may not be called during a write group, but may be
 
1185
        called at any other time.
 
1186
        """
 
1187
        if self.is_in_write_group():
 
1188
            raise errors.InternalBzrError(
 
1189
                "May not refresh_data while in a write group.")
 
1190
        if self._real_repository is not None:
 
1191
            self._real_repository.refresh_data()
 
1192
 
787
1193
    def revision_ids_to_search_result(self, result_set):
788
1194
        """Convert a set of revision ids to a graph SearchResult."""
789
1195
        result_parents = set()
800
1206
    @needs_read_lock
801
1207
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
802
1208
        """Return the revision ids that other has that this does not.
803
 
        
 
1209
 
804
1210
        These are returned in topological order.
805
1211
 
806
1212
        revision_id: only return revision ids included by revision_id.
808
1214
        return repository.InterRepository.get(
809
1215
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
810
1216
 
811
 
    def fetch(self, source, revision_id=None, pb=None):
812
 
        if self.has_same_location(source):
 
1217
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1218
            fetch_spec=None):
 
1219
        # No base implementation to use as RemoteRepository is not a subclass
 
1220
        # of Repository; so this is a copy of Repository.fetch().
 
1221
        if fetch_spec is not None and revision_id is not None:
 
1222
            raise AssertionError(
 
1223
                "fetch_spec and revision_id are mutually exclusive.")
 
1224
        if self.is_in_write_group():
 
1225
            raise errors.InternalBzrError(
 
1226
                "May not fetch while in a write group.")
 
1227
        # fast path same-url fetch operations
 
1228
        if self.has_same_location(source) and fetch_spec is None:
813
1229
            # check that last_revision is in 'from' and then return a
814
1230
            # no-operation.
815
1231
            if (revision_id is not None and
816
1232
                not revision.is_null(revision_id)):
817
1233
                self.get_revision(revision_id)
818
1234
            return 0, []
819
 
        self._ensure_real()
820
 
        return self._real_repository.fetch(
821
 
            source, revision_id=revision_id, pb=pb)
 
1235
        # if there is no specific appropriate InterRepository, this will get
 
1236
        # the InterRepository base class, which raises an
 
1237
        # IncompatibleRepositories when asked to fetch.
 
1238
        inter = repository.InterRepository.get(source, self)
 
1239
        return inter.fetch(revision_id=revision_id, pb=pb,
 
1240
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
822
1241
 
823
1242
    def create_bundle(self, target, base, fileobj, format=None):
824
1243
        self._ensure_real()
825
1244
        self._real_repository.create_bundle(target, base, fileobj, format)
826
1245
 
827
 
    @property
828
 
    def control_weaves(self):
829
 
        self._ensure_real()
830
 
        return self._real_repository.control_weaves
831
 
 
832
1246
    @needs_read_lock
833
1247
    def get_ancestry(self, revision_id, topo_sorted=True):
834
1248
        self._ensure_real()
835
1249
        return self._real_repository.get_ancestry(revision_id, topo_sorted)
836
1250
 
837
 
    @needs_read_lock
838
 
    def get_inventory_weave(self):
839
 
        self._ensure_real()
840
 
        return self._real_repository.get_inventory_weave()
841
 
 
842
1251
    def fileids_altered_by_revision_ids(self, revision_ids):
843
1252
        self._ensure_real()
844
1253
        return self._real_repository.fileids_altered_by_revision_ids(revision_ids)
847
1256
        self._ensure_real()
848
1257
        return self._real_repository._get_versioned_file_checker(
849
1258
            revisions, revision_versions_cache)
850
 
        
 
1259
 
851
1260
    def iter_files_bytes(self, desired_files):
852
1261
        """See Repository.iter_file_bytes.
853
1262
        """
854
1263
        self._ensure_real()
855
1264
        return self._real_repository.iter_files_bytes(desired_files)
856
1265
 
857
 
    def get_parent_map(self, keys):
 
1266
    def get_parent_map(self, revision_ids):
858
1267
        """See bzrlib.Graph.get_parent_map()."""
859
 
#        mutter_callsite(None, "get_parent_map called with %d keys", len(keys))
860
 
#        import pdb;pdb.set_trace()
861
 
        # Hack to build up the caching logic.
862
 
        ancestry = self._parents_map
863
 
        if ancestry is None:
864
 
            # Repository is not locked, so there's no cache.
865
 
            missing_revisions = set(keys)
866
 
            ancestry = {}
867
 
        else:
868
 
            missing_revisions = set(key for key in keys if key not in ancestry)
869
 
        if missing_revisions:
870
 
            parent_map = self._get_parent_map(missing_revisions)
871
 
            if 'hpss' in debug.debug_flags:
872
 
                mutter('retransmitted revisions: %d of %d',
873
 
                        len(set(ancestry).intersection(parent_map)),
874
 
                        len(parent_map))
875
 
            ancestry.update(parent_map)
876
 
        present_keys = [k for k in keys if k in ancestry]
877
 
        if 'hpss' in debug.debug_flags and False:
878
 
            if self._requested_parents is not None and len(ancestry) != 0:
879
 
                self._requested_parents.update(present_keys)
880
 
                mutter('Current RemoteRepository graph hit rate: %d%%',
881
 
                    100.0 * len(self._requested_parents) / len(ancestry))
882
 
        return dict((k, ancestry[k]) for k in present_keys)
 
1268
        return self._make_parents_provider().get_parent_map(revision_ids)
883
1269
 
884
 
    def _get_parent_map(self, keys):
 
1270
    def _get_parent_map_rpc(self, keys):
885
1271
        """Helper for get_parent_map that performs the RPC."""
886
1272
        medium = self._client._medium
887
 
        if not medium._remote_is_at_least_1_2:
 
1273
        if medium._is_remote_before((1, 2)):
888
1274
            # We already found out that the server can't understand
889
1275
            # Repository.get_parent_map requests, so just fetch the whole
890
1276
            # graph.
891
 
            # XXX: Note that this will issue a deprecation warning. This is ok
892
 
            # :- its because we're working with a deprecated server anyway, and
893
 
            # the user will almost certainly have seen a warning about the
894
 
            # server version already.
895
 
            rg = self.get_revision_graph()
896
 
            # There is an api discrepency between get_parent_map and
 
1277
            #
 
1278
            # Note that this reads the whole graph, when only some keys are
 
1279
            # wanted.  On this old server there's no way (?) to get them all
 
1280
            # in one go, and the user probably will have seen a warning about
 
1281
            # the server being old anyhow.
 
1282
            rg = self._get_revision_graph(None)
 
1283
            # There is an API discrepancy between get_parent_map and
897
1284
            # get_revision_graph. Specifically, a "key:()" pair in
898
1285
            # get_revision_graph just means a node has no parents. For
899
1286
            # "get_parent_map" it means the node is a ghost. So fix up the
929
1316
        # TODO: Manage this incrementally to avoid covering the same path
930
1317
        # repeatedly. (The server will have to on each request, but the less
931
1318
        # work done the better).
932
 
        parents_map = self._parents_map
 
1319
        #
 
1320
        # Negative caching notes:
 
1321
        # new server sends missing when a request including the revid
 
1322
        # 'include-missing:' is present in the request.
 
1323
        # missing keys are serialised as missing:X, and we then call
 
1324
        # provider.note_missing(X) for-all X
 
1325
        parents_map = self._unstacked_provider.get_cached_map()
933
1326
        if parents_map is None:
934
1327
            # Repository is not locked, so there's no cache.
935
1328
            parents_map = {}
 
1329
        # start_set is all the keys in the cache
936
1330
        start_set = set(parents_map)
 
1331
        # result set is all the references to keys in the cache
937
1332
        result_parents = set()
938
1333
        for parents in parents_map.itervalues():
939
1334
            result_parents.update(parents)
940
1335
        stop_keys = result_parents.difference(start_set)
 
1336
        # We don't need to send ghosts back to the server as a position to
 
1337
        # stop either.
 
1338
        stop_keys.difference_update(self._unstacked_provider.missing_keys)
 
1339
        key_count = len(parents_map)
 
1340
        if (NULL_REVISION in result_parents
 
1341
            and NULL_REVISION in self._unstacked_provider.missing_keys):
 
1342
            # If we pruned NULL_REVISION from the stop_keys because it's also
 
1343
            # in our cache of "missing" keys we need to increment our key count
 
1344
            # by 1, because the reconsitituted SearchResult on the server will
 
1345
            # still consider NULL_REVISION to be an included key.
 
1346
            key_count += 1
941
1347
        included_keys = start_set.intersection(result_parents)
942
1348
        start_set.difference_update(included_keys)
943
 
        recipe = (start_set, stop_keys, len(parents_map))
 
1349
        recipe = ('manual', start_set, stop_keys, key_count)
944
1350
        body = self._serialise_search_recipe(recipe)
945
1351
        path = self.bzrdir._path_for_remote_call(self._client)
946
1352
        for key in keys:
948
1354
                raise ValueError(
949
1355
                    "key %r not a plain string" % (key,))
950
1356
        verb = 'Repository.get_parent_map'
951
 
        args = (path,) + tuple(keys)
 
1357
        args = (path, 'include-missing:') + tuple(keys)
952
1358
        try:
953
 
            response = self._client.call_with_body_bytes_expecting_body(
954
 
                verb, args, self._serialise_search_recipe(recipe))
 
1359
            response = self._call_with_body_bytes_expecting_body(
 
1360
                verb, args, body)
955
1361
        except errors.UnknownSmartMethod:
956
1362
            # Server does not support this method, so get the whole graph.
957
1363
            # Worse, we have to force a disconnection, because the server now
963
1369
            medium.disconnect()
964
1370
            # To avoid having to disconnect repeatedly, we keep track of the
965
1371
            # fact the server doesn't understand remote methods added in 1.2.
966
 
            medium._remote_is_at_least_1_2 = False
967
 
            return self.get_revision_graph(None)
 
1372
            medium._remember_remote_is_before((1, 2))
 
1373
            # Recurse just once and we should use the fallback code.
 
1374
            return self._get_parent_map_rpc(keys)
968
1375
        response_tuple, response_handler = response
969
1376
        if response_tuple[0] not in ['ok']:
970
1377
            response_handler.cancel_read_body()
981
1388
                if len(d) > 1:
982
1389
                    revision_graph[d[0]] = d[1:]
983
1390
                else:
984
 
                    # No parents - so give the Graph result (NULL_REVISION,).
985
 
                    revision_graph[d[0]] = (NULL_REVISION,)
 
1391
                    # No parents:
 
1392
                    if d[0].startswith('missing:'):
 
1393
                        revid = d[0][8:]
 
1394
                        self._unstacked_provider.note_missing_key(revid)
 
1395
                    else:
 
1396
                        # no parents - so give the Graph result
 
1397
                        # (NULL_REVISION,).
 
1398
                        revision_graph[d[0]] = (NULL_REVISION,)
986
1399
            return revision_graph
987
1400
 
988
1401
    @needs_read_lock
991
1404
        return self._real_repository.get_signature_text(revision_id)
992
1405
 
993
1406
    @needs_read_lock
994
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
995
 
    def get_revision_graph_with_ghosts(self, revision_ids=None):
996
 
        self._ensure_real()
997
 
        return self._real_repository.get_revision_graph_with_ghosts(
998
 
            revision_ids=revision_ids)
999
 
 
1000
 
    @needs_read_lock
1001
1407
    def get_inventory_xml(self, revision_id):
1002
1408
        self._ensure_real()
1003
1409
        return self._real_repository.get_inventory_xml(revision_id)
1009
1415
    def reconcile(self, other=None, thorough=False):
1010
1416
        self._ensure_real()
1011
1417
        return self._real_repository.reconcile(other=other, thorough=thorough)
1012
 
        
 
1418
 
1013
1419
    def all_revision_ids(self):
1014
1420
        self._ensure_real()
1015
1421
        return self._real_repository.all_revision_ids()
1016
 
    
1017
 
    @needs_read_lock
1018
 
    def get_deltas_for_revisions(self, revisions):
1019
 
        self._ensure_real()
1020
 
        return self._real_repository.get_deltas_for_revisions(revisions)
1021
 
 
1022
 
    @needs_read_lock
1023
 
    def get_revision_delta(self, revision_id):
1024
 
        self._ensure_real()
1025
 
        return self._real_repository.get_revision_delta(revision_id)
 
1422
 
 
1423
    @needs_read_lock
 
1424
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
1425
        self._ensure_real()
 
1426
        return self._real_repository.get_deltas_for_revisions(revisions,
 
1427
            specific_fileids=specific_fileids)
 
1428
 
 
1429
    @needs_read_lock
 
1430
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
1431
        self._ensure_real()
 
1432
        return self._real_repository.get_revision_delta(revision_id,
 
1433
            specific_fileids=specific_fileids)
1026
1434
 
1027
1435
    @needs_read_lock
1028
1436
    def revision_trees(self, revision_ids):
1049
1457
        # destination
1050
1458
        from bzrlib import osutils
1051
1459
        import tarfile
1052
 
        import tempfile
1053
1460
        # TODO: Maybe a progress bar while streaming the tarball?
1054
1461
        note("Copying repository content as tarball...")
1055
1462
        tar_file = self._get_tarball('bz2')
1059
1466
        try:
1060
1467
            tar = tarfile.open('repository', fileobj=tar_file,
1061
1468
                mode='r|bz2')
1062
 
            tmpdir = tempfile.mkdtemp()
 
1469
            tmpdir = osutils.mkdtemp()
1063
1470
            try:
1064
1471
                _extract_tar(tar, tmpdir)
1065
1472
                tmp_bzrdir = BzrDir.open(tmpdir)
1073
1480
        # TODO: Suggestion from john: using external tar is much faster than
1074
1481
        # python's tarfile library, but it may not work on windows.
1075
1482
 
 
1483
    @property
 
1484
    def inventories(self):
 
1485
        """Decorate the real repository for now.
 
1486
 
 
1487
        In the long term a full blown network facility is needed to
 
1488
        avoid creating a real repository object locally.
 
1489
        """
 
1490
        self._ensure_real()
 
1491
        return self._real_repository.inventories
 
1492
 
1076
1493
    @needs_write_lock
1077
1494
    def pack(self):
1078
1495
        """Compress the data within the repository.
1082
1499
        self._ensure_real()
1083
1500
        return self._real_repository.pack()
1084
1501
 
 
1502
    @property
 
1503
    def revisions(self):
 
1504
        """Decorate the real repository for now.
 
1505
 
 
1506
        In the short term this should become a real object to intercept graph
 
1507
        lookups.
 
1508
 
 
1509
        In the long term a full blown network facility is needed.
 
1510
        """
 
1511
        self._ensure_real()
 
1512
        return self._real_repository.revisions
 
1513
 
1085
1514
    def set_make_working_trees(self, new_value):
 
1515
        if new_value:
 
1516
            new_value_str = "True"
 
1517
        else:
 
1518
            new_value_str = "False"
 
1519
        path = self.bzrdir._path_for_remote_call(self._client)
 
1520
        try:
 
1521
            response = self._call(
 
1522
                'Repository.set_make_working_trees', path, new_value_str)
 
1523
        except errors.UnknownSmartMethod:
 
1524
            self._ensure_real()
 
1525
            self._real_repository.set_make_working_trees(new_value)
 
1526
        else:
 
1527
            if response[0] != 'ok':
 
1528
                raise errors.UnexpectedSmartServerResponse(response)
 
1529
 
 
1530
    @property
 
1531
    def signatures(self):
 
1532
        """Decorate the real repository for now.
 
1533
 
 
1534
        In the long term a full blown network facility is needed to avoid
 
1535
        creating a real repository object locally.
 
1536
        """
1086
1537
        self._ensure_real()
1087
 
        self._real_repository.set_make_working_trees(new_value)
 
1538
        return self._real_repository.signatures
1088
1539
 
1089
1540
    @needs_write_lock
1090
1541
    def sign_revision(self, revision_id, gpg_strategy):
1091
1542
        self._ensure_real()
1092
1543
        return self._real_repository.sign_revision(revision_id, gpg_strategy)
1093
1544
 
 
1545
    @property
 
1546
    def texts(self):
 
1547
        """Decorate the real repository for now.
 
1548
 
 
1549
        In the long term a full blown network facility is needed to avoid
 
1550
        creating a real repository object locally.
 
1551
        """
 
1552
        self._ensure_real()
 
1553
        return self._real_repository.texts
 
1554
 
1094
1555
    @needs_read_lock
1095
1556
    def get_revisions(self, revision_ids):
1096
1557
        self._ensure_real()
1097
1558
        return self._real_repository.get_revisions(revision_ids)
1098
1559
 
1099
1560
    def supports_rich_root(self):
1100
 
        self._ensure_real()
1101
 
        return self._real_repository.supports_rich_root()
 
1561
        return self._format.rich_root_data
1102
1562
 
1103
1563
    def iter_reverse_revision_history(self, revision_id):
1104
1564
        self._ensure_real()
1106
1566
 
1107
1567
    @property
1108
1568
    def _serializer(self):
1109
 
        self._ensure_real()
1110
 
        return self._real_repository._serializer
 
1569
        return self._format._serializer
1111
1570
 
1112
1571
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1113
1572
        self._ensure_real()
1122
1581
        self._ensure_real()
1123
1582
        return self._real_repository.has_signature_for_revision_id(revision_id)
1124
1583
 
1125
 
    def get_data_stream_for_search(self, search):
1126
 
        medium = self._client._medium
1127
 
        if not medium._remote_is_at_least_1_2:
1128
 
            self._ensure_real()
1129
 
            return self._real_repository.get_data_stream_for_search(search)
1130
 
        REQUEST_NAME = 'Repository.stream_revisions_chunked'
1131
 
        path = self.bzrdir._path_for_remote_call(self._client)
1132
 
        body = self._serialise_search_recipe(search.get_recipe())
1133
 
        try:
1134
 
            result = self._client.call_with_body_bytes_expecting_body(
1135
 
                REQUEST_NAME, (path,), body)
1136
 
            response, protocol = result
1137
 
        except errors.UnknownSmartMethod:
1138
 
            # Server does not support this method, so fall back to VFS.
1139
 
            # Worse, we have to force a disconnection, because the server now
1140
 
            # doesn't realise it has a body on the wire to consume, so the
1141
 
            # only way to recover is to abandon the connection.
1142
 
            warning(
1143
 
                'Server is too old for streaming pull, reconnecting.  '
1144
 
                '(Upgrade the server to Bazaar 1.2 to avoid this)')
1145
 
            medium.disconnect()
1146
 
            # To avoid having to disconnect repeatedly, we keep track of the
1147
 
            # fact the server doesn't understand this remote method.
1148
 
            medium._remote_is_at_least_1_2 = False
1149
 
            self._ensure_real()
1150
 
            return self._real_repository.get_data_stream_for_search(search)
1151
 
 
1152
 
        if response == ('ok',):
1153
 
            return self._deserialise_stream(protocol)
1154
 
        if response == ('NoSuchRevision', ):
1155
 
            # We cannot easily identify the revision that is missing in this
1156
 
            # situation without doing much more network IO. For now, bail.
1157
 
            raise NoSuchRevision(self, "unknown")
1158
 
        else:
1159
 
            raise errors.UnexpectedSmartServerResponse(response)
1160
 
 
1161
 
    def _deserialise_stream(self, protocol):
1162
 
        stream = protocol.read_streamed_body()
1163
 
        container_parser = ContainerPushParser()
1164
 
        for bytes in stream:
1165
 
            container_parser.accept_bytes(bytes)
1166
 
            records = container_parser.read_pending_records()
1167
 
            for record_names, record_bytes in records:
1168
 
                if len(record_names) != 1:
1169
 
                    # These records should have only one name, and that name
1170
 
                    # should be a one-element tuple.
1171
 
                    raise errors.SmartProtocolError(
1172
 
                        'Repository data stream had invalid record name %r'
1173
 
                        % (record_names,))
1174
 
                name_tuple = record_names[0]
1175
 
                yield name_tuple, record_bytes
1176
 
 
1177
 
    def insert_data_stream(self, stream):
1178
 
        self._ensure_real()
1179
 
        self._real_repository.insert_data_stream(stream)
1180
 
 
1181
1584
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1182
1585
        self._ensure_real()
1183
1586
        return self._real_repository.item_keys_introduced_by(revision_ids,
1196
1599
        self._ensure_real()
1197
1600
        return self._real_repository._check_for_inconsistent_revision_parents()
1198
1601
 
1199
 
    def _make_parents_provider(self):
1200
 
        return self
 
1602
    def _make_parents_provider(self, other=None):
 
1603
        providers = [self._unstacked_provider]
 
1604
        if other is not None:
 
1605
            providers.insert(0, other)
 
1606
        providers.extend(r._make_parents_provider() for r in
 
1607
                         self._fallback_repositories)
 
1608
        return graph.StackedParentsProvider(providers)
1201
1609
 
1202
1610
    def _serialise_search_recipe(self, recipe):
1203
1611
        """Serialise a graph search recipe.
1205
1613
        :param recipe: A search recipe (start, stop, count).
1206
1614
        :return: Serialised bytes.
1207
1615
        """
1208
 
        start_keys = ' '.join(recipe[0])
1209
 
        stop_keys = ' '.join(recipe[1])
1210
 
        count = str(recipe[2])
 
1616
        start_keys = ' '.join(recipe[1])
 
1617
        stop_keys = ' '.join(recipe[2])
 
1618
        count = str(recipe[3])
1211
1619
        return '\n'.join((start_keys, stop_keys, count))
1212
1620
 
 
1621
    def _serialise_search_result(self, search_result):
 
1622
        if isinstance(search_result, graph.PendingAncestryResult):
 
1623
            parts = ['ancestry-of']
 
1624
            parts.extend(search_result.heads)
 
1625
        else:
 
1626
            recipe = search_result.get_recipe()
 
1627
            parts = [recipe[0], self._serialise_search_recipe(recipe)]
 
1628
        return '\n'.join(parts)
 
1629
 
 
1630
    def autopack(self):
 
1631
        path = self.bzrdir._path_for_remote_call(self._client)
 
1632
        try:
 
1633
            response = self._call('PackRepository.autopack', path)
 
1634
        except errors.UnknownSmartMethod:
 
1635
            self._ensure_real()
 
1636
            self._real_repository._pack_collection.autopack()
 
1637
            return
 
1638
        self.refresh_data()
 
1639
        if response[0] != 'ok':
 
1640
            raise errors.UnexpectedSmartServerResponse(response)
 
1641
 
 
1642
 
 
1643
class RemoteStreamSink(repository.StreamSink):
 
1644
 
 
1645
    def _insert_real(self, stream, src_format, resume_tokens):
 
1646
        self.target_repo._ensure_real()
 
1647
        sink = self.target_repo._real_repository._get_sink()
 
1648
        result = sink.insert_stream(stream, src_format, resume_tokens)
 
1649
        if not result:
 
1650
            self.target_repo.autopack()
 
1651
        return result
 
1652
 
 
1653
    def insert_stream(self, stream, src_format, resume_tokens):
 
1654
        target = self.target_repo
 
1655
        target._unstacked_provider.missing_keys.clear()
 
1656
        if target._lock_token:
 
1657
            verb = 'Repository.insert_stream_locked'
 
1658
            extra_args = (target._lock_token or '',)
 
1659
            required_version = (1, 14)
 
1660
        else:
 
1661
            verb = 'Repository.insert_stream'
 
1662
            extra_args = ()
 
1663
            required_version = (1, 13)
 
1664
        client = target._client
 
1665
        medium = client._medium
 
1666
        if medium._is_remote_before(required_version):
 
1667
            # No possible way this can work.
 
1668
            return self._insert_real(stream, src_format, resume_tokens)
 
1669
        path = target.bzrdir._path_for_remote_call(client)
 
1670
        if not resume_tokens:
 
1671
            # XXX: Ugly but important for correctness, *will* be fixed during
 
1672
            # 1.13 cycle. Pushing a stream that is interrupted results in a
 
1673
            # fallback to the _real_repositories sink *with a partial stream*.
 
1674
            # Thats bad because we insert less data than bzr expected. To avoid
 
1675
            # this we do a trial push to make sure the verb is accessible, and
 
1676
            # do not fallback when actually pushing the stream. A cleanup patch
 
1677
            # is going to look at rewinding/restarting the stream/partial
 
1678
            # buffering etc.
 
1679
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
 
1680
            try:
 
1681
                response = client.call_with_body_stream(
 
1682
                    (verb, path, '') + extra_args, byte_stream)
 
1683
            except errors.UnknownSmartMethod:
 
1684
                medium._remember_remote_is_before(required_version)
 
1685
                return self._insert_real(stream, src_format, resume_tokens)
 
1686
        byte_stream = smart_repo._stream_to_byte_stream(
 
1687
            stream, src_format)
 
1688
        resume_tokens = ' '.join(resume_tokens)
 
1689
        response = client.call_with_body_stream(
 
1690
            (verb, path, resume_tokens) + extra_args, byte_stream)
 
1691
        if response[0][0] not in ('ok', 'missing-basis'):
 
1692
            raise errors.UnexpectedSmartServerResponse(response)
 
1693
        if response[0][0] == 'missing-basis':
 
1694
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
 
1695
            resume_tokens = tokens
 
1696
            return resume_tokens, set(missing_keys)
 
1697
        else:
 
1698
            self.target_repo.refresh_data()
 
1699
            return [], set()
 
1700
 
 
1701
 
 
1702
class RemoteStreamSource(repository.StreamSource):
 
1703
    """Stream data from a remote server."""
 
1704
 
 
1705
    def get_stream(self, search):
 
1706
        if (self.from_repository._fallback_repositories and
 
1707
            self.to_format._fetch_order == 'topological'):
 
1708
            return self._real_stream(self.from_repository, search)
 
1709
        return self.missing_parents_chain(search, [self.from_repository] +
 
1710
            self.from_repository._fallback_repositories)
 
1711
 
 
1712
    def _real_stream(self, repo, search):
 
1713
        """Get a stream for search from repo.
 
1714
        
 
1715
        This never called RemoteStreamSource.get_stream, and is a heler
 
1716
        for RemoteStreamSource._get_stream to allow getting a stream 
 
1717
        reliably whether fallback back because of old servers or trying
 
1718
        to stream from a non-RemoteRepository (which the stacked support
 
1719
        code will do).
 
1720
        """
 
1721
        source = repo._get_source(self.to_format)
 
1722
        if isinstance(source, RemoteStreamSource):
 
1723
            return repository.StreamSource.get_stream(source, search)
 
1724
        return source.get_stream(search)
 
1725
 
 
1726
    def _get_stream(self, repo, search):
 
1727
        """Core worker to get a stream from repo for search.
 
1728
 
 
1729
        This is used by both get_stream and the stacking support logic. It
 
1730
        deliberately gets a stream for repo which does not need to be
 
1731
        self.from_repository. In the event that repo is not Remote, or
 
1732
        cannot do a smart stream, a fallback is made to the generic
 
1733
        repository._get_stream() interface, via self._real_stream.
 
1734
 
 
1735
        In the event of stacking, streams from _get_stream will not
 
1736
        contain all the data for search - this is normal (see get_stream).
 
1737
 
 
1738
        :param repo: A repository.
 
1739
        :param search: A search.
 
1740
        """
 
1741
        # Fallbacks may be non-smart
 
1742
        if not isinstance(repo, RemoteRepository):
 
1743
            return self._real_stream(repo, search)
 
1744
        client = repo._client
 
1745
        medium = client._medium
 
1746
        if medium._is_remote_before((1, 13)):
 
1747
            # streaming was added in 1.13
 
1748
            return self._real_stream(repo, search)
 
1749
        path = repo.bzrdir._path_for_remote_call(client)
 
1750
        try:
 
1751
            search_bytes = repo._serialise_search_result(search)
 
1752
            response = repo._call_with_body_bytes_expecting_body(
 
1753
                'Repository.get_stream',
 
1754
                (path, self.to_format.network_name()), search_bytes)
 
1755
            response_tuple, response_handler = response
 
1756
        except errors.UnknownSmartMethod:
 
1757
            medium._remember_remote_is_before((1,13))
 
1758
            return self._real_stream(repo, search)
 
1759
        if response_tuple[0] != 'ok':
 
1760
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
1761
        byte_stream = response_handler.read_streamed_body()
 
1762
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
 
1763
        if src_format.network_name() != repo._format.network_name():
 
1764
            raise AssertionError(
 
1765
                "Mismatched RemoteRepository and stream src %r, %r" % (
 
1766
                src_format.network_name(), repo._format.network_name()))
 
1767
        return stream
 
1768
 
 
1769
    def missing_parents_chain(self, search, sources):
 
1770
        """Chain multiple streams together to handle stacking.
 
1771
 
 
1772
        :param search: The overall search to satisfy with streams.
 
1773
        :param sources: A list of Repository objects to query.
 
1774
        """
 
1775
        self.serialiser = self.to_format._serializer
 
1776
        self.seen_revs = set()
 
1777
        self.referenced_revs = set()
 
1778
        # If there are heads in the search, or the key count is > 0, we are not
 
1779
        # done.
 
1780
        while not search.is_empty() and len(sources) > 1:
 
1781
            source = sources.pop(0)
 
1782
            stream = self._get_stream(source, search)
 
1783
            for kind, substream in stream:
 
1784
                if kind != 'revisions':
 
1785
                    yield kind, substream
 
1786
                else:
 
1787
                    yield kind, self.missing_parents_rev_handler(substream)
 
1788
            search = search.refine(self.seen_revs, self.referenced_revs)
 
1789
            self.seen_revs = set()
 
1790
            self.referenced_revs = set()
 
1791
        if not search.is_empty():
 
1792
            for kind, stream in self._get_stream(sources[0], search):
 
1793
                yield kind, stream
 
1794
 
 
1795
    def missing_parents_rev_handler(self, substream):
 
1796
        for content in substream:
 
1797
            revision_bytes = content.get_bytes_as('fulltext')
 
1798
            revision = self.serialiser.read_revision_from_string(revision_bytes)
 
1799
            self.seen_revs.add(content.key[-1])
 
1800
            self.referenced_revs.update(revision.parent_ids)
 
1801
            yield content
 
1802
 
1213
1803
 
1214
1804
class RemoteBranchLockableFiles(LockableFiles):
1215
1805
    """A 'LockableFiles' implementation that talks to a smart server.
1216
 
    
 
1806
 
1217
1807
    This is not a public interface class.
1218
1808
    """
1219
1809
 
1233
1823
 
1234
1824
class RemoteBranchFormat(branch.BranchFormat):
1235
1825
 
 
1826
    def __init__(self, network_name=None):
 
1827
        super(RemoteBranchFormat, self).__init__()
 
1828
        self._matchingbzrdir = RemoteBzrDirFormat()
 
1829
        self._matchingbzrdir.set_branch_format(self)
 
1830
        self._custom_format = None
 
1831
        self._network_name = network_name
 
1832
 
1236
1833
    def __eq__(self, other):
1237
 
        return (isinstance(other, RemoteBranchFormat) and 
 
1834
        return (isinstance(other, RemoteBranchFormat) and
1238
1835
            self.__dict__ == other.__dict__)
1239
1836
 
 
1837
    def _ensure_real(self):
 
1838
        if self._custom_format is None:
 
1839
            self._custom_format = branch.network_format_registry.get(
 
1840
                self._network_name)
 
1841
 
1240
1842
    def get_format_description(self):
1241
1843
        return 'Remote BZR Branch'
1242
1844
 
1243
 
    def get_format_string(self):
1244
 
        return 'Remote BZR Branch'
1245
 
 
1246
 
    def open(self, a_bzrdir):
1247
 
        return a_bzrdir.open_branch()
 
1845
    def network_name(self):
 
1846
        return self._network_name
 
1847
 
 
1848
    def open(self, a_bzrdir, ignore_fallbacks=False):
 
1849
        return a_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
 
1850
 
 
1851
    def _vfs_initialize(self, a_bzrdir):
 
1852
        # Initialisation when using a local bzrdir object, or a non-vfs init
 
1853
        # method is not available on the server.
 
1854
        # self._custom_format is always set - the start of initialize ensures
 
1855
        # that.
 
1856
        if isinstance(a_bzrdir, RemoteBzrDir):
 
1857
            a_bzrdir._ensure_real()
 
1858
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
 
1859
        else:
 
1860
            # We assume the bzrdir is parameterised; it may not be.
 
1861
            result = self._custom_format.initialize(a_bzrdir)
 
1862
        if (isinstance(a_bzrdir, RemoteBzrDir) and
 
1863
            not isinstance(result, RemoteBranch)):
 
1864
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
 
1865
        return result
1248
1866
 
1249
1867
    def initialize(self, a_bzrdir):
1250
 
        return a_bzrdir.create_branch()
 
1868
        # 1) get the network name to use.
 
1869
        if self._custom_format:
 
1870
            network_name = self._custom_format.network_name()
 
1871
        else:
 
1872
            # Select the current bzrlib default and ask for that.
 
1873
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
1874
            reference_format = reference_bzrdir_format.get_branch_format()
 
1875
            self._custom_format = reference_format
 
1876
            network_name = reference_format.network_name()
 
1877
        # Being asked to create on a non RemoteBzrDir:
 
1878
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
1879
            return self._vfs_initialize(a_bzrdir)
 
1880
        medium = a_bzrdir._client._medium
 
1881
        if medium._is_remote_before((1, 13)):
 
1882
            return self._vfs_initialize(a_bzrdir)
 
1883
        # Creating on a remote bzr dir.
 
1884
        # 2) try direct creation via RPC
 
1885
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
1886
        verb = 'BzrDir.create_branch'
 
1887
        try:
 
1888
            response = a_bzrdir._call(verb, path, network_name)
 
1889
        except errors.UnknownSmartMethod:
 
1890
            # Fallback - use vfs methods
 
1891
            medium._remember_remote_is_before((1, 13))
 
1892
            return self._vfs_initialize(a_bzrdir)
 
1893
        if response[0] != 'ok':
 
1894
            raise errors.UnexpectedSmartServerResponse(response)
 
1895
        # Turn the response into a RemoteRepository object.
 
1896
        format = RemoteBranchFormat(network_name=response[1])
 
1897
        repo_format = response_tuple_to_repo_format(response[3:])
 
1898
        if response[2] == '':
 
1899
            repo_bzrdir = a_bzrdir
 
1900
        else:
 
1901
            repo_bzrdir = RemoteBzrDir(
 
1902
                a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
 
1903
                a_bzrdir._client)
 
1904
        remote_repo = RemoteRepository(repo_bzrdir, repo_format)
 
1905
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
 
1906
            format=format, setup_stacking=False)
 
1907
        # XXX: We know this is a new branch, so it must have revno 0, revid
 
1908
        # NULL_REVISION. Creating the branch locked would make this be unable
 
1909
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
 
1910
        remote_branch._last_revision_info_cache = 0, NULL_REVISION
 
1911
        return remote_branch
 
1912
 
 
1913
    def make_tags(self, branch):
 
1914
        self._ensure_real()
 
1915
        return self._custom_format.make_tags(branch)
1251
1916
 
1252
1917
    def supports_tags(self):
1253
1918
        # Remote branches might support tags, but we won't know until we
1254
1919
        # access the real remote branch.
1255
 
        return True
1256
 
 
1257
 
 
1258
 
class RemoteBranch(branch.Branch):
 
1920
        self._ensure_real()
 
1921
        return self._custom_format.supports_tags()
 
1922
 
 
1923
    def supports_stacking(self):
 
1924
        self._ensure_real()
 
1925
        return self._custom_format.supports_stacking()
 
1926
 
 
1927
    def supports_set_append_revisions_only(self):
 
1928
        self._ensure_real()
 
1929
        return self._custom_format.supports_set_append_revisions_only()
 
1930
 
 
1931
 
 
1932
class RemoteBranch(branch.Branch, _RpcHelper):
1259
1933
    """Branch stored on a server accessed by HPSS RPC.
1260
1934
 
1261
1935
    At the moment most operations are mapped down to simple file operations.
1262
1936
    """
1263
1937
 
1264
1938
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1265
 
        _client=None):
 
1939
        _client=None, format=None, setup_stacking=True):
1266
1940
        """Create a RemoteBranch instance.
1267
1941
 
1268
1942
        :param real_branch: An optional local implementation of the branch
1269
1943
            format, usually accessing the data via the VFS.
1270
1944
        :param _client: Private parameter for testing.
 
1945
        :param format: A RemoteBranchFormat object, None to create one
 
1946
            automatically. If supplied it should have a network_name already
 
1947
            supplied.
 
1948
        :param setup_stacking: If True make an RPC call to determine the
 
1949
            stacked (or not) status of the branch. If False assume the branch
 
1950
            is not stacked.
1271
1951
        """
1272
1952
        # We intentionally don't call the parent class's __init__, because it
1273
1953
        # will try to assign to self.tags, which is a property in this subclass.
1274
1954
        # And the parent's __init__ doesn't do much anyway.
1275
 
        self._revision_id_to_revno_cache = None
1276
 
        self._revision_history_cache = None
1277
 
        self._last_revision_info_cache = None
1278
1955
        self.bzrdir = remote_bzrdir
1279
1956
        if _client is not None:
1280
1957
            self._client = _client
1293
1970
            self._real_branch.repository = self.repository
1294
1971
        else:
1295
1972
            self._real_branch = None
1296
 
        # Fill out expected attributes of branch for bzrlib api users.
1297
 
        self._format = RemoteBranchFormat()
 
1973
        # Fill out expected attributes of branch for bzrlib API users.
 
1974
        self._clear_cached_state()
1298
1975
        self.base = self.bzrdir.root_transport.base
1299
1976
        self._control_files = None
1300
1977
        self._lock_mode = None
1302
1979
        self._repo_lock_token = None
1303
1980
        self._lock_count = 0
1304
1981
        self._leave_lock = False
 
1982
        # Setup a format: note that we cannot call _ensure_real until all the
 
1983
        # attributes above are set: This code cannot be moved higher up in this
 
1984
        # function.
 
1985
        if format is None:
 
1986
            self._format = RemoteBranchFormat()
 
1987
            if real_branch is not None:
 
1988
                self._format._network_name = \
 
1989
                    self._real_branch._format.network_name()
 
1990
        else:
 
1991
            self._format = format
 
1992
        if not self._format._network_name:
 
1993
            # Did not get from open_branchV2 - old server.
 
1994
            self._ensure_real()
 
1995
            self._format._network_name = \
 
1996
                self._real_branch._format.network_name()
 
1997
        self.tags = self._format.make_tags(self)
 
1998
        # The base class init is not called, so we duplicate this:
 
1999
        hooks = branch.Branch.hooks['open']
 
2000
        for hook in hooks:
 
2001
            hook(self)
 
2002
        self._is_stacked = False
 
2003
        if setup_stacking:
 
2004
            self._setup_stacking()
 
2005
 
 
2006
    def _setup_stacking(self):
 
2007
        # configure stacking into the remote repository, by reading it from
 
2008
        # the vfs branch.
 
2009
        try:
 
2010
            fallback_url = self.get_stacked_on_url()
 
2011
        except (errors.NotStacked, errors.UnstackableBranchFormat,
 
2012
            errors.UnstackableRepositoryFormat), e:
 
2013
            return
 
2014
        self._is_stacked = True
 
2015
        self._activate_fallback_location(fallback_url)
 
2016
 
 
2017
    def _get_config(self):
 
2018
        return RemoteBranchConfig(self)
 
2019
 
 
2020
    def _get_real_transport(self):
 
2021
        # if we try vfs access, return the real branch's vfs transport
 
2022
        self._ensure_real()
 
2023
        return self._real_branch._transport
 
2024
 
 
2025
    _transport = property(_get_real_transport)
1305
2026
 
1306
2027
    def __str__(self):
1307
2028
        return "%s(%s)" % (self.__class__.__name__, self.base)
1313
2034
 
1314
2035
        Used before calls to self._real_branch.
1315
2036
        """
1316
 
        if not self._real_branch:
 
2037
        if self._real_branch is None:
1317
2038
            if not vfs.vfs_enabled():
1318
2039
                raise AssertionError('smart server vfs must be enabled '
1319
2040
                    'to use vfs implementation')
1320
2041
            self.bzrdir._ensure_real()
1321
2042
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
1322
 
            # Give the remote repository the matching real repo.
1323
 
            real_repo = self._real_branch.repository
1324
 
            if isinstance(real_repo, RemoteRepository):
1325
 
                real_repo._ensure_real()
1326
 
                real_repo = real_repo._real_repository
1327
 
            self.repository._set_real_repository(real_repo)
1328
 
            # Give the branch the remote repository to let fast-pathing happen.
 
2043
            if self.repository._real_repository is None:
 
2044
                # Give the remote repository the matching real repo.
 
2045
                real_repo = self._real_branch.repository
 
2046
                if isinstance(real_repo, RemoteRepository):
 
2047
                    real_repo._ensure_real()
 
2048
                    real_repo = real_repo._real_repository
 
2049
                self.repository._set_real_repository(real_repo)
 
2050
            # Give the real branch the remote repository to let fast-pathing
 
2051
            # happen.
1329
2052
            self._real_branch.repository = self.repository
1330
 
            # XXX: deal with _lock_mode == 'w'
1331
2053
            if self._lock_mode == 'r':
1332
2054
                self._real_branch.lock_read()
 
2055
            elif self._lock_mode == 'w':
 
2056
                self._real_branch.lock_write(token=self._lock_token)
 
2057
 
 
2058
    def _translate_error(self, err, **context):
 
2059
        self.repository._translate_error(err, branch=self, **context)
1333
2060
 
1334
2061
    def _clear_cached_state(self):
1335
2062
        super(RemoteBranch, self)._clear_cached_state()
1336
 
        self._last_revision_info_cache = None
1337
 
        
 
2063
        if self._real_branch is not None:
 
2064
            self._real_branch._clear_cached_state()
 
2065
 
 
2066
    def _clear_cached_state_of_remote_branch_only(self):
 
2067
        """Like _clear_cached_state, but doesn't clear the cache of
 
2068
        self._real_branch.
 
2069
 
 
2070
        This is useful when falling back to calling a method of
 
2071
        self._real_branch that changes state.  In that case the underlying
 
2072
        branch changes, so we need to invalidate this RemoteBranch's cache of
 
2073
        it.  However, there's no need to invalidate the _real_branch's cache
 
2074
        too, in fact doing so might harm performance.
 
2075
        """
 
2076
        super(RemoteBranch, self)._clear_cached_state()
 
2077
 
1338
2078
    @property
1339
2079
    def control_files(self):
1340
2080
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1354
2094
        self._ensure_real()
1355
2095
        return self._real_branch.get_physical_lock_status()
1356
2096
 
 
2097
    def get_stacked_on_url(self):
 
2098
        """Get the URL this branch is stacked against.
 
2099
 
 
2100
        :raises NotStacked: If the branch is not stacked.
 
2101
        :raises UnstackableBranchFormat: If the branch does not support
 
2102
            stacking.
 
2103
        :raises UnstackableRepositoryFormat: If the repository does not support
 
2104
            stacking.
 
2105
        """
 
2106
        try:
 
2107
            # there may not be a repository yet, so we can't use
 
2108
            # self._translate_error, so we can't use self._call either.
 
2109
            response = self._client.call('Branch.get_stacked_on_url',
 
2110
                self._remote_path())
 
2111
        except errors.ErrorFromSmartServer, err:
 
2112
            # there may not be a repository yet, so we can't call through
 
2113
            # its _translate_error
 
2114
            _translate_error(err, branch=self)
 
2115
        except errors.UnknownSmartMethod, err:
 
2116
            self._ensure_real()
 
2117
            return self._real_branch.get_stacked_on_url()
 
2118
        if response[0] != 'ok':
 
2119
            raise errors.UnexpectedSmartServerResponse(response)
 
2120
        return response[1]
 
2121
 
 
2122
    def set_stacked_on_url(self, url):
 
2123
        branch.Branch.set_stacked_on_url(self, url)
 
2124
        if not url:
 
2125
            self._is_stacked = False
 
2126
        else:
 
2127
            self._is_stacked = True
 
2128
        
 
2129
    def _vfs_get_tags_bytes(self):
 
2130
        self._ensure_real()
 
2131
        return self._real_branch._get_tags_bytes()
 
2132
 
 
2133
    def _get_tags_bytes(self):
 
2134
        medium = self._client._medium
 
2135
        if medium._is_remote_before((1, 13)):
 
2136
            return self._vfs_get_tags_bytes()
 
2137
        try:
 
2138
            response = self._call('Branch.get_tags_bytes', self._remote_path())
 
2139
        except errors.UnknownSmartMethod:
 
2140
            medium._remember_remote_is_before((1, 13))
 
2141
            return self._vfs_get_tags_bytes()
 
2142
        return response[0]
 
2143
 
1357
2144
    def lock_read(self):
 
2145
        self.repository.lock_read()
1358
2146
        if not self._lock_mode:
1359
2147
            self._lock_mode = 'r'
1360
2148
            self._lock_count = 1
1370
2158
            branch_token = token
1371
2159
            repo_token = self.repository.lock_write()
1372
2160
            self.repository.unlock()
1373
 
        path = self.bzrdir._path_for_remote_call(self._client)
1374
 
        try:
1375
 
            response = self._client.call(
1376
 
                'Branch.lock_write', path, branch_token, repo_token or '')
1377
 
        except errors.ErrorFromSmartServer, err:
1378
 
            if err.error_verb == 'LockContention':
1379
 
                raise errors.LockContention('(remote lock)')
1380
 
            elif err.error_verb == 'TokenMismatch':
1381
 
                raise errors.TokenMismatch(token, '(remote token)')
1382
 
            elif err.error_verb == 'UnlockableTransport':
1383
 
                raise errors.UnlockableTransport(self.bzrdir.root_transport)
1384
 
            elif err.error_verb == 'ReadOnlyError':
1385
 
                raise errors.ReadOnlyError(self)
1386
 
            elif err.error_verb == 'LockFailed':
1387
 
                raise errors.LockFailed(err.error_args[0], err.error_args[1])
1388
 
            raise
 
2161
        err_context = {'token': token}
 
2162
        response = self._call(
 
2163
            'Branch.lock_write', self._remote_path(), branch_token,
 
2164
            repo_token or '', **err_context)
1389
2165
        if response[0] != 'ok':
1390
2166
            raise errors.UnexpectedSmartServerResponse(response)
1391
2167
        ok, branch_token, repo_token = response
1392
2168
        return branch_token, repo_token
1393
 
            
 
2169
 
1394
2170
    def lock_write(self, token=None):
1395
2171
        if not self._lock_mode:
 
2172
            # Lock the branch and repo in one remote call.
1396
2173
            remote_tokens = self._remote_lock_write(token)
1397
2174
            self._lock_token, self._repo_lock_token = remote_tokens
1398
2175
            if not self._lock_token:
1399
2176
                raise SmartProtocolError('Remote server did not return a token!')
1400
 
            # TODO: We really, really, really don't want to call _ensure_real
1401
 
            # here, but it's the easiest way to ensure coherency between the
1402
 
            # state of the RemoteBranch and RemoteRepository objects and the
1403
 
            # physical locks.  If we don't materialise the real objects here,
1404
 
            # then getting everything in the right state later is complex, so
1405
 
            # for now we just do it the lazy way.
1406
 
            #   -- Andrew Bennetts, 2007-02-22.
1407
 
            self._ensure_real()
 
2177
            # Tell the self.repository object that it is locked.
 
2178
            self.repository.lock_write(
 
2179
                self._repo_lock_token, _skip_rpc=True)
 
2180
 
1408
2181
            if self._real_branch is not None:
1409
 
                self._real_branch.repository.lock_write(
1410
 
                    token=self._repo_lock_token)
1411
 
                try:
1412
 
                    self._real_branch.lock_write(token=self._lock_token)
1413
 
                finally:
1414
 
                    self._real_branch.repository.unlock()
 
2182
                self._real_branch.lock_write(token=self._lock_token)
1415
2183
            if token is not None:
1416
2184
                self._leave_lock = True
1417
2185
            else:
1418
 
                # XXX: this case seems to be unreachable; token cannot be None.
1419
2186
                self._leave_lock = False
1420
2187
            self._lock_mode = 'w'
1421
2188
            self._lock_count = 1
1423
2190
            raise errors.ReadOnlyTransaction
1424
2191
        else:
1425
2192
            if token is not None:
1426
 
                # A token was given to lock_write, and we're relocking, so check
1427
 
                # that the given token actually matches the one we already have.
 
2193
                # A token was given to lock_write, and we're relocking, so
 
2194
                # check that the given token actually matches the one we
 
2195
                # already have.
1428
2196
                if token != self._lock_token:
1429
2197
                    raise errors.TokenMismatch(token, self._lock_token)
1430
2198
            self._lock_count += 1
 
2199
            # Re-lock the repository too.
 
2200
            self.repository.lock_write(self._repo_lock_token)
1431
2201
        return self._lock_token or None
1432
2202
 
 
2203
    def _set_tags_bytes(self, bytes):
 
2204
        self._ensure_real()
 
2205
        return self._real_branch._set_tags_bytes(bytes)
 
2206
 
1433
2207
    def _unlock(self, branch_token, repo_token):
1434
 
        path = self.bzrdir._path_for_remote_call(self._client)
1435
 
        try:
1436
 
            response = self._client.call('Branch.unlock', path, branch_token,
1437
 
                                         repo_token or '')
1438
 
        except errors.ErrorFromSmartServer, err:
1439
 
            if err.error_verb == 'TokenMismatch':
1440
 
                raise errors.TokenMismatch(
1441
 
                    str((branch_token, repo_token)), '(remote tokens)')
1442
 
            raise
 
2208
        err_context = {'token': str((branch_token, repo_token))}
 
2209
        response = self._call(
 
2210
            'Branch.unlock', self._remote_path(), branch_token,
 
2211
            repo_token or '', **err_context)
1443
2212
        if response == ('ok',):
1444
2213
            return
1445
2214
        raise errors.UnexpectedSmartServerResponse(response)
1446
2215
 
1447
2216
    def unlock(self):
1448
 
        self._lock_count -= 1
1449
 
        if not self._lock_count:
1450
 
            self._clear_cached_state()
1451
 
            mode = self._lock_mode
1452
 
            self._lock_mode = None
1453
 
            if self._real_branch is not None:
1454
 
                if (not self._leave_lock and mode == 'w' and
1455
 
                    self._repo_lock_token):
1456
 
                    # If this RemoteBranch will remove the physical lock for the
1457
 
                    # repository, make sure the _real_branch doesn't do it
1458
 
                    # first.  (Because the _real_branch's repository is set to
1459
 
                    # be the RemoteRepository.)
1460
 
                    self._real_branch.repository.leave_lock_in_place()
1461
 
                self._real_branch.unlock()
1462
 
            if mode != 'w':
1463
 
                # Only write-locked branched need to make a remote method call
1464
 
                # to perfom the unlock.
1465
 
                return
1466
 
            if not self._lock_token:
1467
 
                raise AssertionError('Locked, but no token!')
1468
 
            branch_token = self._lock_token
1469
 
            repo_token = self._repo_lock_token
1470
 
            self._lock_token = None
1471
 
            self._repo_lock_token = None
1472
 
            if not self._leave_lock:
1473
 
                self._unlock(branch_token, repo_token)
 
2217
        try:
 
2218
            self._lock_count -= 1
 
2219
            if not self._lock_count:
 
2220
                self._clear_cached_state()
 
2221
                mode = self._lock_mode
 
2222
                self._lock_mode = None
 
2223
                if self._real_branch is not None:
 
2224
                    if (not self._leave_lock and mode == 'w' and
 
2225
                        self._repo_lock_token):
 
2226
                        # If this RemoteBranch will remove the physical lock
 
2227
                        # for the repository, make sure the _real_branch
 
2228
                        # doesn't do it first.  (Because the _real_branch's
 
2229
                        # repository is set to be the RemoteRepository.)
 
2230
                        self._real_branch.repository.leave_lock_in_place()
 
2231
                    self._real_branch.unlock()
 
2232
                if mode != 'w':
 
2233
                    # Only write-locked branched need to make a remote method
 
2234
                    # call to perform the unlock.
 
2235
                    return
 
2236
                if not self._lock_token:
 
2237
                    raise AssertionError('Locked, but no token!')
 
2238
                branch_token = self._lock_token
 
2239
                repo_token = self._repo_lock_token
 
2240
                self._lock_token = None
 
2241
                self._repo_lock_token = None
 
2242
                if not self._leave_lock:
 
2243
                    self._unlock(branch_token, repo_token)
 
2244
        finally:
 
2245
            self.repository.unlock()
1474
2246
 
1475
2247
    def break_lock(self):
1476
2248
        self._ensure_real()
1486
2258
            raise NotImplementedError(self.dont_leave_lock_in_place)
1487
2259
        self._leave_lock = False
1488
2260
 
1489
 
    def last_revision_info(self):
1490
 
        """See Branch.last_revision_info()."""
1491
 
        if self._last_revision_info_cache is None:
1492
 
            self._last_revision_info_cache = self._last_revision_info()
1493
 
        return self._last_revision_info_cache
1494
 
    
 
2261
    def get_rev_id(self, revno, history=None):
 
2262
        if revno == 0:
 
2263
            return _mod_revision.NULL_REVISION
 
2264
        last_revision_info = self.last_revision_info()
 
2265
        ok, result = self.repository.get_rev_id_for_revno(
 
2266
            revno, last_revision_info)
 
2267
        if ok:
 
2268
            return result
 
2269
        missing_parent = result[1]
 
2270
        # Either the revision named by the server is missing, or its parent
 
2271
        # is.  Call get_parent_map to determine which, so that we report a
 
2272
        # useful error.
 
2273
        parent_map = self.repository.get_parent_map([missing_parent])
 
2274
        if missing_parent in parent_map:
 
2275
            missing_parent = parent_map[missing_parent]
 
2276
        raise errors.RevisionNotPresent(missing_parent, self.repository)
 
2277
 
1495
2278
    def _last_revision_info(self):
1496
 
        path = self.bzrdir._path_for_remote_call(self._client)
1497
 
        response = self._client.call('Branch.last_revision_info', path)
 
2279
        response = self._call('Branch.last_revision_info', self._remote_path())
1498
2280
        if response[0] != 'ok':
1499
2281
            raise SmartProtocolError('unexpected response code %s' % (response,))
1500
2282
        revno = int(response[1])
1503
2285
 
1504
2286
    def _gen_revision_history(self):
1505
2287
        """See Branch._gen_revision_history()."""
1506
 
        path = self.bzrdir._path_for_remote_call(self._client)
1507
 
        response_tuple, response_handler = self._client.call_expecting_body(
1508
 
            'Branch.revision_history', path)
 
2288
        if self._is_stacked:
 
2289
            self._ensure_real()
 
2290
            return self._real_branch._gen_revision_history()
 
2291
        response_tuple, response_handler = self._call_expecting_body(
 
2292
            'Branch.revision_history', self._remote_path())
1509
2293
        if response_tuple[0] != 'ok':
1510
 
            raise UnexpectedSmartServerResponse(response_tuple)
 
2294
            raise errors.UnexpectedSmartServerResponse(response_tuple)
1511
2295
        result = response_handler.read_body_bytes().split('\x00')
1512
2296
        if result == ['']:
1513
2297
            return []
1514
2298
        return result
1515
2299
 
 
2300
    def _remote_path(self):
 
2301
        return self.bzrdir._path_for_remote_call(self._client)
 
2302
 
 
2303
    def _set_last_revision_descendant(self, revision_id, other_branch,
 
2304
            allow_diverged=False, allow_overwrite_descendant=False):
 
2305
        # This performs additional work to meet the hook contract; while its
 
2306
        # undesirable, we have to synthesise the revno to call the hook, and
 
2307
        # not calling the hook is worse as it means changes can't be prevented.
 
2308
        # Having calculated this though, we can't just call into
 
2309
        # set_last_revision_info as a simple call, because there is a set_rh
 
2310
        # hook that some folk may still be using.
 
2311
        old_revno, old_revid = self.last_revision_info()
 
2312
        history = self._lefthand_history(revision_id)
 
2313
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
 
2314
        err_context = {'other_branch': other_branch}
 
2315
        response = self._call('Branch.set_last_revision_ex',
 
2316
            self._remote_path(), self._lock_token, self._repo_lock_token,
 
2317
            revision_id, int(allow_diverged), int(allow_overwrite_descendant),
 
2318
            **err_context)
 
2319
        self._clear_cached_state()
 
2320
        if len(response) != 3 and response[0] != 'ok':
 
2321
            raise errors.UnexpectedSmartServerResponse(response)
 
2322
        new_revno, new_revision_id = response[1:]
 
2323
        self._last_revision_info_cache = new_revno, new_revision_id
 
2324
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2325
        if self._real_branch is not None:
 
2326
            cache = new_revno, new_revision_id
 
2327
            self._real_branch._last_revision_info_cache = cache
 
2328
 
1516
2329
    def _set_last_revision(self, revision_id):
1517
 
        path = self.bzrdir._path_for_remote_call(self._client)
 
2330
        old_revno, old_revid = self.last_revision_info()
 
2331
        # This performs additional work to meet the hook contract; while its
 
2332
        # undesirable, we have to synthesise the revno to call the hook, and
 
2333
        # not calling the hook is worse as it means changes can't be prevented.
 
2334
        # Having calculated this though, we can't just call into
 
2335
        # set_last_revision_info as a simple call, because there is a set_rh
 
2336
        # hook that some folk may still be using.
 
2337
        history = self._lefthand_history(revision_id)
 
2338
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1518
2339
        self._clear_cached_state()
1519
 
        try:
1520
 
            response = self._client.call('Branch.set_last_revision',
1521
 
                path, self._lock_token, self._repo_lock_token, revision_id)
1522
 
        except errors.ErrorFromSmartServer, err:
1523
 
            if err.error_verb == 'NoSuchRevision':
1524
 
                raise NoSuchRevision(self, revision_id)
1525
 
            raise
 
2340
        response = self._call('Branch.set_last_revision',
 
2341
            self._remote_path(), self._lock_token, self._repo_lock_token,
 
2342
            revision_id)
1526
2343
        if response != ('ok',):
1527
2344
            raise errors.UnexpectedSmartServerResponse(response)
 
2345
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1528
2346
 
1529
2347
    @needs_write_lock
1530
2348
    def set_revision_history(self, rev_history):
1536
2354
        else:
1537
2355
            rev_id = rev_history[-1]
1538
2356
        self._set_last_revision(rev_id)
 
2357
        for hook in branch.Branch.hooks['set_rh']:
 
2358
            hook(self, rev_history)
1539
2359
        self._cache_revision_history(rev_history)
1540
2360
 
1541
 
    def get_parent(self):
1542
 
        self._ensure_real()
1543
 
        return self._real_branch.get_parent()
1544
 
        
1545
 
    def set_parent(self, url):
1546
 
        self._ensure_real()
1547
 
        return self._real_branch.set_parent(url)
1548
 
        
1549
 
    def sprout(self, to_bzrdir, revision_id=None):
1550
 
        # Like Branch.sprout, except that it sprouts a branch in the default
1551
 
        # format, because RemoteBranches can't be created at arbitrary URLs.
1552
 
        # XXX: if to_bzrdir is a RemoteBranch, this should perhaps do
1553
 
        # to_bzrdir.create_branch...
1554
 
        self._ensure_real()
1555
 
        result = self._real_branch._format.initialize(to_bzrdir)
1556
 
        self.copy_content_into(result, revision_id=revision_id)
1557
 
        result.set_parent(self.bzrdir.root_transport.base)
1558
 
        return result
 
2361
    def _get_parent_location(self):
 
2362
        medium = self._client._medium
 
2363
        if medium._is_remote_before((1, 13)):
 
2364
            return self._vfs_get_parent_location()
 
2365
        try:
 
2366
            response = self._call('Branch.get_parent', self._remote_path())
 
2367
        except errors.UnknownSmartMethod:
 
2368
            medium._remember_remote_is_before((1, 13))
 
2369
            return self._vfs_get_parent_location()
 
2370
        if len(response) != 1:
 
2371
            raise errors.UnexpectedSmartServerResponse(response)
 
2372
        parent_location = response[0]
 
2373
        if parent_location == '':
 
2374
            return None
 
2375
        return parent_location
 
2376
 
 
2377
    def _vfs_get_parent_location(self):
 
2378
        self._ensure_real()
 
2379
        return self._real_branch._get_parent_location()
 
2380
 
 
2381
    def _set_parent_location(self, url):
 
2382
        medium = self._client._medium
 
2383
        if medium._is_remote_before((1, 15)):
 
2384
            return self._vfs_set_parent_location(url)
 
2385
        try:
 
2386
            call_url = url or ''
 
2387
            if type(call_url) is not str:
 
2388
                raise AssertionError('url must be a str or None (%s)' % url)
 
2389
            response = self._call('Branch.set_parent_location',
 
2390
                self._remote_path(), self._lock_token, self._repo_lock_token,
 
2391
                call_url)
 
2392
        except errors.UnknownSmartMethod:
 
2393
            medium._remember_remote_is_before((1, 15))
 
2394
            return self._vfs_set_parent_location(url)
 
2395
        if response != ():
 
2396
            raise errors.UnexpectedSmartServerResponse(response)
 
2397
 
 
2398
    def _vfs_set_parent_location(self, url):
 
2399
        self._ensure_real()
 
2400
        return self._real_branch._set_parent_location(url)
1559
2401
 
1560
2402
    @needs_write_lock
1561
2403
    def pull(self, source, overwrite=False, stop_revision=None,
1562
2404
             **kwargs):
1563
 
        # FIXME: This asks the real branch to run the hooks, which means
1564
 
        # they're called with the wrong target branch parameter. 
1565
 
        # The test suite specifically allows this at present but it should be
1566
 
        # fixed.  It should get a _override_hook_target branch,
1567
 
        # as push does.  -- mbp 20070405
 
2405
        self._clear_cached_state_of_remote_branch_only()
1568
2406
        self._ensure_real()
1569
 
        self._real_branch.pull(
 
2407
        return self._real_branch.pull(
1570
2408
            source, overwrite=overwrite, stop_revision=stop_revision,
1571
 
            **kwargs)
 
2409
            _override_hook_target=self, **kwargs)
1572
2410
 
1573
2411
    @needs_read_lock
1574
2412
    def push(self, target, overwrite=False, stop_revision=None):
1580
2418
    def is_locked(self):
1581
2419
        return self._lock_count >= 1
1582
2420
 
 
2421
    @needs_read_lock
 
2422
    def revision_id_to_revno(self, revision_id):
 
2423
        self._ensure_real()
 
2424
        return self._real_branch.revision_id_to_revno(revision_id)
 
2425
 
1583
2426
    @needs_write_lock
1584
2427
    def set_last_revision_info(self, revno, revision_id):
 
2428
        # XXX: These should be returned by the set_last_revision_info verb
 
2429
        old_revno, old_revid = self.last_revision_info()
 
2430
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
1585
2431
        revision_id = ensure_null(revision_id)
1586
 
        path = self.bzrdir._path_for_remote_call(self._client)
1587
2432
        try:
1588
 
            response = self._client.call('Branch.set_last_revision_info',
1589
 
                path, self._lock_token, self._repo_lock_token, str(revno), revision_id)
 
2433
            response = self._call('Branch.set_last_revision_info',
 
2434
                self._remote_path(), self._lock_token, self._repo_lock_token,
 
2435
                str(revno), revision_id)
1590
2436
        except errors.UnknownSmartMethod:
1591
2437
            self._ensure_real()
1592
 
            self._clear_cached_state()
 
2438
            self._clear_cached_state_of_remote_branch_only()
1593
2439
            self._real_branch.set_last_revision_info(revno, revision_id)
1594
2440
            self._last_revision_info_cache = revno, revision_id
1595
2441
            return
1596
 
        except errors.ErrorFromSmartServer, err:
1597
 
            if err.error_verb == 'NoSuchRevision':
1598
 
                raise NoSuchRevision(self, err.error_args[0])
1599
 
            raise
1600
2442
        if response == ('ok',):
1601
2443
            self._clear_cached_state()
1602
2444
            self._last_revision_info_cache = revno, revision_id
 
2445
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2446
            # Update the _real_branch's cache too.
 
2447
            if self._real_branch is not None:
 
2448
                cache = self._last_revision_info_cache
 
2449
                self._real_branch._last_revision_info_cache = cache
1603
2450
        else:
1604
2451
            raise errors.UnexpectedSmartServerResponse(response)
1605
2452
 
 
2453
    @needs_write_lock
1606
2454
    def generate_revision_history(self, revision_id, last_rev=None,
1607
2455
                                  other_branch=None):
1608
 
#        self._ensure_real()
1609
 
#        return self._real_branch.generate_revision_history(
1610
 
#            revision_id, last_rev=last_rev, other_branch=other_branch)
1611
 
        self._set_last_revision(revision_id)
1612
 
        return # XXX
1613
 
        if last_rev is None and other_branch is None:
1614
 
            self._set_last_revision(revision_id)
1615
 
        else:
1616
 
            self._ensure_real()
1617
 
            return self._real_branch.generate_revision_history(
1618
 
                revision_id, last_rev=last_rev, other_branch=other_branch)
1619
 
 
1620
 
    @property
1621
 
    def tags(self):
1622
 
        self._ensure_real()
1623
 
        return self._real_branch.tags
 
2456
        medium = self._client._medium
 
2457
        if not medium._is_remote_before((1, 6)):
 
2458
            # Use a smart method for 1.6 and above servers
 
2459
            try:
 
2460
                self._set_last_revision_descendant(revision_id, other_branch,
 
2461
                    allow_diverged=True, allow_overwrite_descendant=True)
 
2462
                return
 
2463
            except errors.UnknownSmartMethod:
 
2464
                medium._remember_remote_is_before((1, 6))
 
2465
        self._clear_cached_state_of_remote_branch_only()
 
2466
        self.set_revision_history(self._lefthand_history(revision_id,
 
2467
            last_rev=last_rev,other_branch=other_branch))
1624
2468
 
1625
2469
    def set_push_location(self, location):
1626
2470
        self._ensure_real()
1627
2471
        return self._real_branch.set_push_location(location)
1628
2472
 
1629
 
    def update_revisions(self, other, stop_revision=None, overwrite=False):
1630
 
        mutter('RemoteBranch.update_revisions(%r, %s, %r)', 
1631
 
               other, stop_revision, overwrite)
1632
 
        if overwrite:
1633
 
            self._ensure_real()
1634
 
            return self._real_branch.update_revisions(
1635
 
                other, stop_revision=stop_revision, overwrite=True)
1636
 
        from bzrlib import revision as _mod_revision
1637
 
        other.lock_read()
 
2473
 
 
2474
class RemoteConfig(object):
 
2475
    """A Config that reads and writes from smart verbs.
 
2476
 
 
2477
    It is a low-level object that considers config data to be name/value pairs
 
2478
    that may be associated with a section. Assigning meaning to the these
 
2479
    values is done at higher levels like bzrlib.config.TreeConfig.
 
2480
    """
 
2481
 
 
2482
    def get_option(self, name, section=None, default=None):
 
2483
        """Return the value associated with a named option.
 
2484
 
 
2485
        :param name: The name of the value
 
2486
        :param section: The section the option is in (if any)
 
2487
        :param default: The value to return if the value is not set
 
2488
        :return: The value or default value
 
2489
        """
1638
2490
        try:
1639
 
            other_last_revno, other_last_revision = other.last_revision_info()
1640
 
            if stop_revision is None:
1641
 
                stop_revision = other_last_revision
1642
 
                if _mod_revision.is_null(stop_revision):
1643
 
                    # if there are no commits, we're done.
1644
 
                    return
1645
 
            # whats the current last revision, before we fetch [and change it
1646
 
            # possibly]
1647
 
            last_rev = _mod_revision.ensure_null(self.last_revision())
1648
 
            # we fetch here so that we don't process data twice in the common
1649
 
            # case of having something to pull, and so that the check for 
1650
 
            # already merged can operate on the just fetched graph, which will
1651
 
            # be cached in memory.
1652
 
            mutter('about to fetch %s from %r', stop_revision, other)
1653
 
            self.fetch(other, stop_revision)
1654
 
            # Check to see if one is an ancestor of the other
1655
 
            heads = self.repository.get_graph().heads([stop_revision,
1656
 
                                                       last_rev])
1657
 
            if heads == set([last_rev]):
1658
 
                # The current revision is a decendent of the target,
1659
 
                # nothing to do
1660
 
                return
1661
 
            elif heads == set([stop_revision, last_rev]):
1662
 
                # These branches have diverged
1663
 
                raise errors.DivergedBranches(self, other)
1664
 
            elif heads != set([stop_revision]):
1665
 
                raise AssertionError("invalid heads: %r" % heads)
1666
 
            if other_last_revision == stop_revision:
1667
 
                self.set_last_revision_info(other_last_revno,
1668
 
                                            other_last_revision)
 
2491
            configobj = self._get_configobj()
 
2492
            if section is None:
 
2493
                section_obj = configobj
1669
2494
            else:
1670
 
                self._set_last_revision(stop_revision)
1671
 
#                # TODO: jam 2007-11-29 Is there a way to determine the
1672
 
#                #       revno without searching all of history??
1673
 
#                self.generate_revision_history(stop_revision,
1674
 
#                    last_rev=last_rev, other_branch=other)
1675
 
        finally:
1676
 
            other.unlock()
1677
 
        
1678
 
        return
1679
 
        # XXX
1680
 
        self._ensure_real()
1681
 
        return self._real_branch.update_revisions(
1682
 
            other, stop_revision=stop_revision, overwrite=overwrite)
 
2495
                try:
 
2496
                    section_obj = configobj[section]
 
2497
                except KeyError:
 
2498
                    return default
 
2499
            return section_obj.get(name, default)
 
2500
        except errors.UnknownSmartMethod:
 
2501
            return self._vfs_get_option(name, section, default)
 
2502
 
 
2503
    def _response_to_configobj(self, response):
 
2504
        if len(response[0]) and response[0][0] != 'ok':
 
2505
            raise errors.UnexpectedSmartServerResponse(response)
 
2506
        lines = response[1].read_body_bytes().splitlines()
 
2507
        return config.ConfigObj(lines, encoding='utf-8')
 
2508
 
 
2509
 
 
2510
class RemoteBranchConfig(RemoteConfig):
 
2511
    """A RemoteConfig for Branches."""
 
2512
 
 
2513
    def __init__(self, branch):
 
2514
        self._branch = branch
 
2515
 
 
2516
    def _get_configobj(self):
 
2517
        path = self._branch._remote_path()
 
2518
        response = self._branch._client.call_expecting_body(
 
2519
            'Branch.get_config_file', path)
 
2520
        return self._response_to_configobj(response)
 
2521
 
 
2522
    def set_option(self, value, name, section=None):
 
2523
        """Set the value associated with a named option.
 
2524
 
 
2525
        :param value: The value to set
 
2526
        :param name: The name of the value to set
 
2527
        :param section: The section the option is in (if any)
 
2528
        """
 
2529
        medium = self._branch._client._medium
 
2530
        if medium._is_remote_before((1, 14)):
 
2531
            return self._vfs_set_option(value, name, section)
 
2532
        try:
 
2533
            path = self._branch._remote_path()
 
2534
            response = self._branch._client.call('Branch.set_config_option',
 
2535
                path, self._branch._lock_token, self._branch._repo_lock_token,
 
2536
                value.encode('utf8'), name, section or '')
 
2537
        except errors.UnknownSmartMethod:
 
2538
            medium._remember_remote_is_before((1, 14))
 
2539
            return self._vfs_set_option(value, name, section)
 
2540
        if response != ():
 
2541
            raise errors.UnexpectedSmartServerResponse(response)
 
2542
 
 
2543
    def _real_object(self):
 
2544
        self._branch._ensure_real()
 
2545
        return self._branch._real_branch
 
2546
 
 
2547
    def _vfs_set_option(self, value, name, section=None):
 
2548
        return self._real_object()._get_config().set_option(
 
2549
            value, name, section)
 
2550
 
 
2551
 
 
2552
class RemoteBzrDirConfig(RemoteConfig):
 
2553
    """A RemoteConfig for BzrDirs."""
 
2554
 
 
2555
    def __init__(self, bzrdir):
 
2556
        self._bzrdir = bzrdir
 
2557
 
 
2558
    def _get_configobj(self):
 
2559
        medium = self._bzrdir._client._medium
 
2560
        verb = 'BzrDir.get_config_file'
 
2561
        if medium._is_remote_before((1, 15)):
 
2562
            raise errors.UnknownSmartMethod(verb)
 
2563
        path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
 
2564
        response = self._bzrdir._call_expecting_body(
 
2565
            verb, path)
 
2566
        return self._response_to_configobj(response)
 
2567
 
 
2568
    def _vfs_get_option(self, name, section, default):
 
2569
        return self._real_object()._get_config().get_option(
 
2570
            name, section, default)
 
2571
 
 
2572
    def set_option(self, value, name, section=None):
 
2573
        """Set the value associated with a named option.
 
2574
 
 
2575
        :param value: The value to set
 
2576
        :param name: The name of the value to set
 
2577
        :param section: The section the option is in (if any)
 
2578
        """
 
2579
        return self._real_object()._get_config().set_option(
 
2580
            value, name, section)
 
2581
 
 
2582
    def _real_object(self):
 
2583
        self._bzrdir._ensure_real()
 
2584
        return self._bzrdir._real_bzrdir
 
2585
 
1683
2586
 
1684
2587
 
1685
2588
def _extract_tar(tar, to_dir):
1689
2592
    """
1690
2593
    for tarinfo in tar:
1691
2594
        tar.extract(tarinfo, to_dir)
 
2595
 
 
2596
 
 
2597
def _translate_error(err, **context):
 
2598
    """Translate an ErrorFromSmartServer into a more useful error.
 
2599
 
 
2600
    Possible context keys:
 
2601
      - branch
 
2602
      - repository
 
2603
      - bzrdir
 
2604
      - token
 
2605
      - other_branch
 
2606
      - path
 
2607
 
 
2608
    If the error from the server doesn't match a known pattern, then
 
2609
    UnknownErrorFromSmartServer is raised.
 
2610
    """
 
2611
    def find(name):
 
2612
        try:
 
2613
            return context[name]
 
2614
        except KeyError, key_err:
 
2615
            mutter('Missing key %r in context %r', key_err.args[0], context)
 
2616
            raise err
 
2617
    def get_path():
 
2618
        """Get the path from the context if present, otherwise use first error
 
2619
        arg.
 
2620
        """
 
2621
        try:
 
2622
            return context['path']
 
2623
        except KeyError, key_err:
 
2624
            try:
 
2625
                return err.error_args[0]
 
2626
            except IndexError, idx_err:
 
2627
                mutter(
 
2628
                    'Missing key %r in context %r', key_err.args[0], context)
 
2629
                raise err
 
2630
 
 
2631
    if err.error_verb == 'NoSuchRevision':
 
2632
        raise NoSuchRevision(find('branch'), err.error_args[0])
 
2633
    elif err.error_verb == 'nosuchrevision':
 
2634
        raise NoSuchRevision(find('repository'), err.error_args[0])
 
2635
    elif err.error_tuple == ('nobranch',):
 
2636
        raise errors.NotBranchError(path=find('bzrdir').root_transport.base)
 
2637
    elif err.error_verb == 'norepository':
 
2638
        raise errors.NoRepositoryPresent(find('bzrdir'))
 
2639
    elif err.error_verb == 'LockContention':
 
2640
        raise errors.LockContention('(remote lock)')
 
2641
    elif err.error_verb == 'UnlockableTransport':
 
2642
        raise errors.UnlockableTransport(find('bzrdir').root_transport)
 
2643
    elif err.error_verb == 'LockFailed':
 
2644
        raise errors.LockFailed(err.error_args[0], err.error_args[1])
 
2645
    elif err.error_verb == 'TokenMismatch':
 
2646
        raise errors.TokenMismatch(find('token'), '(remote token)')
 
2647
    elif err.error_verb == 'Diverged':
 
2648
        raise errors.DivergedBranches(find('branch'), find('other_branch'))
 
2649
    elif err.error_verb == 'TipChangeRejected':
 
2650
        raise errors.TipChangeRejected(err.error_args[0].decode('utf8'))
 
2651
    elif err.error_verb == 'UnstackableBranchFormat':
 
2652
        raise errors.UnstackableBranchFormat(*err.error_args)
 
2653
    elif err.error_verb == 'UnstackableRepositoryFormat':
 
2654
        raise errors.UnstackableRepositoryFormat(*err.error_args)
 
2655
    elif err.error_verb == 'NotStacked':
 
2656
        raise errors.NotStacked(branch=find('branch'))
 
2657
    elif err.error_verb == 'PermissionDenied':
 
2658
        path = get_path()
 
2659
        if len(err.error_args) >= 2:
 
2660
            extra = err.error_args[1]
 
2661
        else:
 
2662
            extra = None
 
2663
        raise errors.PermissionDenied(path, extra=extra)
 
2664
    elif err.error_verb == 'ReadError':
 
2665
        path = get_path()
 
2666
        raise errors.ReadError(path)
 
2667
    elif err.error_verb == 'NoSuchFile':
 
2668
        path = get_path()
 
2669
        raise errors.NoSuchFile(path)
 
2670
    elif err.error_verb == 'FileExists':
 
2671
        raise errors.FileExists(err.error_args[0])
 
2672
    elif err.error_verb == 'DirectoryNotEmpty':
 
2673
        raise errors.DirectoryNotEmpty(err.error_args[0])
 
2674
    elif err.error_verb == 'ShortReadvError':
 
2675
        args = err.error_args
 
2676
        raise errors.ShortReadvError(
 
2677
            args[0], int(args[1]), int(args[2]), int(args[3]))
 
2678
    elif err.error_verb in ('UnicodeEncodeError', 'UnicodeDecodeError'):
 
2679
        encoding = str(err.error_args[0]) # encoding must always be a string
 
2680
        val = err.error_args[1]
 
2681
        start = int(err.error_args[2])
 
2682
        end = int(err.error_args[3])
 
2683
        reason = str(err.error_args[4]) # reason must always be a string
 
2684
        if val.startswith('u:'):
 
2685
            val = val[2:].decode('utf-8')
 
2686
        elif val.startswith('s:'):
 
2687
            val = val[2:].decode('base64')
 
2688
        if err.error_verb == 'UnicodeDecodeError':
 
2689
            raise UnicodeDecodeError(encoding, val, start, end, reason)
 
2690
        elif err.error_verb == 'UnicodeEncodeError':
 
2691
            raise UnicodeEncodeError(encoding, val, start, end, reason)
 
2692
    elif err.error_verb == 'ReadOnlyError':
 
2693
        raise errors.TransportNotPossible('readonly transport')
 
2694
    raise errors.UnknownErrorFromSmartServer(err)