~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/remote.py

  • Committer: Martin Pool
  • Date: 2009-07-27 06:28:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4587.
  • Revision ID: mbp@sourcefrog.net-20090727062835-o66p8it658tq1sma
Add CountedLock.get_physical_lock_status

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
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
16
 
 
17
 
# TODO: At some point, handle upgrades by just passing the whole request
18
 
# across to run on the server.
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
16
 
20
17
import bz2
21
18
 
22
19
from bzrlib import (
 
20
    bencode,
23
21
    branch,
 
22
    bzrdir,
 
23
    config,
24
24
    debug,
25
25
    errors,
26
26
    graph,
 
27
    lock,
27
28
    lockdir,
28
29
    repository,
29
30
    revision,
 
31
    revision as _mod_revision,
30
32
    symbol_versioning,
31
 
    urlutils,
32
33
)
33
34
from bzrlib.branch import BranchReferenceFormat
34
35
from bzrlib.bzrdir import BzrDir, RemoteBzrDirFormat
38
39
    SmartProtocolError,
39
40
    )
40
41
from bzrlib.lockable_files import LockableFiles
41
 
from bzrlib.smart import client, vfs
 
42
from bzrlib.smart import client, vfs, repository as smart_repo
42
43
from bzrlib.revision import ensure_null, NULL_REVISION
43
44
from bzrlib.trace import mutter, note, warning
44
45
 
51
52
            return self._client.call(method, *args)
52
53
        except errors.ErrorFromSmartServer, err:
53
54
            self._translate_error(err, **err_context)
54
 
        
 
55
 
55
56
    def _call_expecting_body(self, method, *args, **err_context):
56
57
        try:
57
58
            return self._client.call_expecting_body(method, *args)
58
59
        except errors.ErrorFromSmartServer, err:
59
60
            self._translate_error(err, **err_context)
60
 
        
 
61
 
61
62
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
62
63
                                             **err_context):
63
64
        try:
65
66
                method, args, body_bytes)
66
67
        except errors.ErrorFromSmartServer, err:
67
68
            self._translate_error(err, **err_context)
68
 
        
 
69
 
 
70
 
 
71
def response_tuple_to_repo_format(response):
 
72
    """Convert a response tuple describing a repository format to a format."""
 
73
    format = RemoteRepositoryFormat()
 
74
    format._rich_root_data = (response[0] == 'yes')
 
75
    format._supports_tree_reference = (response[1] == 'yes')
 
76
    format._supports_external_lookups = (response[2] == 'yes')
 
77
    format._network_name = response[3]
 
78
    return format
 
79
 
 
80
 
69
81
# Note: RemoteBzrDirFormat is in bzrdir.py
70
82
 
71
83
class RemoteBzrDir(BzrDir, _RpcHelper):
72
84
    """Control directory on a remote server, accessed via bzr:// or similar."""
73
85
 
74
 
    def __init__(self, transport, _client=None):
 
86
    def __init__(self, transport, format, _client=None):
75
87
        """Construct a RemoteBzrDir.
76
88
 
77
89
        :param _client: Private parameter for testing. Disables probing and the
78
90
            use of a real bzrdir.
79
91
        """
80
 
        BzrDir.__init__(self, transport, RemoteBzrDirFormat())
 
92
        BzrDir.__init__(self, transport, format)
81
93
        # this object holds a delegated bzrdir that uses file-level operations
82
94
        # to talk to the other side
83
95
        self._real_bzrdir = None
 
96
        # 1-shot cache for the call pattern 'create_branch; open_branch' - see
 
97
        # create_branch for details.
 
98
        self._next_open_branch_result = None
84
99
 
85
100
        if _client is None:
86
101
            medium = transport.get_smart_medium()
104
119
        if not self._real_bzrdir:
105
120
            self._real_bzrdir = BzrDir.open_from_transport(
106
121
                self.root_transport, _server_formats=False)
 
122
            self._format._network_name = \
 
123
                self._real_bzrdir._format.network_name()
107
124
 
108
125
    def _translate_error(self, err, **context):
109
126
        _translate_error(err, bzrdir=self, **context)
110
127
 
111
 
    def cloning_metadir(self, stacked=False):
 
128
    def break_lock(self):
 
129
        # Prevent aliasing problems in the next_open_branch_result cache.
 
130
        # See create_branch for rationale.
 
131
        self._next_open_branch_result = None
 
132
        return BzrDir.break_lock(self)
 
133
 
 
134
    def _vfs_cloning_metadir(self, require_stacking=False):
112
135
        self._ensure_real()
113
 
        return self._real_bzrdir.cloning_metadir(stacked)
 
136
        return self._real_bzrdir.cloning_metadir(
 
137
            require_stacking=require_stacking)
 
138
 
 
139
    def cloning_metadir(self, require_stacking=False):
 
140
        medium = self._client._medium
 
141
        if medium._is_remote_before((1, 13)):
 
142
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
143
        verb = 'BzrDir.cloning_metadir'
 
144
        if require_stacking:
 
145
            stacking = 'True'
 
146
        else:
 
147
            stacking = 'False'
 
148
        path = self._path_for_remote_call(self._client)
 
149
        try:
 
150
            response = self._call(verb, path, stacking)
 
151
        except errors.UnknownSmartMethod:
 
152
            medium._remember_remote_is_before((1, 13))
 
153
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
154
        except errors.UnknownErrorFromSmartServer, err:
 
155
            if err.error_tuple != ('BranchReference',):
 
156
                raise
 
157
            # We need to resolve the branch reference to determine the
 
158
            # cloning_metadir.  This causes unnecessary RPCs to open the
 
159
            # referenced branch (and bzrdir, etc) but only when the caller
 
160
            # didn't already resolve the branch reference.
 
161
            referenced_branch = self.open_branch()
 
162
            return referenced_branch.bzrdir.cloning_metadir()
 
163
        if len(response) != 3:
 
164
            raise errors.UnexpectedSmartServerResponse(response)
 
165
        control_name, repo_name, branch_info = response
 
166
        if len(branch_info) != 2:
 
167
            raise errors.UnexpectedSmartServerResponse(response)
 
168
        branch_ref, branch_name = branch_info
 
169
        format = bzrdir.network_format_registry.get(control_name)
 
170
        if repo_name:
 
171
            format.repository_format = repository.network_format_registry.get(
 
172
                repo_name)
 
173
        if branch_ref == 'ref':
 
174
            # XXX: we need possible_transports here to avoid reopening the
 
175
            # connection to the referenced location
 
176
            ref_bzrdir = BzrDir.open(branch_name)
 
177
            branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
 
178
            format.set_branch_format(branch_format)
 
179
        elif branch_ref == 'branch':
 
180
            if branch_name:
 
181
                format.set_branch_format(
 
182
                    branch.network_format_registry.get(branch_name))
 
183
        else:
 
184
            raise errors.UnexpectedSmartServerResponse(response)
 
185
        return format
114
186
 
115
187
    def create_repository(self, shared=False):
116
 
        self._ensure_real()
117
 
        self._real_bzrdir.create_repository(shared=shared)
118
 
        return self.open_repository()
 
188
        # as per meta1 formats - just delegate to the format object which may
 
189
        # be parameterised.
 
190
        result = self._format.repository_format.initialize(self, shared)
 
191
        if not isinstance(result, RemoteRepository):
 
192
            return self.open_repository()
 
193
        else:
 
194
            return result
119
195
 
120
196
    def destroy_repository(self):
121
197
        """See BzrDir.destroy_repository"""
123
199
        self._real_bzrdir.destroy_repository()
124
200
 
125
201
    def create_branch(self):
126
 
        self._ensure_real()
127
 
        real_branch = self._real_bzrdir.create_branch()
128
 
        return RemoteBranch(self, self.find_repository(), real_branch)
 
202
        # as per meta1 formats - just delegate to the format object which may
 
203
        # be parameterised.
 
204
        real_branch = self._format.get_branch_format().initialize(self)
 
205
        if not isinstance(real_branch, RemoteBranch):
 
206
            result = RemoteBranch(self, self.find_repository(), real_branch)
 
207
        else:
 
208
            result = real_branch
 
209
        # BzrDir.clone_on_transport() uses the result of create_branch but does
 
210
        # not return it to its callers; we save approximately 8% of our round
 
211
        # trips by handing the branch we created back to the first caller to
 
212
        # open_branch rather than probing anew. Long term we need a API in
 
213
        # bzrdir that doesn't discard result objects (like result_branch).
 
214
        # RBC 20090225
 
215
        self._next_open_branch_result = result
 
216
        return result
129
217
 
130
218
    def destroy_branch(self):
131
219
        """See BzrDir.destroy_branch"""
132
220
        self._ensure_real()
133
221
        self._real_bzrdir.destroy_branch()
 
222
        self._next_open_branch_result = None
134
223
 
135
224
    def create_workingtree(self, revision_id=None, from_branch=None):
136
225
        raise errors.NotLocalUrl(self.transport.base)
145
234
 
146
235
    def get_branch_reference(self):
147
236
        """See BzrDir.get_branch_reference()."""
 
237
        response = self._get_branch_reference()
 
238
        if response[0] == 'ref':
 
239
            return response[1]
 
240
        else:
 
241
            return None
 
242
 
 
243
    def _get_branch_reference(self):
148
244
        path = self._path_for_remote_call(self._client)
 
245
        medium = self._client._medium
 
246
        if not medium._is_remote_before((1, 13)):
 
247
            try:
 
248
                response = self._call('BzrDir.open_branchV2', path)
 
249
                if response[0] not in ('ref', 'branch'):
 
250
                    raise errors.UnexpectedSmartServerResponse(response)
 
251
                return response
 
252
            except errors.UnknownSmartMethod:
 
253
                medium._remember_remote_is_before((1, 13))
149
254
        response = self._call('BzrDir.open_branch', path)
150
 
        if response[0] == 'ok':
151
 
            if response[1] == '':
152
 
                # branch at this location.
153
 
                return None
154
 
            else:
155
 
                # a branch reference, use the existing BranchReference logic.
156
 
                return response[1]
 
255
        if response[0] != 'ok':
 
256
            raise errors.UnexpectedSmartServerResponse(response)
 
257
        if response[1] != '':
 
258
            return ('ref', response[1])
157
259
        else:
158
 
            raise errors.UnexpectedSmartServerResponse(response)
 
260
            return ('branch', '')
159
261
 
160
262
    def _get_tree_branch(self):
161
263
        """See BzrDir._get_tree_branch()."""
162
264
        return None, self.open_branch()
163
265
 
164
 
    def open_branch(self, _unsupported=False):
 
266
    def open_branch(self, _unsupported=False, ignore_fallbacks=False):
165
267
        if _unsupported:
166
268
            raise NotImplementedError('unsupported flag support not implemented yet.')
167
 
        reference_url = self.get_branch_reference()
168
 
        if reference_url is None:
169
 
            # branch at this location.
170
 
            return RemoteBranch(self, self.find_repository())
171
 
        else:
 
269
        if self._next_open_branch_result is not None:
 
270
            # See create_branch for details.
 
271
            result = self._next_open_branch_result
 
272
            self._next_open_branch_result = None
 
273
            return result
 
274
        response = self._get_branch_reference()
 
275
        if response[0] == 'ref':
172
276
            # a branch reference, use the existing BranchReference logic.
173
277
            format = BranchReferenceFormat()
174
 
            return format.open(self, _found=True, location=reference_url)
175
 
                
 
278
            return format.open(self, _found=True, location=response[1],
 
279
                ignore_fallbacks=ignore_fallbacks)
 
280
        branch_format_name = response[1]
 
281
        if not branch_format_name:
 
282
            branch_format_name = None
 
283
        format = RemoteBranchFormat(network_name=branch_format_name)
 
284
        return RemoteBranch(self, self.find_repository(), format=format,
 
285
            setup_stacking=not ignore_fallbacks)
 
286
 
 
287
    def _open_repo_v1(self, path):
 
288
        verb = 'BzrDir.find_repository'
 
289
        response = self._call(verb, path)
 
290
        if response[0] != 'ok':
 
291
            raise errors.UnexpectedSmartServerResponse(response)
 
292
        # servers that only support the v1 method don't support external
 
293
        # references either.
 
294
        self._ensure_real()
 
295
        repo = self._real_bzrdir.open_repository()
 
296
        response = response + ('no', repo._format.network_name())
 
297
        return response, repo
 
298
 
 
299
    def _open_repo_v2(self, path):
 
300
        verb = 'BzrDir.find_repositoryV2'
 
301
        response = self._call(verb, path)
 
302
        if response[0] != 'ok':
 
303
            raise errors.UnexpectedSmartServerResponse(response)
 
304
        self._ensure_real()
 
305
        repo = self._real_bzrdir.open_repository()
 
306
        response = response + (repo._format.network_name(),)
 
307
        return response, repo
 
308
 
 
309
    def _open_repo_v3(self, path):
 
310
        verb = 'BzrDir.find_repositoryV3'
 
311
        medium = self._client._medium
 
312
        if medium._is_remote_before((1, 13)):
 
313
            raise errors.UnknownSmartMethod(verb)
 
314
        try:
 
315
            response = self._call(verb, path)
 
316
        except errors.UnknownSmartMethod:
 
317
            medium._remember_remote_is_before((1, 13))
 
318
            raise
 
319
        if response[0] != 'ok':
 
320
            raise errors.UnexpectedSmartServerResponse(response)
 
321
        return response, None
 
322
 
176
323
    def open_repository(self):
177
324
        path = self._path_for_remote_call(self._client)
178
 
        verb = 'BzrDir.find_repositoryV2'
179
 
        try:
180
 
            response = self._call(verb, path)
181
 
        except errors.UnknownSmartMethod:
182
 
            verb = 'BzrDir.find_repository'
183
 
            response = self._call(verb, path)
 
325
        response = None
 
326
        for probe in [self._open_repo_v3, self._open_repo_v2,
 
327
            self._open_repo_v1]:
 
328
            try:
 
329
                response, real_repo = probe(path)
 
330
                break
 
331
            except errors.UnknownSmartMethod:
 
332
                pass
 
333
        if response is None:
 
334
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
184
335
        if response[0] != 'ok':
185
336
            raise errors.UnexpectedSmartServerResponse(response)
186
 
        if verb == 'BzrDir.find_repository':
187
 
            # servers that don't support the V2 method don't support external
188
 
            # references either.
189
 
            response = response + ('no', )
190
 
        if not (len(response) == 5):
 
337
        if len(response) != 6:
191
338
            raise SmartProtocolError('incorrect response length %s' % (response,))
192
339
        if response[1] == '':
193
 
            format = RemoteRepositoryFormat()
194
 
            format.rich_root_data = (response[2] == 'yes')
195
 
            format.supports_tree_reference = (response[3] == 'yes')
196
 
            # No wire format to check this yet.
197
 
            format.supports_external_lookups = (response[4] == 'yes')
 
340
            # repo is at this dir.
 
341
            format = response_tuple_to_repo_format(response[2:])
198
342
            # Used to support creating a real format instance when needed.
199
343
            format._creating_bzrdir = self
200
 
            return RemoteRepository(self, format)
 
344
            remote_repo = RemoteRepository(self, format)
 
345
            format._creating_repo = remote_repo
 
346
            if real_repo is not None:
 
347
                remote_repo._set_real_repository(real_repo)
 
348
            return remote_repo
201
349
        else:
202
350
            raise errors.NoRepositoryPresent(self)
203
351
 
241
389
        return self._real_bzrdir.clone(url, revision_id=revision_id,
242
390
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
243
391
 
244
 
    def get_config(self):
245
 
        self._ensure_real()
246
 
        return self._real_bzrdir.get_config()
 
392
    def _get_config(self):
 
393
        return RemoteBzrDirConfig(self)
247
394
 
248
395
 
249
396
class RemoteRepositoryFormat(repository.RepositoryFormat):
257
404
    the attributes rich_root_data and supports_tree_reference are set
258
405
    on a per instance basis, and are not set (and should not be) at
259
406
    the class level.
 
407
 
 
408
    :ivar _custom_format: If set, a specific concrete repository format that
 
409
        will be used when initializing a repository with this
 
410
        RemoteRepositoryFormat.
 
411
    :ivar _creating_repo: If set, the repository object that this
 
412
        RemoteRepositoryFormat was created for: it can be called into
 
413
        to obtain data like the network name.
260
414
    """
261
415
 
262
416
    _matchingbzrdir = RemoteBzrDirFormat()
263
417
 
264
 
    def initialize(self, a_bzrdir, shared=False):
265
 
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
418
    def __init__(self):
 
419
        repository.RepositoryFormat.__init__(self)
 
420
        self._custom_format = None
 
421
        self._network_name = None
 
422
        self._creating_bzrdir = None
 
423
        self._supports_external_lookups = None
 
424
        self._supports_tree_reference = None
 
425
        self._rich_root_data = None
 
426
 
 
427
    @property
 
428
    def fast_deltas(self):
 
429
        self._ensure_real()
 
430
        return self._custom_format.fast_deltas
 
431
 
 
432
    @property
 
433
    def rich_root_data(self):
 
434
        if self._rich_root_data is None:
 
435
            self._ensure_real()
 
436
            self._rich_root_data = self._custom_format.rich_root_data
 
437
        return self._rich_root_data
 
438
 
 
439
    @property
 
440
    def supports_external_lookups(self):
 
441
        if self._supports_external_lookups is None:
 
442
            self._ensure_real()
 
443
            self._supports_external_lookups = \
 
444
                self._custom_format.supports_external_lookups
 
445
        return self._supports_external_lookups
 
446
 
 
447
    @property
 
448
    def supports_tree_reference(self):
 
449
        if self._supports_tree_reference is None:
 
450
            self._ensure_real()
 
451
            self._supports_tree_reference = \
 
452
                self._custom_format.supports_tree_reference
 
453
        return self._supports_tree_reference
 
454
 
 
455
    def _vfs_initialize(self, a_bzrdir, shared):
 
456
        """Helper for common code in initialize."""
 
457
        if self._custom_format:
 
458
            # Custom format requested
 
459
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
 
460
        elif self._creating_bzrdir is not None:
 
461
            # Use the format that the repository we were created to back
 
462
            # has.
266
463
            prior_repo = self._creating_bzrdir.open_repository()
267
464
            prior_repo._ensure_real()
268
 
            return prior_repo._real_repository._format.initialize(
 
465
            result = prior_repo._real_repository._format.initialize(
269
466
                a_bzrdir, shared=shared)
270
 
        return a_bzrdir.create_repository(shared=shared)
271
 
    
 
467
        else:
 
468
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
 
469
            # support remote initialization.
 
470
            # We delegate to a real object at this point (as RemoteBzrDir
 
471
            # delegate to the repository format which would lead to infinite
 
472
            # recursion if we just called a_bzrdir.create_repository.
 
473
            a_bzrdir._ensure_real()
 
474
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
 
475
        if not isinstance(result, RemoteRepository):
 
476
            return self.open(a_bzrdir)
 
477
        else:
 
478
            return result
 
479
 
 
480
    def initialize(self, a_bzrdir, shared=False):
 
481
        # Being asked to create on a non RemoteBzrDir:
 
482
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
483
            return self._vfs_initialize(a_bzrdir, shared)
 
484
        medium = a_bzrdir._client._medium
 
485
        if medium._is_remote_before((1, 13)):
 
486
            return self._vfs_initialize(a_bzrdir, shared)
 
487
        # Creating on a remote bzr dir.
 
488
        # 1) get the network name to use.
 
489
        if self._custom_format:
 
490
            network_name = self._custom_format.network_name()
 
491
        elif self._network_name:
 
492
            network_name = self._network_name
 
493
        else:
 
494
            # Select the current bzrlib default and ask for that.
 
495
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
496
            reference_format = reference_bzrdir_format.repository_format
 
497
            network_name = reference_format.network_name()
 
498
        # 2) try direct creation via RPC
 
499
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
500
        verb = 'BzrDir.create_repository'
 
501
        if shared:
 
502
            shared_str = 'True'
 
503
        else:
 
504
            shared_str = 'False'
 
505
        try:
 
506
            response = a_bzrdir._call(verb, path, network_name, shared_str)
 
507
        except errors.UnknownSmartMethod:
 
508
            # Fallback - use vfs methods
 
509
            medium._remember_remote_is_before((1, 13))
 
510
            return self._vfs_initialize(a_bzrdir, shared)
 
511
        else:
 
512
            # Turn the response into a RemoteRepository object.
 
513
            format = response_tuple_to_repo_format(response[1:])
 
514
            # Used to support creating a real format instance when needed.
 
515
            format._creating_bzrdir = a_bzrdir
 
516
            remote_repo = RemoteRepository(a_bzrdir, format)
 
517
            format._creating_repo = remote_repo
 
518
            return remote_repo
 
519
 
272
520
    def open(self, a_bzrdir):
273
521
        if not isinstance(a_bzrdir, RemoteBzrDir):
274
522
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
275
523
        return a_bzrdir.open_repository()
276
524
 
 
525
    def _ensure_real(self):
 
526
        if self._custom_format is None:
 
527
            self._custom_format = repository.network_format_registry.get(
 
528
                self._network_name)
 
529
 
 
530
    @property
 
531
    def _fetch_order(self):
 
532
        self._ensure_real()
 
533
        return self._custom_format._fetch_order
 
534
 
 
535
    @property
 
536
    def _fetch_uses_deltas(self):
 
537
        self._ensure_real()
 
538
        return self._custom_format._fetch_uses_deltas
 
539
 
 
540
    @property
 
541
    def _fetch_reconcile(self):
 
542
        self._ensure_real()
 
543
        return self._custom_format._fetch_reconcile
 
544
 
277
545
    def get_format_description(self):
278
546
        return 'bzr remote repository'
279
547
 
280
548
    def __eq__(self, other):
281
 
        return self.__class__ == other.__class__
 
549
        return self.__class__ is other.__class__
282
550
 
283
551
    def check_conversion_target(self, target_format):
284
552
        if self.rich_root_data and not target_format.rich_root_data:
289
557
            raise errors.BadConversionTarget(
290
558
                'Does not support nested trees', target_format)
291
559
 
 
560
    def network_name(self):
 
561
        if self._network_name:
 
562
            return self._network_name
 
563
        self._creating_repo._ensure_real()
 
564
        return self._creating_repo._real_repository._format.network_name()
 
565
 
 
566
    @property
 
567
    def pack_compresses(self):
 
568
        self._ensure_real()
 
569
        return self._custom_format.pack_compresses
 
570
 
 
571
    @property
 
572
    def _serializer(self):
 
573
        self._ensure_real()
 
574
        return self._custom_format._serializer
 
575
 
292
576
 
293
577
class RemoteRepository(_RpcHelper):
294
578
    """Repository accessed over rpc.
299
583
 
300
584
    def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
301
585
        """Create a RemoteRepository instance.
302
 
        
 
586
 
303
587
        :param remote_bzrdir: The bzrdir hosting this repository.
304
588
        :param format: The RemoteFormat object to use.
305
589
        :param real_repository: If not None, a local implementation of the
322
606
        self._lock_token = None
323
607
        self._lock_count = 0
324
608
        self._leave_lock = False
 
609
        # Cache of revision parents; misses are cached during read locks, and
 
610
        # write locks when no _real_repository has been set.
325
611
        self._unstacked_provider = graph.CachingParentsProvider(
326
612
            get_parent_map=self._get_parent_map_rpc)
327
613
        self._unstacked_provider.disable_cache()
344
630
 
345
631
    def abort_write_group(self, suppress_errors=False):
346
632
        """Complete a write group on the decorated repository.
347
 
        
348
 
        Smart methods peform operations in a single step so this api
 
633
 
 
634
        Smart methods perform operations in a single step so this API
349
635
        is not really applicable except as a compatibility thunk
350
636
        for older plugins that don't use e.g. the CommitBuilder
351
637
        facility.
356
642
        return self._real_repository.abort_write_group(
357
643
            suppress_errors=suppress_errors)
358
644
 
 
645
    @property
 
646
    def chk_bytes(self):
 
647
        """Decorate the real repository for now.
 
648
 
 
649
        In the long term a full blown network facility is needed to avoid
 
650
        creating a real repository object locally.
 
651
        """
 
652
        self._ensure_real()
 
653
        return self._real_repository.chk_bytes
 
654
 
359
655
    def commit_write_group(self):
360
656
        """Complete a write group on the decorated repository.
361
 
        
362
 
        Smart methods peform operations in a single step so this api
 
657
 
 
658
        Smart methods perform operations in a single step so this API
363
659
        is not really applicable except as a compatibility thunk
364
660
        for older plugins that don't use e.g. the CommitBuilder
365
661
        facility.
367
663
        self._ensure_real()
368
664
        return self._real_repository.commit_write_group()
369
665
 
 
666
    def resume_write_group(self, tokens):
 
667
        self._ensure_real()
 
668
        return self._real_repository.resume_write_group(tokens)
 
669
 
 
670
    def suspend_write_group(self):
 
671
        self._ensure_real()
 
672
        return self._real_repository.suspend_write_group()
 
673
 
 
674
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
675
        self._ensure_real()
 
676
        return self._real_repository.get_missing_parent_inventories(
 
677
            check_for_missing_texts=check_for_missing_texts)
 
678
 
 
679
    def _get_rev_id_for_revno_vfs(self, revno, known_pair):
 
680
        self._ensure_real()
 
681
        return self._real_repository.get_rev_id_for_revno(
 
682
            revno, known_pair)
 
683
 
 
684
    def get_rev_id_for_revno(self, revno, known_pair):
 
685
        """See Repository.get_rev_id_for_revno."""
 
686
        path = self.bzrdir._path_for_remote_call(self._client)
 
687
        try:
 
688
            if self._client._medium._is_remote_before((1, 17)):
 
689
                return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
690
            response = self._call(
 
691
                'Repository.get_rev_id_for_revno', path, revno, known_pair)
 
692
        except errors.UnknownSmartMethod:
 
693
            self._client._medium._remember_remote_is_before((1, 17))
 
694
            return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
695
        if response[0] == 'ok':
 
696
            return True, response[1]
 
697
        elif response[0] == 'history-incomplete':
 
698
            known_pair = response[1:3]
 
699
            for fallback in self._fallback_repositories:
 
700
                found, result = fallback.get_rev_id_for_revno(revno, known_pair)
 
701
                if found:
 
702
                    return True, result
 
703
                else:
 
704
                    known_pair = result
 
705
            # Not found in any fallbacks
 
706
            return False, known_pair
 
707
        else:
 
708
            raise errors.UnexpectedSmartServerResponse(response)
 
709
 
370
710
    def _ensure_real(self):
371
711
        """Ensure that there is a _real_repository set.
372
712
 
373
713
        Used before calls to self._real_repository.
 
714
 
 
715
        Note that _ensure_real causes many roundtrips to the server which are
 
716
        not desirable, and prevents the use of smart one-roundtrip RPC's to
 
717
        perform complex operations (such as accessing parent data, streaming
 
718
        revisions etc). Adding calls to _ensure_real should only be done when
 
719
        bringing up new functionality, adding fallbacks for smart methods that
 
720
        require a fallback path, and never to replace an existing smart method
 
721
        invocation. If in doubt chat to the bzr network team.
374
722
        """
375
723
        if self._real_repository is None:
 
724
            if 'hpssvfs' in debug.debug_flags:
 
725
                import traceback
 
726
                warning('VFS Repository access triggered\n%s',
 
727
                    ''.join(traceback.format_stack()))
 
728
            self._unstacked_provider.missing_keys.clear()
376
729
            self.bzrdir._ensure_real()
377
730
            self._set_real_repository(
378
731
                self.bzrdir._real_bzrdir.open_repository())
405
758
        self._ensure_real()
406
759
        return self._real_repository._generate_text_key_index()
407
760
 
408
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_four)
409
 
    def get_revision_graph(self, revision_id=None):
410
 
        """See Repository.get_revision_graph()."""
411
 
        return self._get_revision_graph(revision_id)
412
 
 
413
761
    def _get_revision_graph(self, revision_id):
414
762
        """Private method for using with old (< 1.2) servers to fallback."""
415
763
        if revision_id is None:
432
780
        for line in lines:
433
781
            d = tuple(line.split())
434
782
            revision_graph[d[0]] = d[1:]
435
 
            
 
783
 
436
784
        return revision_graph
437
785
 
 
786
    def _get_sink(self):
 
787
        """See Repository._get_sink()."""
 
788
        return RemoteStreamSink(self)
 
789
 
 
790
    def _get_source(self, to_format):
 
791
        """Return a source for streaming from this repository."""
 
792
        return RemoteStreamSource(self, to_format)
 
793
 
 
794
    @needs_read_lock
438
795
    def has_revision(self, revision_id):
439
 
        """See Repository.has_revision()."""
440
 
        if revision_id == NULL_REVISION:
441
 
            # The null revision is always present.
442
 
            return True
443
 
        path = self.bzrdir._path_for_remote_call(self._client)
444
 
        response = self._call('Repository.has_revision', path, revision_id)
445
 
        if response[0] not in ('yes', 'no'):
446
 
            raise errors.UnexpectedSmartServerResponse(response)
447
 
        if response[0] == 'yes':
448
 
            return True
449
 
        for fallback_repo in self._fallback_repositories:
450
 
            if fallback_repo.has_revision(revision_id):
451
 
                return True
452
 
        return False
 
796
        """True if this repository has a copy of the revision."""
 
797
        # Copy of bzrlib.repository.Repository.has_revision
 
798
        return revision_id in self.has_revisions((revision_id,))
453
799
 
 
800
    @needs_read_lock
454
801
    def has_revisions(self, revision_ids):
455
 
        """See Repository.has_revisions()."""
456
 
        # FIXME: This does many roundtrips, particularly when there are
457
 
        # fallback repositories.  -- mbp 20080905
458
 
        result = set()
459
 
        for revision_id in revision_ids:
460
 
            if self.has_revision(revision_id):
461
 
                result.add(revision_id)
 
802
        """Probe to find out the presence of multiple revisions.
 
803
 
 
804
        :param revision_ids: An iterable of revision_ids.
 
805
        :return: A set of the revision_ids that were present.
 
806
        """
 
807
        # Copy of bzrlib.repository.Repository.has_revisions
 
808
        parent_map = self.get_parent_map(revision_ids)
 
809
        result = set(parent_map)
 
810
        if _mod_revision.NULL_REVISION in revision_ids:
 
811
            result.add(_mod_revision.NULL_REVISION)
462
812
        return result
463
813
 
 
814
    def _has_same_fallbacks(self, other_repo):
 
815
        """Returns true if the repositories have the same fallbacks."""
 
816
        # XXX: copied from Repository; it should be unified into a base class
 
817
        # <https://bugs.edge.launchpad.net/bzr/+bug/401622>
 
818
        my_fb = self._fallback_repositories
 
819
        other_fb = other_repo._fallback_repositories
 
820
        if len(my_fb) != len(other_fb):
 
821
            return False
 
822
        for f, g in zip(my_fb, other_fb):
 
823
            if not f.has_same_location(g):
 
824
                return False
 
825
        return True
 
826
 
464
827
    def has_same_location(self, other):
465
 
        return (self.__class__ == other.__class__ and
 
828
        # TODO: Move to RepositoryBase and unify with the regular Repository
 
829
        # one; unfortunately the tests rely on slightly different behaviour at
 
830
        # present -- mbp 20090710
 
831
        return (self.__class__ is other.__class__ and
466
832
                self.bzrdir.transport.base == other.bzrdir.transport.base)
467
833
 
468
834
    def get_graph(self, other_repository=None):
540
906
        if not self._lock_mode:
541
907
            self._lock_mode = 'r'
542
908
            self._lock_count = 1
543
 
            self._unstacked_provider.enable_cache(cache_misses=False)
 
909
            self._unstacked_provider.enable_cache(cache_misses=True)
544
910
            if self._real_repository is not None:
545
911
                self._real_repository.lock_read()
 
912
            for repo in self._fallback_repositories:
 
913
                repo.lock_read()
546
914
        else:
547
915
            self._lock_count += 1
548
916
 
580
948
                self._leave_lock = False
581
949
            self._lock_mode = 'w'
582
950
            self._lock_count = 1
583
 
            self._unstacked_provider.enable_cache(cache_misses=False)
 
951
            cache_misses = self._real_repository is None
 
952
            self._unstacked_provider.enable_cache(cache_misses=cache_misses)
 
953
            for repo in self._fallback_repositories:
 
954
                # Writes don't affect fallback repos
 
955
                repo.lock_read()
584
956
        elif self._lock_mode == 'r':
585
957
            raise errors.ReadOnlyError(self)
586
958
        else:
604
976
            implemented operations.
605
977
        """
606
978
        if self._real_repository is not None:
607
 
            raise AssertionError('_real_repository is already set')
 
979
            # Replacing an already set real repository.
 
980
            # We cannot do this [currently] if the repository is locked -
 
981
            # synchronised state might be lost.
 
982
            if self.is_locked():
 
983
                raise AssertionError('_real_repository is already set')
608
984
        if isinstance(repository, RemoteRepository):
609
985
            raise AssertionError()
610
986
        self._real_repository = repository
 
987
        # three code paths happen here:
 
988
        # 1) old servers, RemoteBranch.open() calls _ensure_real before setting
 
989
        # up stacking. In this case self._fallback_repositories is [], and the
 
990
        # real repo is already setup. Preserve the real repo and
 
991
        # RemoteRepository.add_fallback_repository will avoid adding
 
992
        # duplicates.
 
993
        # 2) new servers, RemoteBranch.open() sets up stacking, and when
 
994
        # ensure_real is triggered from a branch, the real repository to
 
995
        # set already has a matching list with separate instances, but
 
996
        # as they are also RemoteRepositories we don't worry about making the
 
997
        # lists be identical.
 
998
        # 3) new servers, RemoteRepository.ensure_real is triggered before
 
999
        # RemoteBranch.ensure real, in this case we get a repo with no fallbacks
 
1000
        # and need to populate it.
 
1001
        if (self._fallback_repositories and
 
1002
            len(self._real_repository._fallback_repositories) !=
 
1003
            len(self._fallback_repositories)):
 
1004
            if len(self._real_repository._fallback_repositories):
 
1005
                raise AssertionError(
 
1006
                    "cannot cleanly remove existing _fallback_repositories")
611
1007
        for fb in self._fallback_repositories:
612
1008
            self._real_repository.add_fallback_repository(fb)
613
1009
        if self._lock_mode == 'w':
619
1015
 
620
1016
    def start_write_group(self):
621
1017
        """Start a write group on the decorated repository.
622
 
        
623
 
        Smart methods peform operations in a single step so this api
 
1018
 
 
1019
        Smart methods perform operations in a single step so this API
624
1020
        is not really applicable except as a compatibility thunk
625
1021
        for older plugins that don't use e.g. the CommitBuilder
626
1022
        facility.
642
1038
            raise errors.UnexpectedSmartServerResponse(response)
643
1039
 
644
1040
    def unlock(self):
 
1041
        if not self._lock_count:
 
1042
            return lock.cant_unlock_not_held(self)
645
1043
        self._lock_count -= 1
646
1044
        if self._lock_count > 0:
647
1045
            return
661
1059
            # problem releasing the vfs-based lock.
662
1060
            if old_mode == 'w':
663
1061
                # Only write-locked repositories need to make a remote method
664
 
                # call to perfom the unlock.
 
1062
                # call to perform the unlock.
665
1063
                old_token = self._lock_token
666
1064
                self._lock_token = None
667
1065
                if not self._leave_lock:
668
1066
                    self._unlock(old_token)
 
1067
        # Fallbacks are always 'lock_read()' so we don't pay attention to
 
1068
        # self._leave_lock
 
1069
        for repo in self._fallback_repositories:
 
1070
            repo.unlock()
669
1071
 
670
1072
    def break_lock(self):
671
1073
        # should hand off to the network
674
1076
 
675
1077
    def _get_tarball(self, compression):
676
1078
        """Return a TemporaryFile containing a repository tarball.
677
 
        
 
1079
 
678
1080
        Returns None if the server does not support sending tarballs.
679
1081
        """
680
1082
        import tempfile
726
1128
 
727
1129
    def add_fallback_repository(self, repository):
728
1130
        """Add a repository to use for looking up data not held locally.
729
 
        
 
1131
 
730
1132
        :param repository: A repository.
731
1133
        """
732
 
        # XXX: At the moment the RemoteRepository will allow fallbacks
733
 
        # unconditionally - however, a _real_repository will usually exist,
734
 
        # and may raise an error if it's not accommodated by the underlying
735
 
        # format.  Eventually we should check when opening the repository
736
 
        # whether it's willing to allow them or not.
737
 
        #
 
1134
        if not self._format.supports_external_lookups:
 
1135
            raise errors.UnstackableRepositoryFormat(
 
1136
                self._format.network_name(), self.base)
738
1137
        # We need to accumulate additional repositories here, to pass them in
739
1138
        # on various RPC's.
 
1139
        #
 
1140
        if self.is_locked():
 
1141
            # We will call fallback.unlock() when we transition to the unlocked
 
1142
            # state, so always add a lock here. If a caller passes us a locked
 
1143
            # repository, they are responsible for unlocking it later.
 
1144
            repository.lock_read()
740
1145
        self._fallback_repositories.append(repository)
741
 
        # They are also seen by the fallback repository.  If it doesn't exist
742
 
        # yet they'll be added then.  This implicitly copies them.
743
 
        self._ensure_real()
 
1146
        # If self._real_repository was parameterised already (e.g. because a
 
1147
        # _real_branch had its get_stacked_on_url method called), then the
 
1148
        # repository to be added may already be in the _real_repositories list.
 
1149
        if self._real_repository is not None:
 
1150
            fallback_locations = [repo.bzrdir.root_transport.base for repo in
 
1151
                self._real_repository._fallback_repositories]
 
1152
            if repository.bzrdir.root_transport.base not in fallback_locations:
 
1153
                self._real_repository.add_fallback_repository(repository)
744
1154
 
745
1155
    def add_inventory(self, revid, inv, parents):
746
1156
        self._ensure_real()
785
1195
        self._ensure_real()
786
1196
        return self._real_repository.make_working_trees()
787
1197
 
 
1198
    def refresh_data(self):
 
1199
        """Re-read any data needed to to synchronise with disk.
 
1200
 
 
1201
        This method is intended to be called after another repository instance
 
1202
        (such as one used by a smart server) has inserted data into the
 
1203
        repository. It may not be called during a write group, but may be
 
1204
        called at any other time.
 
1205
        """
 
1206
        if self.is_in_write_group():
 
1207
            raise errors.InternalBzrError(
 
1208
                "May not refresh_data while in a write group.")
 
1209
        if self._real_repository is not None:
 
1210
            self._real_repository.refresh_data()
 
1211
 
788
1212
    def revision_ids_to_search_result(self, result_set):
789
1213
        """Convert a set of revision ids to a graph SearchResult."""
790
1214
        result_parents = set()
801
1225
    @needs_read_lock
802
1226
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
803
1227
        """Return the revision ids that other has that this does not.
804
 
        
 
1228
 
805
1229
        These are returned in topological order.
806
1230
 
807
1231
        revision_id: only return revision ids included by revision_id.
809
1233
        return repository.InterRepository.get(
810
1234
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
811
1235
 
812
 
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False):
813
 
        # Not delegated to _real_repository so that InterRepository.get has a
814
 
        # chance to find an InterRepository specialised for RemoteRepository.
815
 
        if self.has_same_location(source):
 
1236
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1237
            fetch_spec=None):
 
1238
        # No base implementation to use as RemoteRepository is not a subclass
 
1239
        # of Repository; so this is a copy of Repository.fetch().
 
1240
        if fetch_spec is not None and revision_id is not None:
 
1241
            raise AssertionError(
 
1242
                "fetch_spec and revision_id are mutually exclusive.")
 
1243
        if self.is_in_write_group():
 
1244
            raise errors.InternalBzrError(
 
1245
                "May not fetch while in a write group.")
 
1246
        # fast path same-url fetch operations
 
1247
        if (self.has_same_location(source)
 
1248
            and fetch_spec is None
 
1249
            and self._has_same_fallbacks(source)):
816
1250
            # check that last_revision is in 'from' and then return a
817
1251
            # no-operation.
818
1252
            if (revision_id is not None and
819
1253
                not revision.is_null(revision_id)):
820
1254
                self.get_revision(revision_id)
821
1255
            return 0, []
 
1256
        # if there is no specific appropriate InterRepository, this will get
 
1257
        # the InterRepository base class, which raises an
 
1258
        # IncompatibleRepositories when asked to fetch.
822
1259
        inter = repository.InterRepository.get(source, self)
823
 
        try:
824
 
            return inter.fetch(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts)
825
 
        except NotImplementedError:
826
 
            raise errors.IncompatibleRepositories(source, self)
 
1260
        return inter.fetch(revision_id=revision_id, pb=pb,
 
1261
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
827
1262
 
828
1263
    def create_bundle(self, target, base, fileobj, format=None):
829
1264
        self._ensure_real()
842
1277
        self._ensure_real()
843
1278
        return self._real_repository._get_versioned_file_checker(
844
1279
            revisions, revision_versions_cache)
845
 
        
 
1280
 
846
1281
    def iter_files_bytes(self, desired_files):
847
1282
        """See Repository.iter_file_bytes.
848
1283
        """
849
1284
        self._ensure_real()
850
1285
        return self._real_repository.iter_files_bytes(desired_files)
851
1286
 
852
 
    @property
853
 
    def _fetch_order(self):
854
 
        """Decorate the real repository for now.
855
 
 
856
 
        In the long term getting this back from the remote repository as part
857
 
        of open would be more efficient.
858
 
        """
859
 
        self._ensure_real()
860
 
        return self._real_repository._fetch_order
861
 
 
862
 
    @property
863
 
    def _fetch_uses_deltas(self):
864
 
        """Decorate the real repository for now.
865
 
 
866
 
        In the long term getting this back from the remote repository as part
867
 
        of open would be more efficient.
868
 
        """
869
 
        self._ensure_real()
870
 
        return self._real_repository._fetch_uses_deltas
871
 
 
872
 
    @property
873
 
    def _fetch_reconcile(self):
874
 
        """Decorate the real repository for now.
875
 
 
876
 
        In the long term getting this back from the remote repository as part
877
 
        of open would be more efficient.
878
 
        """
879
 
        self._ensure_real()
880
 
        return self._real_repository._fetch_reconcile
881
 
 
882
1287
    def get_parent_map(self, revision_ids):
883
1288
        """See bzrlib.Graph.get_parent_map()."""
884
1289
        return self._make_parents_provider().get_parent_map(revision_ids)
890
1295
            # We already found out that the server can't understand
891
1296
            # Repository.get_parent_map requests, so just fetch the whole
892
1297
            # graph.
893
 
            # XXX: Note that this will issue a deprecation warning. This is ok
894
 
            # :- its because we're working with a deprecated server anyway, and
895
 
            # the user will almost certainly have seen a warning about the
896
 
            # server version already.
897
 
            rg = self.get_revision_graph()
898
 
            # There is an api discrepency between get_parent_map and
 
1298
            #
 
1299
            # Note that this reads the whole graph, when only some keys are
 
1300
            # wanted.  On this old server there's no way (?) to get them all
 
1301
            # in one go, and the user probably will have seen a warning about
 
1302
            # the server being old anyhow.
 
1303
            rg = self._get_revision_graph(None)
 
1304
            # There is an API discrepancy between get_parent_map and
899
1305
            # get_revision_graph. Specifically, a "key:()" pair in
900
1306
            # get_revision_graph just means a node has no parents. For
901
1307
            # "get_parent_map" it means the node is a ghost. So fix up the
931
1337
        # TODO: Manage this incrementally to avoid covering the same path
932
1338
        # repeatedly. (The server will have to on each request, but the less
933
1339
        # work done the better).
 
1340
        #
 
1341
        # Negative caching notes:
 
1342
        # new server sends missing when a request including the revid
 
1343
        # 'include-missing:' is present in the request.
 
1344
        # missing keys are serialised as missing:X, and we then call
 
1345
        # provider.note_missing(X) for-all X
934
1346
        parents_map = self._unstacked_provider.get_cached_map()
935
1347
        if parents_map is None:
936
1348
            # Repository is not locked, so there's no cache.
937
1349
            parents_map = {}
 
1350
        # start_set is all the keys in the cache
938
1351
        start_set = set(parents_map)
 
1352
        # result set is all the references to keys in the cache
939
1353
        result_parents = set()
940
1354
        for parents in parents_map.itervalues():
941
1355
            result_parents.update(parents)
942
1356
        stop_keys = result_parents.difference(start_set)
 
1357
        # We don't need to send ghosts back to the server as a position to
 
1358
        # stop either.
 
1359
        stop_keys.difference_update(self._unstacked_provider.missing_keys)
 
1360
        key_count = len(parents_map)
 
1361
        if (NULL_REVISION in result_parents
 
1362
            and NULL_REVISION in self._unstacked_provider.missing_keys):
 
1363
            # If we pruned NULL_REVISION from the stop_keys because it's also
 
1364
            # in our cache of "missing" keys we need to increment our key count
 
1365
            # by 1, because the reconsitituted SearchResult on the server will
 
1366
            # still consider NULL_REVISION to be an included key.
 
1367
            key_count += 1
943
1368
        included_keys = start_set.intersection(result_parents)
944
1369
        start_set.difference_update(included_keys)
945
 
        recipe = (start_set, stop_keys, len(parents_map))
 
1370
        recipe = ('manual', start_set, stop_keys, key_count)
946
1371
        body = self._serialise_search_recipe(recipe)
947
1372
        path = self.bzrdir._path_for_remote_call(self._client)
948
1373
        for key in keys:
950
1375
                raise ValueError(
951
1376
                    "key %r not a plain string" % (key,))
952
1377
        verb = 'Repository.get_parent_map'
953
 
        args = (path,) + tuple(keys)
 
1378
        args = (path, 'include-missing:') + tuple(keys)
954
1379
        try:
955
1380
            response = self._call_with_body_bytes_expecting_body(
956
1381
                verb, args, body)
966
1391
            # To avoid having to disconnect repeatedly, we keep track of the
967
1392
            # fact the server doesn't understand remote methods added in 1.2.
968
1393
            medium._remember_remote_is_before((1, 2))
969
 
            return self.get_revision_graph(None)
 
1394
            # Recurse just once and we should use the fallback code.
 
1395
            return self._get_parent_map_rpc(keys)
970
1396
        response_tuple, response_handler = response
971
1397
        if response_tuple[0] not in ['ok']:
972
1398
            response_handler.cancel_read_body()
983
1409
                if len(d) > 1:
984
1410
                    revision_graph[d[0]] = d[1:]
985
1411
                else:
986
 
                    # No parents - so give the Graph result (NULL_REVISION,).
987
 
                    revision_graph[d[0]] = (NULL_REVISION,)
 
1412
                    # No parents:
 
1413
                    if d[0].startswith('missing:'):
 
1414
                        revid = d[0][8:]
 
1415
                        self._unstacked_provider.note_missing_key(revid)
 
1416
                    else:
 
1417
                        # no parents - so give the Graph result
 
1418
                        # (NULL_REVISION,).
 
1419
                        revision_graph[d[0]] = (NULL_REVISION,)
988
1420
            return revision_graph
989
1421
 
990
1422
    @needs_read_lock
993
1425
        return self._real_repository.get_signature_text(revision_id)
994
1426
 
995
1427
    @needs_read_lock
996
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_three)
997
 
    def get_revision_graph_with_ghosts(self, revision_ids=None):
998
 
        self._ensure_real()
999
 
        return self._real_repository.get_revision_graph_with_ghosts(
1000
 
            revision_ids=revision_ids)
1001
 
 
1002
 
    @needs_read_lock
1003
1428
    def get_inventory_xml(self, revision_id):
1004
1429
        self._ensure_real()
1005
1430
        return self._real_repository.get_inventory_xml(revision_id)
1011
1436
    def reconcile(self, other=None, thorough=False):
1012
1437
        self._ensure_real()
1013
1438
        return self._real_repository.reconcile(other=other, thorough=thorough)
1014
 
        
 
1439
 
1015
1440
    def all_revision_ids(self):
1016
1441
        self._ensure_real()
1017
1442
        return self._real_repository.all_revision_ids()
1018
 
    
1019
 
    @needs_read_lock
1020
 
    def get_deltas_for_revisions(self, revisions):
1021
 
        self._ensure_real()
1022
 
        return self._real_repository.get_deltas_for_revisions(revisions)
1023
 
 
1024
 
    @needs_read_lock
1025
 
    def get_revision_delta(self, revision_id):
1026
 
        self._ensure_real()
1027
 
        return self._real_repository.get_revision_delta(revision_id)
 
1443
 
 
1444
    @needs_read_lock
 
1445
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
1446
        self._ensure_real()
 
1447
        return self._real_repository.get_deltas_for_revisions(revisions,
 
1448
            specific_fileids=specific_fileids)
 
1449
 
 
1450
    @needs_read_lock
 
1451
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
1452
        self._ensure_real()
 
1453
        return self._real_repository.get_revision_delta(revision_id,
 
1454
            specific_fileids=specific_fileids)
1028
1455
 
1029
1456
    @needs_read_lock
1030
1457
    def revision_trees(self, revision_ids):
1085
1512
        return self._real_repository.inventories
1086
1513
 
1087
1514
    @needs_write_lock
1088
 
    def pack(self):
 
1515
    def pack(self, hint=None):
1089
1516
        """Compress the data within the repository.
1090
1517
 
1091
1518
        This is not currently implemented within the smart server.
1092
1519
        """
1093
1520
        self._ensure_real()
1094
 
        return self._real_repository.pack()
 
1521
        return self._real_repository.pack(hint=hint)
1095
1522
 
1096
1523
    @property
1097
1524
    def revisions(self):
1106
1533
        return self._real_repository.revisions
1107
1534
 
1108
1535
    def set_make_working_trees(self, new_value):
1109
 
        self._ensure_real()
1110
 
        self._real_repository.set_make_working_trees(new_value)
 
1536
        if new_value:
 
1537
            new_value_str = "True"
 
1538
        else:
 
1539
            new_value_str = "False"
 
1540
        path = self.bzrdir._path_for_remote_call(self._client)
 
1541
        try:
 
1542
            response = self._call(
 
1543
                'Repository.set_make_working_trees', path, new_value_str)
 
1544
        except errors.UnknownSmartMethod:
 
1545
            self._ensure_real()
 
1546
            self._real_repository.set_make_working_trees(new_value)
 
1547
        else:
 
1548
            if response[0] != 'ok':
 
1549
                raise errors.UnexpectedSmartServerResponse(response)
1111
1550
 
1112
1551
    @property
1113
1552
    def signatures(self):
1140
1579
        return self._real_repository.get_revisions(revision_ids)
1141
1580
 
1142
1581
    def supports_rich_root(self):
1143
 
        self._ensure_real()
1144
 
        return self._real_repository.supports_rich_root()
 
1582
        return self._format.rich_root_data
1145
1583
 
1146
1584
    def iter_reverse_revision_history(self, revision_id):
1147
1585
        self._ensure_real()
1149
1587
 
1150
1588
    @property
1151
1589
    def _serializer(self):
1152
 
        self._ensure_real()
1153
 
        return self._real_repository._serializer
 
1590
        return self._format._serializer
1154
1591
 
1155
1592
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1156
1593
        self._ensure_real()
1189
1626
            providers.insert(0, other)
1190
1627
        providers.extend(r._make_parents_provider() for r in
1191
1628
                         self._fallback_repositories)
1192
 
        return graph._StackedParentsProvider(providers)
 
1629
        return graph.StackedParentsProvider(providers)
1193
1630
 
1194
1631
    def _serialise_search_recipe(self, recipe):
1195
1632
        """Serialise a graph search recipe.
1197
1634
        :param recipe: A search recipe (start, stop, count).
1198
1635
        :return: Serialised bytes.
1199
1636
        """
1200
 
        start_keys = ' '.join(recipe[0])
1201
 
        stop_keys = ' '.join(recipe[1])
1202
 
        count = str(recipe[2])
 
1637
        start_keys = ' '.join(recipe[1])
 
1638
        stop_keys = ' '.join(recipe[2])
 
1639
        count = str(recipe[3])
1203
1640
        return '\n'.join((start_keys, stop_keys, count))
1204
1641
 
 
1642
    def _serialise_search_result(self, search_result):
 
1643
        if isinstance(search_result, graph.PendingAncestryResult):
 
1644
            parts = ['ancestry-of']
 
1645
            parts.extend(search_result.heads)
 
1646
        else:
 
1647
            recipe = search_result.get_recipe()
 
1648
            parts = [recipe[0], self._serialise_search_recipe(recipe)]
 
1649
        return '\n'.join(parts)
 
1650
 
1205
1651
    def autopack(self):
1206
1652
        path = self.bzrdir._path_for_remote_call(self._client)
1207
1653
        try:
1210
1656
            self._ensure_real()
1211
1657
            self._real_repository._pack_collection.autopack()
1212
1658
            return
1213
 
        if self._real_repository is not None:
1214
 
            # Reset the real repository's cache of pack names.
1215
 
            # XXX: At some point we may be able to skip this and just rely on
1216
 
            # the automatic retry logic to do the right thing, but for now we
1217
 
            # err on the side of being correct rather than being optimal.
1218
 
            self._real_repository._pack_collection.reload_pack_names()
 
1659
        self.refresh_data()
1219
1660
        if response[0] != 'ok':
1220
1661
            raise errors.UnexpectedSmartServerResponse(response)
1221
1662
 
1222
1663
 
 
1664
class RemoteStreamSink(repository.StreamSink):
 
1665
 
 
1666
    def _insert_real(self, stream, src_format, resume_tokens):
 
1667
        self.target_repo._ensure_real()
 
1668
        sink = self.target_repo._real_repository._get_sink()
 
1669
        result = sink.insert_stream(stream, src_format, resume_tokens)
 
1670
        if not result:
 
1671
            self.target_repo.autopack()
 
1672
        return result
 
1673
 
 
1674
    def insert_stream(self, stream, src_format, resume_tokens):
 
1675
        target = self.target_repo
 
1676
        target._unstacked_provider.missing_keys.clear()
 
1677
        if target._lock_token:
 
1678
            verb = 'Repository.insert_stream_locked'
 
1679
            extra_args = (target._lock_token or '',)
 
1680
            required_version = (1, 14)
 
1681
        else:
 
1682
            verb = 'Repository.insert_stream'
 
1683
            extra_args = ()
 
1684
            required_version = (1, 13)
 
1685
        client = target._client
 
1686
        medium = client._medium
 
1687
        if medium._is_remote_before(required_version):
 
1688
            # No possible way this can work.
 
1689
            return self._insert_real(stream, src_format, resume_tokens)
 
1690
        path = target.bzrdir._path_for_remote_call(client)
 
1691
        if not resume_tokens:
 
1692
            # XXX: Ugly but important for correctness, *will* be fixed during
 
1693
            # 1.13 cycle. Pushing a stream that is interrupted results in a
 
1694
            # fallback to the _real_repositories sink *with a partial stream*.
 
1695
            # Thats bad because we insert less data than bzr expected. To avoid
 
1696
            # this we do a trial push to make sure the verb is accessible, and
 
1697
            # do not fallback when actually pushing the stream. A cleanup patch
 
1698
            # is going to look at rewinding/restarting the stream/partial
 
1699
            # buffering etc.
 
1700
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
 
1701
            try:
 
1702
                response = client.call_with_body_stream(
 
1703
                    (verb, path, '') + extra_args, byte_stream)
 
1704
            except errors.UnknownSmartMethod:
 
1705
                medium._remember_remote_is_before(required_version)
 
1706
                return self._insert_real(stream, src_format, resume_tokens)
 
1707
        byte_stream = smart_repo._stream_to_byte_stream(
 
1708
            stream, src_format)
 
1709
        resume_tokens = ' '.join(resume_tokens)
 
1710
        response = client.call_with_body_stream(
 
1711
            (verb, path, resume_tokens) + extra_args, byte_stream)
 
1712
        if response[0][0] not in ('ok', 'missing-basis'):
 
1713
            raise errors.UnexpectedSmartServerResponse(response)
 
1714
        if response[0][0] == 'missing-basis':
 
1715
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
 
1716
            resume_tokens = tokens
 
1717
            return resume_tokens, set(missing_keys)
 
1718
        else:
 
1719
            self.target_repo.refresh_data()
 
1720
            return [], set()
 
1721
 
 
1722
 
 
1723
class RemoteStreamSource(repository.StreamSource):
 
1724
    """Stream data from a remote server."""
 
1725
 
 
1726
    def get_stream(self, search):
 
1727
        if (self.from_repository._fallback_repositories and
 
1728
            self.to_format._fetch_order == 'topological'):
 
1729
            return self._real_stream(self.from_repository, search)
 
1730
        return self.missing_parents_chain(search, [self.from_repository] +
 
1731
            self.from_repository._fallback_repositories)
 
1732
 
 
1733
    def _real_stream(self, repo, search):
 
1734
        """Get a stream for search from repo.
 
1735
        
 
1736
        This never called RemoteStreamSource.get_stream, and is a heler
 
1737
        for RemoteStreamSource._get_stream to allow getting a stream 
 
1738
        reliably whether fallback back because of old servers or trying
 
1739
        to stream from a non-RemoteRepository (which the stacked support
 
1740
        code will do).
 
1741
        """
 
1742
        source = repo._get_source(self.to_format)
 
1743
        if isinstance(source, RemoteStreamSource):
 
1744
            return repository.StreamSource.get_stream(source, search)
 
1745
        return source.get_stream(search)
 
1746
 
 
1747
    def _get_stream(self, repo, search):
 
1748
        """Core worker to get a stream from repo for search.
 
1749
 
 
1750
        This is used by both get_stream and the stacking support logic. It
 
1751
        deliberately gets a stream for repo which does not need to be
 
1752
        self.from_repository. In the event that repo is not Remote, or
 
1753
        cannot do a smart stream, a fallback is made to the generic
 
1754
        repository._get_stream() interface, via self._real_stream.
 
1755
 
 
1756
        In the event of stacking, streams from _get_stream will not
 
1757
        contain all the data for search - this is normal (see get_stream).
 
1758
 
 
1759
        :param repo: A repository.
 
1760
        :param search: A search.
 
1761
        """
 
1762
        # Fallbacks may be non-smart
 
1763
        if not isinstance(repo, RemoteRepository):
 
1764
            return self._real_stream(repo, search)
 
1765
        client = repo._client
 
1766
        medium = client._medium
 
1767
        if medium._is_remote_before((1, 13)):
 
1768
            # streaming was added in 1.13
 
1769
            return self._real_stream(repo, search)
 
1770
        path = repo.bzrdir._path_for_remote_call(client)
 
1771
        try:
 
1772
            search_bytes = repo._serialise_search_result(search)
 
1773
            response = repo._call_with_body_bytes_expecting_body(
 
1774
                'Repository.get_stream',
 
1775
                (path, self.to_format.network_name()), search_bytes)
 
1776
            response_tuple, response_handler = response
 
1777
        except errors.UnknownSmartMethod:
 
1778
            medium._remember_remote_is_before((1,13))
 
1779
            return self._real_stream(repo, search)
 
1780
        if response_tuple[0] != 'ok':
 
1781
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
1782
        byte_stream = response_handler.read_streamed_body()
 
1783
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
 
1784
        if src_format.network_name() != repo._format.network_name():
 
1785
            raise AssertionError(
 
1786
                "Mismatched RemoteRepository and stream src %r, %r" % (
 
1787
                src_format.network_name(), repo._format.network_name()))
 
1788
        return stream
 
1789
 
 
1790
    def missing_parents_chain(self, search, sources):
 
1791
        """Chain multiple streams together to handle stacking.
 
1792
 
 
1793
        :param search: The overall search to satisfy with streams.
 
1794
        :param sources: A list of Repository objects to query.
 
1795
        """
 
1796
        self.serialiser = self.to_format._serializer
 
1797
        self.seen_revs = set()
 
1798
        self.referenced_revs = set()
 
1799
        # If there are heads in the search, or the key count is > 0, we are not
 
1800
        # done.
 
1801
        while not search.is_empty() and len(sources) > 1:
 
1802
            source = sources.pop(0)
 
1803
            stream = self._get_stream(source, search)
 
1804
            for kind, substream in stream:
 
1805
                if kind != 'revisions':
 
1806
                    yield kind, substream
 
1807
                else:
 
1808
                    yield kind, self.missing_parents_rev_handler(substream)
 
1809
            search = search.refine(self.seen_revs, self.referenced_revs)
 
1810
            self.seen_revs = set()
 
1811
            self.referenced_revs = set()
 
1812
        if not search.is_empty():
 
1813
            for kind, stream in self._get_stream(sources[0], search):
 
1814
                yield kind, stream
 
1815
 
 
1816
    def missing_parents_rev_handler(self, substream):
 
1817
        for content in substream:
 
1818
            revision_bytes = content.get_bytes_as('fulltext')
 
1819
            revision = self.serialiser.read_revision_from_string(revision_bytes)
 
1820
            self.seen_revs.add(content.key[-1])
 
1821
            self.referenced_revs.update(revision.parent_ids)
 
1822
            yield content
 
1823
 
 
1824
 
1223
1825
class RemoteBranchLockableFiles(LockableFiles):
1224
1826
    """A 'LockableFiles' implementation that talks to a smart server.
1225
 
    
 
1827
 
1226
1828
    This is not a public interface class.
1227
1829
    """
1228
1830
 
1242
1844
 
1243
1845
class RemoteBranchFormat(branch.BranchFormat):
1244
1846
 
1245
 
    def __init__(self):
 
1847
    def __init__(self, network_name=None):
1246
1848
        super(RemoteBranchFormat, self).__init__()
1247
1849
        self._matchingbzrdir = RemoteBzrDirFormat()
1248
1850
        self._matchingbzrdir.set_branch_format(self)
 
1851
        self._custom_format = None
 
1852
        self._network_name = network_name
1249
1853
 
1250
1854
    def __eq__(self, other):
1251
 
        return (isinstance(other, RemoteBranchFormat) and 
 
1855
        return (isinstance(other, RemoteBranchFormat) and
1252
1856
            self.__dict__ == other.__dict__)
1253
1857
 
 
1858
    def _ensure_real(self):
 
1859
        if self._custom_format is None:
 
1860
            self._custom_format = branch.network_format_registry.get(
 
1861
                self._network_name)
 
1862
 
1254
1863
    def get_format_description(self):
1255
1864
        return 'Remote BZR Branch'
1256
1865
 
1257
 
    def get_format_string(self):
1258
 
        return 'Remote BZR Branch'
1259
 
 
1260
 
    def open(self, a_bzrdir):
1261
 
        return a_bzrdir.open_branch()
 
1866
    def network_name(self):
 
1867
        return self._network_name
 
1868
 
 
1869
    def open(self, a_bzrdir, ignore_fallbacks=False):
 
1870
        return a_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
 
1871
 
 
1872
    def _vfs_initialize(self, a_bzrdir):
 
1873
        # Initialisation when using a local bzrdir object, or a non-vfs init
 
1874
        # method is not available on the server.
 
1875
        # self._custom_format is always set - the start of initialize ensures
 
1876
        # that.
 
1877
        if isinstance(a_bzrdir, RemoteBzrDir):
 
1878
            a_bzrdir._ensure_real()
 
1879
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
 
1880
        else:
 
1881
            # We assume the bzrdir is parameterised; it may not be.
 
1882
            result = self._custom_format.initialize(a_bzrdir)
 
1883
        if (isinstance(a_bzrdir, RemoteBzrDir) and
 
1884
            not isinstance(result, RemoteBranch)):
 
1885
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
 
1886
        return result
1262
1887
 
1263
1888
    def initialize(self, a_bzrdir):
1264
 
        return a_bzrdir.create_branch()
 
1889
        # 1) get the network name to use.
 
1890
        if self._custom_format:
 
1891
            network_name = self._custom_format.network_name()
 
1892
        else:
 
1893
            # Select the current bzrlib default and ask for that.
 
1894
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
1895
            reference_format = reference_bzrdir_format.get_branch_format()
 
1896
            self._custom_format = reference_format
 
1897
            network_name = reference_format.network_name()
 
1898
        # Being asked to create on a non RemoteBzrDir:
 
1899
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
1900
            return self._vfs_initialize(a_bzrdir)
 
1901
        medium = a_bzrdir._client._medium
 
1902
        if medium._is_remote_before((1, 13)):
 
1903
            return self._vfs_initialize(a_bzrdir)
 
1904
        # Creating on a remote bzr dir.
 
1905
        # 2) try direct creation via RPC
 
1906
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
1907
        verb = 'BzrDir.create_branch'
 
1908
        try:
 
1909
            response = a_bzrdir._call(verb, path, network_name)
 
1910
        except errors.UnknownSmartMethod:
 
1911
            # Fallback - use vfs methods
 
1912
            medium._remember_remote_is_before((1, 13))
 
1913
            return self._vfs_initialize(a_bzrdir)
 
1914
        if response[0] != 'ok':
 
1915
            raise errors.UnexpectedSmartServerResponse(response)
 
1916
        # Turn the response into a RemoteRepository object.
 
1917
        format = RemoteBranchFormat(network_name=response[1])
 
1918
        repo_format = response_tuple_to_repo_format(response[3:])
 
1919
        if response[2] == '':
 
1920
            repo_bzrdir = a_bzrdir
 
1921
        else:
 
1922
            repo_bzrdir = RemoteBzrDir(
 
1923
                a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
 
1924
                a_bzrdir._client)
 
1925
        remote_repo = RemoteRepository(repo_bzrdir, repo_format)
 
1926
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
 
1927
            format=format, setup_stacking=False)
 
1928
        # XXX: We know this is a new branch, so it must have revno 0, revid
 
1929
        # NULL_REVISION. Creating the branch locked would make this be unable
 
1930
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
 
1931
        remote_branch._last_revision_info_cache = 0, NULL_REVISION
 
1932
        return remote_branch
 
1933
 
 
1934
    def make_tags(self, branch):
 
1935
        self._ensure_real()
 
1936
        return self._custom_format.make_tags(branch)
1265
1937
 
1266
1938
    def supports_tags(self):
1267
1939
        # Remote branches might support tags, but we won't know until we
1268
1940
        # access the real remote branch.
1269
 
        return True
 
1941
        self._ensure_real()
 
1942
        return self._custom_format.supports_tags()
 
1943
 
 
1944
    def supports_stacking(self):
 
1945
        self._ensure_real()
 
1946
        return self._custom_format.supports_stacking()
 
1947
 
 
1948
    def supports_set_append_revisions_only(self):
 
1949
        self._ensure_real()
 
1950
        return self._custom_format.supports_set_append_revisions_only()
1270
1951
 
1271
1952
 
1272
1953
class RemoteBranch(branch.Branch, _RpcHelper):
1276
1957
    """
1277
1958
 
1278
1959
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1279
 
        _client=None):
 
1960
        _client=None, format=None, setup_stacking=True):
1280
1961
        """Create a RemoteBranch instance.
1281
1962
 
1282
1963
        :param real_branch: An optional local implementation of the branch
1283
1964
            format, usually accessing the data via the VFS.
1284
1965
        :param _client: Private parameter for testing.
 
1966
        :param format: A RemoteBranchFormat object, None to create one
 
1967
            automatically. If supplied it should have a network_name already
 
1968
            supplied.
 
1969
        :param setup_stacking: If True make an RPC call to determine the
 
1970
            stacked (or not) status of the branch. If False assume the branch
 
1971
            is not stacked.
1285
1972
        """
1286
1973
        # We intentionally don't call the parent class's __init__, because it
1287
1974
        # will try to assign to self.tags, which is a property in this subclass.
1288
1975
        # And the parent's __init__ doesn't do much anyway.
1289
 
        self._revision_id_to_revno_cache = None
1290
 
        self._partial_revision_id_to_revno_cache = {}
1291
 
        self._revision_history_cache = None
1292
 
        self._last_revision_info_cache = None
1293
 
        self._merge_sorted_revisions_cache = None
1294
1976
        self.bzrdir = remote_bzrdir
1295
1977
        if _client is not None:
1296
1978
            self._client = _client
1309
1991
            self._real_branch.repository = self.repository
1310
1992
        else:
1311
1993
            self._real_branch = None
1312
 
        # Fill out expected attributes of branch for bzrlib api users.
1313
 
        self._format = RemoteBranchFormat()
 
1994
        # Fill out expected attributes of branch for bzrlib API users.
 
1995
        self._clear_cached_state()
1314
1996
        self.base = self.bzrdir.root_transport.base
1315
1997
        self._control_files = None
1316
1998
        self._lock_mode = None
1318
2000
        self._repo_lock_token = None
1319
2001
        self._lock_count = 0
1320
2002
        self._leave_lock = False
 
2003
        # Setup a format: note that we cannot call _ensure_real until all the
 
2004
        # attributes above are set: This code cannot be moved higher up in this
 
2005
        # function.
 
2006
        if format is None:
 
2007
            self._format = RemoteBranchFormat()
 
2008
            if real_branch is not None:
 
2009
                self._format._network_name = \
 
2010
                    self._real_branch._format.network_name()
 
2011
        else:
 
2012
            self._format = format
 
2013
        if not self._format._network_name:
 
2014
            # Did not get from open_branchV2 - old server.
 
2015
            self._ensure_real()
 
2016
            self._format._network_name = \
 
2017
                self._real_branch._format.network_name()
 
2018
        self.tags = self._format.make_tags(self)
1321
2019
        # The base class init is not called, so we duplicate this:
1322
2020
        hooks = branch.Branch.hooks['open']
1323
2021
        for hook in hooks:
1324
2022
            hook(self)
1325
 
        self._setup_stacking()
 
2023
        self._is_stacked = False
 
2024
        if setup_stacking:
 
2025
            self._setup_stacking()
1326
2026
 
1327
2027
    def _setup_stacking(self):
1328
2028
        # configure stacking into the remote repository, by reading it from
1332
2032
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1333
2033
            errors.UnstackableRepositoryFormat), e:
1334
2034
            return
1335
 
        # it's relative to this branch...
1336
 
        fallback_url = urlutils.join(self.base, fallback_url)
1337
 
        transports = [self.bzrdir.root_transport]
1338
 
        if self._real_branch is not None:
1339
 
            transports.append(self._real_branch._transport)
1340
 
        stacked_on = branch.Branch.open(fallback_url,
1341
 
                                        possible_transports=transports)
1342
 
        self.repository.add_fallback_repository(stacked_on.repository)
 
2035
        self._is_stacked = True
 
2036
        self._activate_fallback_location(fallback_url)
 
2037
 
 
2038
    def _get_config(self):
 
2039
        return RemoteBranchConfig(self)
1343
2040
 
1344
2041
    def _get_real_transport(self):
1345
2042
        # if we try vfs access, return the real branch's vfs transport
1398
2095
        too, in fact doing so might harm performance.
1399
2096
        """
1400
2097
        super(RemoteBranch, self)._clear_cached_state()
1401
 
        
 
2098
 
1402
2099
    @property
1403
2100
    def control_files(self):
1404
2101
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1443
2140
            raise errors.UnexpectedSmartServerResponse(response)
1444
2141
        return response[1]
1445
2142
 
 
2143
    def set_stacked_on_url(self, url):
 
2144
        branch.Branch.set_stacked_on_url(self, url)
 
2145
        if not url:
 
2146
            self._is_stacked = False
 
2147
        else:
 
2148
            self._is_stacked = True
 
2149
        
 
2150
    def _vfs_get_tags_bytes(self):
 
2151
        self._ensure_real()
 
2152
        return self._real_branch._get_tags_bytes()
 
2153
 
 
2154
    def _get_tags_bytes(self):
 
2155
        medium = self._client._medium
 
2156
        if medium._is_remote_before((1, 13)):
 
2157
            return self._vfs_get_tags_bytes()
 
2158
        try:
 
2159
            response = self._call('Branch.get_tags_bytes', self._remote_path())
 
2160
        except errors.UnknownSmartMethod:
 
2161
            medium._remember_remote_is_before((1, 13))
 
2162
            return self._vfs_get_tags_bytes()
 
2163
        return response[0]
 
2164
 
1446
2165
    def lock_read(self):
1447
2166
        self.repository.lock_read()
1448
2167
        if not self._lock_mode:
1468
2187
            raise errors.UnexpectedSmartServerResponse(response)
1469
2188
        ok, branch_token, repo_token = response
1470
2189
        return branch_token, repo_token
1471
 
            
 
2190
 
1472
2191
    def lock_write(self, token=None):
1473
2192
        if not self._lock_mode:
1474
2193
            # Lock the branch and repo in one remote call.
1502
2221
            self.repository.lock_write(self._repo_lock_token)
1503
2222
        return self._lock_token or None
1504
2223
 
 
2224
    def _set_tags_bytes(self, bytes):
 
2225
        self._ensure_real()
 
2226
        return self._real_branch._set_tags_bytes(bytes)
 
2227
 
1505
2228
    def _unlock(self, branch_token, repo_token):
1506
2229
        err_context = {'token': str((branch_token, repo_token))}
1507
2230
        response = self._call(
1529
2252
                    self._real_branch.unlock()
1530
2253
                if mode != 'w':
1531
2254
                    # Only write-locked branched need to make a remote method
1532
 
                    # call to perfom the unlock.
 
2255
                    # call to perform the unlock.
1533
2256
                    return
1534
2257
                if not self._lock_token:
1535
2258
                    raise AssertionError('Locked, but no token!')
1556
2279
            raise NotImplementedError(self.dont_leave_lock_in_place)
1557
2280
        self._leave_lock = False
1558
2281
 
 
2282
    def get_rev_id(self, revno, history=None):
 
2283
        if revno == 0:
 
2284
            return _mod_revision.NULL_REVISION
 
2285
        last_revision_info = self.last_revision_info()
 
2286
        ok, result = self.repository.get_rev_id_for_revno(
 
2287
            revno, last_revision_info)
 
2288
        if ok:
 
2289
            return result
 
2290
        missing_parent = result[1]
 
2291
        # Either the revision named by the server is missing, or its parent
 
2292
        # is.  Call get_parent_map to determine which, so that we report a
 
2293
        # useful error.
 
2294
        parent_map = self.repository.get_parent_map([missing_parent])
 
2295
        if missing_parent in parent_map:
 
2296
            missing_parent = parent_map[missing_parent]
 
2297
        raise errors.RevisionNotPresent(missing_parent, self.repository)
 
2298
 
1559
2299
    def _last_revision_info(self):
1560
2300
        response = self._call('Branch.last_revision_info', self._remote_path())
1561
2301
        if response[0] != 'ok':
1566
2306
 
1567
2307
    def _gen_revision_history(self):
1568
2308
        """See Branch._gen_revision_history()."""
 
2309
        if self._is_stacked:
 
2310
            self._ensure_real()
 
2311
            return self._real_branch._gen_revision_history()
1569
2312
        response_tuple, response_handler = self._call_expecting_body(
1570
2313
            'Branch.revision_history', self._remote_path())
1571
2314
        if response_tuple[0] != 'ok':
1580
2323
 
1581
2324
    def _set_last_revision_descendant(self, revision_id, other_branch,
1582
2325
            allow_diverged=False, allow_overwrite_descendant=False):
 
2326
        # This performs additional work to meet the hook contract; while its
 
2327
        # undesirable, we have to synthesise the revno to call the hook, and
 
2328
        # not calling the hook is worse as it means changes can't be prevented.
 
2329
        # Having calculated this though, we can't just call into
 
2330
        # set_last_revision_info as a simple call, because there is a set_rh
 
2331
        # hook that some folk may still be using.
 
2332
        old_revno, old_revid = self.last_revision_info()
 
2333
        history = self._lefthand_history(revision_id)
 
2334
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1583
2335
        err_context = {'other_branch': other_branch}
1584
2336
        response = self._call('Branch.set_last_revision_ex',
1585
2337
            self._remote_path(), self._lock_token, self._repo_lock_token,
1590
2342
            raise errors.UnexpectedSmartServerResponse(response)
1591
2343
        new_revno, new_revision_id = response[1:]
1592
2344
        self._last_revision_info_cache = new_revno, new_revision_id
 
2345
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1593
2346
        if self._real_branch is not None:
1594
2347
            cache = new_revno, new_revision_id
1595
2348
            self._real_branch._last_revision_info_cache = cache
1596
2349
 
1597
2350
    def _set_last_revision(self, revision_id):
 
2351
        old_revno, old_revid = self.last_revision_info()
 
2352
        # This performs additional work to meet the hook contract; while its
 
2353
        # undesirable, we have to synthesise the revno to call the hook, and
 
2354
        # not calling the hook is worse as it means changes can't be prevented.
 
2355
        # Having calculated this though, we can't just call into
 
2356
        # set_last_revision_info as a simple call, because there is a set_rh
 
2357
        # hook that some folk may still be using.
 
2358
        history = self._lefthand_history(revision_id)
 
2359
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1598
2360
        self._clear_cached_state()
1599
2361
        response = self._call('Branch.set_last_revision',
1600
2362
            self._remote_path(), self._lock_token, self._repo_lock_token,
1601
2363
            revision_id)
1602
2364
        if response != ('ok',):
1603
2365
            raise errors.UnexpectedSmartServerResponse(response)
 
2366
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1604
2367
 
1605
2368
    @needs_write_lock
1606
2369
    def set_revision_history(self, rev_history):
1612
2375
        else:
1613
2376
            rev_id = rev_history[-1]
1614
2377
        self._set_last_revision(rev_id)
 
2378
        for hook in branch.Branch.hooks['set_rh']:
 
2379
            hook(self, rev_history)
1615
2380
        self._cache_revision_history(rev_history)
1616
2381
 
1617
 
    def get_parent(self):
1618
 
        self._ensure_real()
1619
 
        return self._real_branch.get_parent()
1620
 
        
1621
 
    def set_parent(self, url):
1622
 
        self._ensure_real()
1623
 
        return self._real_branch.set_parent(url)
1624
 
        
1625
 
    def set_stacked_on_url(self, stacked_location):
1626
 
        """Set the URL this branch is stacked against.
1627
 
 
1628
 
        :raises UnstackableBranchFormat: If the branch does not support
1629
 
            stacking.
1630
 
        :raises UnstackableRepositoryFormat: If the repository does not support
1631
 
            stacking.
1632
 
        """
1633
 
        self._ensure_real()
1634
 
        return self._real_branch.set_stacked_on_url(stacked_location)
1635
 
 
1636
 
    def sprout(self, to_bzrdir, revision_id=None):
1637
 
        branch_format = to_bzrdir._format._branch_format
1638
 
        if (branch_format is None or
1639
 
            isinstance(branch_format, RemoteBranchFormat)):
1640
 
            # The to_bzrdir specifies RemoteBranchFormat (or no format, which
1641
 
            # implies the same thing), but RemoteBranches can't be created at
1642
 
            # arbitrary URLs.  So create a branch in the same format as
1643
 
            # _real_branch instead.
1644
 
            # XXX: if to_bzrdir is a RemoteBzrDir, this should perhaps do
1645
 
            # to_bzrdir.create_branch to create a RemoteBranch after all...
1646
 
            self._ensure_real()
1647
 
            result = self._real_branch._format.initialize(to_bzrdir)
1648
 
            self.copy_content_into(result, revision_id=revision_id)
1649
 
            result.set_parent(self.bzrdir.root_transport.base)
1650
 
        else:
1651
 
            result = branch.Branch.sprout(
1652
 
                self, to_bzrdir, revision_id=revision_id)
1653
 
        return result
 
2382
    def _get_parent_location(self):
 
2383
        medium = self._client._medium
 
2384
        if medium._is_remote_before((1, 13)):
 
2385
            return self._vfs_get_parent_location()
 
2386
        try:
 
2387
            response = self._call('Branch.get_parent', self._remote_path())
 
2388
        except errors.UnknownSmartMethod:
 
2389
            medium._remember_remote_is_before((1, 13))
 
2390
            return self._vfs_get_parent_location()
 
2391
        if len(response) != 1:
 
2392
            raise errors.UnexpectedSmartServerResponse(response)
 
2393
        parent_location = response[0]
 
2394
        if parent_location == '':
 
2395
            return None
 
2396
        return parent_location
 
2397
 
 
2398
    def _vfs_get_parent_location(self):
 
2399
        self._ensure_real()
 
2400
        return self._real_branch._get_parent_location()
 
2401
 
 
2402
    def _set_parent_location(self, url):
 
2403
        medium = self._client._medium
 
2404
        if medium._is_remote_before((1, 15)):
 
2405
            return self._vfs_set_parent_location(url)
 
2406
        try:
 
2407
            call_url = url or ''
 
2408
            if type(call_url) is not str:
 
2409
                raise AssertionError('url must be a str or None (%s)' % url)
 
2410
            response = self._call('Branch.set_parent_location',
 
2411
                self._remote_path(), self._lock_token, self._repo_lock_token,
 
2412
                call_url)
 
2413
        except errors.UnknownSmartMethod:
 
2414
            medium._remember_remote_is_before((1, 15))
 
2415
            return self._vfs_set_parent_location(url)
 
2416
        if response != ():
 
2417
            raise errors.UnexpectedSmartServerResponse(response)
 
2418
 
 
2419
    def _vfs_set_parent_location(self, url):
 
2420
        self._ensure_real()
 
2421
        return self._real_branch._set_parent_location(url)
1654
2422
 
1655
2423
    @needs_write_lock
1656
2424
    def pull(self, source, overwrite=False, stop_revision=None,
1678
2446
 
1679
2447
    @needs_write_lock
1680
2448
    def set_last_revision_info(self, revno, revision_id):
 
2449
        # XXX: These should be returned by the set_last_revision_info verb
 
2450
        old_revno, old_revid = self.last_revision_info()
 
2451
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
1681
2452
        revision_id = ensure_null(revision_id)
1682
2453
        try:
1683
2454
            response = self._call('Branch.set_last_revision_info',
1692
2463
        if response == ('ok',):
1693
2464
            self._clear_cached_state()
1694
2465
            self._last_revision_info_cache = revno, revision_id
 
2466
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1695
2467
            # Update the _real_branch's cache too.
1696
2468
            if self._real_branch is not None:
1697
2469
                cache = self._last_revision_info_cache
1704
2476
                                  other_branch=None):
1705
2477
        medium = self._client._medium
1706
2478
        if not medium._is_remote_before((1, 6)):
 
2479
            # Use a smart method for 1.6 and above servers
1707
2480
            try:
1708
2481
                self._set_last_revision_descendant(revision_id, other_branch,
1709
2482
                    allow_diverged=True, allow_overwrite_descendant=True)
1711
2484
            except errors.UnknownSmartMethod:
1712
2485
                medium._remember_remote_is_before((1, 6))
1713
2486
        self._clear_cached_state_of_remote_branch_only()
1714
 
        self._ensure_real()
1715
 
        self._real_branch.generate_revision_history(
1716
 
            revision_id, last_rev=last_rev, other_branch=other_branch)
1717
 
 
1718
 
    @property
1719
 
    def tags(self):
1720
 
        self._ensure_real()
1721
 
        return self._real_branch.tags
 
2487
        self.set_revision_history(self._lefthand_history(revision_id,
 
2488
            last_rev=last_rev,other_branch=other_branch))
1722
2489
 
1723
2490
    def set_push_location(self, location):
1724
2491
        self._ensure_real()
1725
2492
        return self._real_branch.set_push_location(location)
1726
2493
 
1727
 
    @needs_write_lock
1728
 
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1729
 
                         graph=None):
1730
 
        """See Branch.update_revisions."""
1731
 
        other.lock_read()
 
2494
 
 
2495
class RemoteConfig(object):
 
2496
    """A Config that reads and writes from smart verbs.
 
2497
 
 
2498
    It is a low-level object that considers config data to be name/value pairs
 
2499
    that may be associated with a section. Assigning meaning to the these
 
2500
    values is done at higher levels like bzrlib.config.TreeConfig.
 
2501
    """
 
2502
 
 
2503
    def get_option(self, name, section=None, default=None):
 
2504
        """Return the value associated with a named option.
 
2505
 
 
2506
        :param name: The name of the value
 
2507
        :param section: The section the option is in (if any)
 
2508
        :param default: The value to return if the value is not set
 
2509
        :return: The value or default value
 
2510
        """
1732
2511
        try:
1733
 
            if stop_revision is None:
1734
 
                stop_revision = other.last_revision()
1735
 
                if revision.is_null(stop_revision):
1736
 
                    # if there are no commits, we're done.
1737
 
                    return
1738
 
            self.fetch(other, stop_revision)
1739
 
 
1740
 
            if overwrite:
1741
 
                # Just unconditionally set the new revision.  We don't care if
1742
 
                # the branches have diverged.
1743
 
                self._set_last_revision(stop_revision)
 
2512
            configobj = self._get_configobj()
 
2513
            if section is None:
 
2514
                section_obj = configobj
1744
2515
            else:
1745
 
                medium = self._client._medium
1746
 
                if not medium._is_remote_before((1, 6)):
1747
 
                    try:
1748
 
                        self._set_last_revision_descendant(stop_revision, other)
1749
 
                        return
1750
 
                    except errors.UnknownSmartMethod:
1751
 
                        medium._remember_remote_is_before((1, 6))
1752
 
                # Fallback for pre-1.6 servers: check for divergence
1753
 
                # client-side, then do _set_last_revision.
1754
 
                last_rev = revision.ensure_null(self.last_revision())
1755
 
                if graph is None:
1756
 
                    graph = self.repository.get_graph()
1757
 
                if self._check_if_descendant_or_diverged(
1758
 
                        stop_revision, last_rev, graph, other):
1759
 
                    # stop_revision is a descendant of last_rev, but we aren't
1760
 
                    # overwriting, so we're done.
1761
 
                    return
1762
 
                self._set_last_revision(stop_revision)
1763
 
        finally:
1764
 
            other.unlock()
 
2516
                try:
 
2517
                    section_obj = configobj[section]
 
2518
                except KeyError:
 
2519
                    return default
 
2520
            return section_obj.get(name, default)
 
2521
        except errors.UnknownSmartMethod:
 
2522
            return self._vfs_get_option(name, section, default)
 
2523
 
 
2524
    def _response_to_configobj(self, response):
 
2525
        if len(response[0]) and response[0][0] != 'ok':
 
2526
            raise errors.UnexpectedSmartServerResponse(response)
 
2527
        lines = response[1].read_body_bytes().splitlines()
 
2528
        return config.ConfigObj(lines, encoding='utf-8')
 
2529
 
 
2530
 
 
2531
class RemoteBranchConfig(RemoteConfig):
 
2532
    """A RemoteConfig for Branches."""
 
2533
 
 
2534
    def __init__(self, branch):
 
2535
        self._branch = branch
 
2536
 
 
2537
    def _get_configobj(self):
 
2538
        path = self._branch._remote_path()
 
2539
        response = self._branch._client.call_expecting_body(
 
2540
            'Branch.get_config_file', path)
 
2541
        return self._response_to_configobj(response)
 
2542
 
 
2543
    def set_option(self, value, name, section=None):
 
2544
        """Set the value associated with a named option.
 
2545
 
 
2546
        :param value: The value to set
 
2547
        :param name: The name of the value to set
 
2548
        :param section: The section the option is in (if any)
 
2549
        """
 
2550
        medium = self._branch._client._medium
 
2551
        if medium._is_remote_before((1, 14)):
 
2552
            return self._vfs_set_option(value, name, section)
 
2553
        try:
 
2554
            path = self._branch._remote_path()
 
2555
            response = self._branch._client.call('Branch.set_config_option',
 
2556
                path, self._branch._lock_token, self._branch._repo_lock_token,
 
2557
                value.encode('utf8'), name, section or '')
 
2558
        except errors.UnknownSmartMethod:
 
2559
            medium._remember_remote_is_before((1, 14))
 
2560
            return self._vfs_set_option(value, name, section)
 
2561
        if response != ():
 
2562
            raise errors.UnexpectedSmartServerResponse(response)
 
2563
 
 
2564
    def _real_object(self):
 
2565
        self._branch._ensure_real()
 
2566
        return self._branch._real_branch
 
2567
 
 
2568
    def _vfs_set_option(self, value, name, section=None):
 
2569
        return self._real_object()._get_config().set_option(
 
2570
            value, name, section)
 
2571
 
 
2572
 
 
2573
class RemoteBzrDirConfig(RemoteConfig):
 
2574
    """A RemoteConfig for BzrDirs."""
 
2575
 
 
2576
    def __init__(self, bzrdir):
 
2577
        self._bzrdir = bzrdir
 
2578
 
 
2579
    def _get_configobj(self):
 
2580
        medium = self._bzrdir._client._medium
 
2581
        verb = 'BzrDir.get_config_file'
 
2582
        if medium._is_remote_before((1, 15)):
 
2583
            raise errors.UnknownSmartMethod(verb)
 
2584
        path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
 
2585
        response = self._bzrdir._call_expecting_body(
 
2586
            verb, path)
 
2587
        return self._response_to_configobj(response)
 
2588
 
 
2589
    def _vfs_get_option(self, name, section, default):
 
2590
        return self._real_object()._get_config().get_option(
 
2591
            name, section, default)
 
2592
 
 
2593
    def set_option(self, value, name, section=None):
 
2594
        """Set the value associated with a named option.
 
2595
 
 
2596
        :param value: The value to set
 
2597
        :param name: The name of the value to set
 
2598
        :param section: The section the option is in (if any)
 
2599
        """
 
2600
        return self._real_object()._get_config().set_option(
 
2601
            value, name, section)
 
2602
 
 
2603
    def _real_object(self):
 
2604
        self._bzrdir._ensure_real()
 
2605
        return self._bzrdir._real_bzrdir
 
2606
 
1765
2607
 
1766
2608
 
1767
2609
def _extract_tar(tar, to_dir):