~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/remote.py

  • Committer: Andrew Bennetts
  • Date: 2010-01-12 03:53:21 UTC
  • mfrom: (4948 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4964.
  • Revision ID: andrew.bennetts@canonical.com-20100112035321-hofpz5p10224ryj3
Merge lp:bzr, resolving conflicts.

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
35
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
36
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
36
37
from bzrlib.errors import (
37
38
    NoSuchRevision,
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
 
 
62
    def _call_with_body_bytes(self, method, args, body_bytes, **err_context):
 
63
        try:
 
64
            return self._client.call_with_body_bytes(method, args, body_bytes)
 
65
        except errors.ErrorFromSmartServer, err:
 
66
            self._translate_error(err, **err_context)
 
67
 
61
68
    def _call_with_body_bytes_expecting_body(self, method, args, body_bytes,
62
69
                                             **err_context):
63
70
        try:
65
72
                method, args, body_bytes)
66
73
        except errors.ErrorFromSmartServer, err:
67
74
            self._translate_error(err, **err_context)
68
 
        
 
75
 
 
76
 
 
77
def response_tuple_to_repo_format(response):
 
78
    """Convert a response tuple describing a repository format to a format."""
 
79
    format = RemoteRepositoryFormat()
 
80
    format._rich_root_data = (response[0] == 'yes')
 
81
    format._supports_tree_reference = (response[1] == 'yes')
 
82
    format._supports_external_lookups = (response[2] == 'yes')
 
83
    format._network_name = response[3]
 
84
    return format
 
85
 
 
86
 
69
87
# Note: RemoteBzrDirFormat is in bzrdir.py
70
88
 
71
89
class RemoteBzrDir(BzrDir, _RpcHelper):
72
90
    """Control directory on a remote server, accessed via bzr:// or similar."""
73
91
 
74
 
    def __init__(self, transport, _client=None):
 
92
    def __init__(self, transport, format, _client=None, _force_probe=False):
75
93
        """Construct a RemoteBzrDir.
76
94
 
77
95
        :param _client: Private parameter for testing. Disables probing and the
78
96
            use of a real bzrdir.
79
97
        """
80
 
        BzrDir.__init__(self, transport, RemoteBzrDirFormat())
 
98
        BzrDir.__init__(self, transport, format)
81
99
        # this object holds a delegated bzrdir that uses file-level operations
82
100
        # to talk to the other side
83
101
        self._real_bzrdir = None
 
102
        self._has_working_tree = None
 
103
        # 1-shot cache for the call pattern 'create_branch; open_branch' - see
 
104
        # create_branch for details.
 
105
        self._next_open_branch_result = None
84
106
 
85
107
        if _client is None:
86
108
            medium = transport.get_smart_medium()
87
109
            self._client = client._SmartClient(medium)
88
110
        else:
89
111
            self._client = _client
90
 
            return
91
 
 
 
112
            if not _force_probe:
 
113
                return
 
114
 
 
115
        self._probe_bzrdir()
 
116
 
 
117
    def _probe_bzrdir(self):
 
118
        medium = self._client._medium
92
119
        path = self._path_for_remote_call(self._client)
 
120
        if medium._is_remote_before((2, 1)):
 
121
            self._rpc_open(path)
 
122
            return
 
123
        try:
 
124
            self._rpc_open_2_1(path)
 
125
            return
 
126
        except errors.UnknownSmartMethod:
 
127
            medium._remember_remote_is_before((2, 1))
 
128
            self._rpc_open(path)
 
129
 
 
130
    def _rpc_open_2_1(self, path):
 
131
        response = self._call('BzrDir.open_2.1', path)
 
132
        if response == ('no',):
 
133
            raise errors.NotBranchError(path=self.root_transport.base)
 
134
        elif response[0] == 'yes':
 
135
            if response[1] == 'yes':
 
136
                self._has_working_tree = True
 
137
            elif response[1] == 'no':
 
138
                self._has_working_tree = False
 
139
            else:
 
140
                raise errors.UnexpectedSmartServerResponse(response)
 
141
        else:
 
142
            raise errors.UnexpectedSmartServerResponse(response)
 
143
 
 
144
    def _rpc_open(self, path):
93
145
        response = self._call('BzrDir.open', path)
94
146
        if response not in [('yes',), ('no',)]:
95
147
            raise errors.UnexpectedSmartServerResponse(response)
96
148
        if response == ('no',):
97
 
            raise errors.NotBranchError(path=transport.base)
 
149
            raise errors.NotBranchError(path=self.root_transport.base)
98
150
 
99
151
    def _ensure_real(self):
100
152
        """Ensure that there is a _real_bzrdir set.
102
154
        Used before calls to self._real_bzrdir.
103
155
        """
104
156
        if not self._real_bzrdir:
 
157
            if 'hpssvfs' in debug.debug_flags:
 
158
                import traceback
 
159
                warning('VFS BzrDir access triggered\n%s',
 
160
                    ''.join(traceback.format_stack()))
105
161
            self._real_bzrdir = BzrDir.open_from_transport(
106
162
                self.root_transport, _server_formats=False)
 
163
            self._format._network_name = \
 
164
                self._real_bzrdir._format.network_name()
107
165
 
108
166
    def _translate_error(self, err, **context):
109
167
        _translate_error(err, bzrdir=self, **context)
110
168
 
111
 
    def cloning_metadir(self, stacked=False):
 
169
    def break_lock(self):
 
170
        # Prevent aliasing problems in the next_open_branch_result cache.
 
171
        # See create_branch for rationale.
 
172
        self._next_open_branch_result = None
 
173
        return BzrDir.break_lock(self)
 
174
 
 
175
    def _vfs_cloning_metadir(self, require_stacking=False):
112
176
        self._ensure_real()
113
 
        return self._real_bzrdir.cloning_metadir(stacked)
 
177
        return self._real_bzrdir.cloning_metadir(
 
178
            require_stacking=require_stacking)
 
179
 
 
180
    def cloning_metadir(self, require_stacking=False):
 
181
        medium = self._client._medium
 
182
        if medium._is_remote_before((1, 13)):
 
183
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
184
        verb = 'BzrDir.cloning_metadir'
 
185
        if require_stacking:
 
186
            stacking = 'True'
 
187
        else:
 
188
            stacking = 'False'
 
189
        path = self._path_for_remote_call(self._client)
 
190
        try:
 
191
            response = self._call(verb, path, stacking)
 
192
        except errors.UnknownSmartMethod:
 
193
            medium._remember_remote_is_before((1, 13))
 
194
            return self._vfs_cloning_metadir(require_stacking=require_stacking)
 
195
        except errors.UnknownErrorFromSmartServer, err:
 
196
            if err.error_tuple != ('BranchReference',):
 
197
                raise
 
198
            # We need to resolve the branch reference to determine the
 
199
            # cloning_metadir.  This causes unnecessary RPCs to open the
 
200
            # referenced branch (and bzrdir, etc) but only when the caller
 
201
            # didn't already resolve the branch reference.
 
202
            referenced_branch = self.open_branch()
 
203
            return referenced_branch.bzrdir.cloning_metadir()
 
204
        if len(response) != 3:
 
205
            raise errors.UnexpectedSmartServerResponse(response)
 
206
        control_name, repo_name, branch_info = response
 
207
        if len(branch_info) != 2:
 
208
            raise errors.UnexpectedSmartServerResponse(response)
 
209
        branch_ref, branch_name = branch_info
 
210
        format = bzrdir.network_format_registry.get(control_name)
 
211
        if repo_name:
 
212
            format.repository_format = repository.network_format_registry.get(
 
213
                repo_name)
 
214
        if branch_ref == 'ref':
 
215
            # XXX: we need possible_transports here to avoid reopening the
 
216
            # connection to the referenced location
 
217
            ref_bzrdir = BzrDir.open(branch_name)
 
218
            branch_format = ref_bzrdir.cloning_metadir().get_branch_format()
 
219
            format.set_branch_format(branch_format)
 
220
        elif branch_ref == 'branch':
 
221
            if branch_name:
 
222
                format.set_branch_format(
 
223
                    branch.network_format_registry.get(branch_name))
 
224
        else:
 
225
            raise errors.UnexpectedSmartServerResponse(response)
 
226
        return format
114
227
 
115
228
    def create_repository(self, shared=False):
116
 
        self._ensure_real()
117
 
        self._real_bzrdir.create_repository(shared=shared)
118
 
        return self.open_repository()
 
229
        # as per meta1 formats - just delegate to the format object which may
 
230
        # be parameterised.
 
231
        result = self._format.repository_format.initialize(self, shared)
 
232
        if not isinstance(result, RemoteRepository):
 
233
            return self.open_repository()
 
234
        else:
 
235
            return result
119
236
 
120
237
    def destroy_repository(self):
121
238
        """See BzrDir.destroy_repository"""
123
240
        self._real_bzrdir.destroy_repository()
124
241
 
125
242
    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)
 
243
        # as per meta1 formats - just delegate to the format object which may
 
244
        # be parameterised.
 
245
        real_branch = self._format.get_branch_format().initialize(self)
 
246
        if not isinstance(real_branch, RemoteBranch):
 
247
            result = RemoteBranch(self, self.find_repository(), real_branch)
 
248
        else:
 
249
            result = real_branch
 
250
        # BzrDir.clone_on_transport() uses the result of create_branch but does
 
251
        # not return it to its callers; we save approximately 8% of our round
 
252
        # trips by handing the branch we created back to the first caller to
 
253
        # open_branch rather than probing anew. Long term we need a API in
 
254
        # bzrdir that doesn't discard result objects (like result_branch).
 
255
        # RBC 20090225
 
256
        self._next_open_branch_result = result
 
257
        return result
129
258
 
130
259
    def destroy_branch(self):
131
260
        """See BzrDir.destroy_branch"""
132
261
        self._ensure_real()
133
262
        self._real_bzrdir.destroy_branch()
 
263
        self._next_open_branch_result = None
134
264
 
135
265
    def create_workingtree(self, revision_id=None, from_branch=None):
136
266
        raise errors.NotLocalUrl(self.transport.base)
145
275
 
146
276
    def get_branch_reference(self):
147
277
        """See BzrDir.get_branch_reference()."""
 
278
        response = self._get_branch_reference()
 
279
        if response[0] == 'ref':
 
280
            return response[1]
 
281
        else:
 
282
            return None
 
283
 
 
284
    def _get_branch_reference(self):
148
285
        path = self._path_for_remote_call(self._client)
 
286
        medium = self._client._medium
 
287
        if not medium._is_remote_before((1, 13)):
 
288
            try:
 
289
                response = self._call('BzrDir.open_branchV2', path)
 
290
                if response[0] not in ('ref', 'branch'):
 
291
                    raise errors.UnexpectedSmartServerResponse(response)
 
292
                return response
 
293
            except errors.UnknownSmartMethod:
 
294
                medium._remember_remote_is_before((1, 13))
149
295
        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]
 
296
        if response[0] != 'ok':
 
297
            raise errors.UnexpectedSmartServerResponse(response)
 
298
        if response[1] != '':
 
299
            return ('ref', response[1])
157
300
        else:
158
 
            raise errors.UnexpectedSmartServerResponse(response)
 
301
            return ('branch', '')
159
302
 
160
303
    def _get_tree_branch(self):
161
304
        """See BzrDir._get_tree_branch()."""
162
305
        return None, self.open_branch()
163
306
 
164
 
    def open_branch(self, _unsupported=False):
 
307
    def open_branch(self, _unsupported=False, ignore_fallbacks=False):
165
308
        if _unsupported:
166
309
            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:
 
310
        if self._next_open_branch_result is not None:
 
311
            # See create_branch for details.
 
312
            result = self._next_open_branch_result
 
313
            self._next_open_branch_result = None
 
314
            return result
 
315
        response = self._get_branch_reference()
 
316
        if response[0] == 'ref':
172
317
            # a branch reference, use the existing BranchReference logic.
173
318
            format = BranchReferenceFormat()
174
 
            return format.open(self, _found=True, location=reference_url)
175
 
                
 
319
            return format.open(self, _found=True, location=response[1],
 
320
                ignore_fallbacks=ignore_fallbacks)
 
321
        branch_format_name = response[1]
 
322
        if not branch_format_name:
 
323
            branch_format_name = None
 
324
        format = RemoteBranchFormat(network_name=branch_format_name)
 
325
        return RemoteBranch(self, self.find_repository(), format=format,
 
326
            setup_stacking=not ignore_fallbacks)
 
327
 
 
328
    def _open_repo_v1(self, path):
 
329
        verb = 'BzrDir.find_repository'
 
330
        response = self._call(verb, path)
 
331
        if response[0] != 'ok':
 
332
            raise errors.UnexpectedSmartServerResponse(response)
 
333
        # servers that only support the v1 method don't support external
 
334
        # references either.
 
335
        self._ensure_real()
 
336
        repo = self._real_bzrdir.open_repository()
 
337
        response = response + ('no', repo._format.network_name())
 
338
        return response, repo
 
339
 
 
340
    def _open_repo_v2(self, path):
 
341
        verb = 'BzrDir.find_repositoryV2'
 
342
        response = self._call(verb, path)
 
343
        if response[0] != 'ok':
 
344
            raise errors.UnexpectedSmartServerResponse(response)
 
345
        self._ensure_real()
 
346
        repo = self._real_bzrdir.open_repository()
 
347
        response = response + (repo._format.network_name(),)
 
348
        return response, repo
 
349
 
 
350
    def _open_repo_v3(self, path):
 
351
        verb = 'BzrDir.find_repositoryV3'
 
352
        medium = self._client._medium
 
353
        if medium._is_remote_before((1, 13)):
 
354
            raise errors.UnknownSmartMethod(verb)
 
355
        try:
 
356
            response = self._call(verb, path)
 
357
        except errors.UnknownSmartMethod:
 
358
            medium._remember_remote_is_before((1, 13))
 
359
            raise
 
360
        if response[0] != 'ok':
 
361
            raise errors.UnexpectedSmartServerResponse(response)
 
362
        return response, None
 
363
 
176
364
    def open_repository(self):
177
365
        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)
 
366
        response = None
 
367
        for probe in [self._open_repo_v3, self._open_repo_v2,
 
368
            self._open_repo_v1]:
 
369
            try:
 
370
                response, real_repo = probe(path)
 
371
                break
 
372
            except errors.UnknownSmartMethod:
 
373
                pass
 
374
        if response is None:
 
375
            raise errors.UnknownSmartMethod('BzrDir.find_repository{3,2,}')
184
376
        if response[0] != 'ok':
185
377
            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):
 
378
        if len(response) != 6:
191
379
            raise SmartProtocolError('incorrect response length %s' % (response,))
192
380
        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')
 
381
            # repo is at this dir.
 
382
            format = response_tuple_to_repo_format(response[2:])
198
383
            # Used to support creating a real format instance when needed.
199
384
            format._creating_bzrdir = self
200
 
            return RemoteRepository(self, format)
 
385
            remote_repo = RemoteRepository(self, format)
 
386
            format._creating_repo = remote_repo
 
387
            if real_repo is not None:
 
388
                remote_repo._set_real_repository(real_repo)
 
389
            return remote_repo
201
390
        else:
202
391
            raise errors.NoRepositoryPresent(self)
203
392
 
 
393
    def has_workingtree(self):
 
394
        if self._has_working_tree is None:
 
395
            self._ensure_real()
 
396
            self._has_working_tree = self._real_bzrdir.has_workingtree()
 
397
        return self._has_working_tree
 
398
 
204
399
    def open_workingtree(self, recommend_upgrade=True):
205
 
        self._ensure_real()
206
 
        if self._real_bzrdir.has_workingtree():
 
400
        if self.has_workingtree():
207
401
            raise errors.NotLocalUrl(self.root_transport)
208
402
        else:
209
403
            raise errors.NoWorkingTree(self.root_transport.base)
241
435
        return self._real_bzrdir.clone(url, revision_id=revision_id,
242
436
            force_new_repo=force_new_repo, preserve_stacking=preserve_stacking)
243
437
 
244
 
    def get_config(self):
245
 
        self._ensure_real()
246
 
        return self._real_bzrdir.get_config()
 
438
    def _get_config(self):
 
439
        return RemoteBzrDirConfig(self)
247
440
 
248
441
 
249
442
class RemoteRepositoryFormat(repository.RepositoryFormat):
257
450
    the attributes rich_root_data and supports_tree_reference are set
258
451
    on a per instance basis, and are not set (and should not be) at
259
452
    the class level.
 
453
 
 
454
    :ivar _custom_format: If set, a specific concrete repository format that
 
455
        will be used when initializing a repository with this
 
456
        RemoteRepositoryFormat.
 
457
    :ivar _creating_repo: If set, the repository object that this
 
458
        RemoteRepositoryFormat was created for: it can be called into
 
459
        to obtain data like the network name.
260
460
    """
261
461
 
262
462
    _matchingbzrdir = RemoteBzrDirFormat()
263
463
 
264
 
    def initialize(self, a_bzrdir, shared=False):
265
 
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
464
    def __init__(self):
 
465
        repository.RepositoryFormat.__init__(self)
 
466
        self._custom_format = None
 
467
        self._network_name = None
 
468
        self._creating_bzrdir = None
 
469
        self._supports_chks = None
 
470
        self._supports_external_lookups = None
 
471
        self._supports_tree_reference = None
 
472
        self._rich_root_data = None
 
473
 
 
474
    def __repr__(self):
 
475
        return "%s(_network_name=%r)" % (self.__class__.__name__,
 
476
            self._network_name)
 
477
 
 
478
    @property
 
479
    def fast_deltas(self):
 
480
        self._ensure_real()
 
481
        return self._custom_format.fast_deltas
 
482
 
 
483
    @property
 
484
    def rich_root_data(self):
 
485
        if self._rich_root_data is None:
 
486
            self._ensure_real()
 
487
            self._rich_root_data = self._custom_format.rich_root_data
 
488
        return self._rich_root_data
 
489
 
 
490
    @property
 
491
    def supports_chks(self):
 
492
        if self._supports_chks is None:
 
493
            self._ensure_real()
 
494
            self._supports_chks = self._custom_format.supports_chks
 
495
        return self._supports_chks
 
496
 
 
497
    @property
 
498
    def supports_external_lookups(self):
 
499
        if self._supports_external_lookups is None:
 
500
            self._ensure_real()
 
501
            self._supports_external_lookups = \
 
502
                self._custom_format.supports_external_lookups
 
503
        return self._supports_external_lookups
 
504
 
 
505
    @property
 
506
    def supports_tree_reference(self):
 
507
        if self._supports_tree_reference is None:
 
508
            self._ensure_real()
 
509
            self._supports_tree_reference = \
 
510
                self._custom_format.supports_tree_reference
 
511
        return self._supports_tree_reference
 
512
 
 
513
    def _vfs_initialize(self, a_bzrdir, shared):
 
514
        """Helper for common code in initialize."""
 
515
        if self._custom_format:
 
516
            # Custom format requested
 
517
            result = self._custom_format.initialize(a_bzrdir, shared=shared)
 
518
        elif self._creating_bzrdir is not None:
 
519
            # Use the format that the repository we were created to back
 
520
            # has.
266
521
            prior_repo = self._creating_bzrdir.open_repository()
267
522
            prior_repo._ensure_real()
268
 
            return prior_repo._real_repository._format.initialize(
 
523
            result = prior_repo._real_repository._format.initialize(
269
524
                a_bzrdir, shared=shared)
270
 
        return a_bzrdir.create_repository(shared=shared)
271
 
    
 
525
        else:
 
526
            # assume that a_bzr is a RemoteBzrDir but the smart server didn't
 
527
            # support remote initialization.
 
528
            # We delegate to a real object at this point (as RemoteBzrDir
 
529
            # delegate to the repository format which would lead to infinite
 
530
            # recursion if we just called a_bzrdir.create_repository.
 
531
            a_bzrdir._ensure_real()
 
532
            result = a_bzrdir._real_bzrdir.create_repository(shared=shared)
 
533
        if not isinstance(result, RemoteRepository):
 
534
            return self.open(a_bzrdir)
 
535
        else:
 
536
            return result
 
537
 
 
538
    def initialize(self, a_bzrdir, shared=False):
 
539
        # Being asked to create on a non RemoteBzrDir:
 
540
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
541
            return self._vfs_initialize(a_bzrdir, shared)
 
542
        medium = a_bzrdir._client._medium
 
543
        if medium._is_remote_before((1, 13)):
 
544
            return self._vfs_initialize(a_bzrdir, shared)
 
545
        # Creating on a remote bzr dir.
 
546
        # 1) get the network name to use.
 
547
        if self._custom_format:
 
548
            network_name = self._custom_format.network_name()
 
549
        elif self._network_name:
 
550
            network_name = self._network_name
 
551
        else:
 
552
            # Select the current bzrlib default and ask for that.
 
553
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
554
            reference_format = reference_bzrdir_format.repository_format
 
555
            network_name = reference_format.network_name()
 
556
        # 2) try direct creation via RPC
 
557
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
558
        verb = 'BzrDir.create_repository'
 
559
        if shared:
 
560
            shared_str = 'True'
 
561
        else:
 
562
            shared_str = 'False'
 
563
        try:
 
564
            response = a_bzrdir._call(verb, path, network_name, shared_str)
 
565
        except errors.UnknownSmartMethod:
 
566
            # Fallback - use vfs methods
 
567
            medium._remember_remote_is_before((1, 13))
 
568
            return self._vfs_initialize(a_bzrdir, shared)
 
569
        else:
 
570
            # Turn the response into a RemoteRepository object.
 
571
            format = response_tuple_to_repo_format(response[1:])
 
572
            # Used to support creating a real format instance when needed.
 
573
            format._creating_bzrdir = a_bzrdir
 
574
            remote_repo = RemoteRepository(a_bzrdir, format)
 
575
            format._creating_repo = remote_repo
 
576
            return remote_repo
 
577
 
272
578
    def open(self, a_bzrdir):
273
579
        if not isinstance(a_bzrdir, RemoteBzrDir):
274
580
            raise AssertionError('%r is not a RemoteBzrDir' % (a_bzrdir,))
275
581
        return a_bzrdir.open_repository()
276
582
 
 
583
    def _ensure_real(self):
 
584
        if self._custom_format is None:
 
585
            self._custom_format = repository.network_format_registry.get(
 
586
                self._network_name)
 
587
 
 
588
    @property
 
589
    def _fetch_order(self):
 
590
        self._ensure_real()
 
591
        return self._custom_format._fetch_order
 
592
 
 
593
    @property
 
594
    def _fetch_uses_deltas(self):
 
595
        self._ensure_real()
 
596
        return self._custom_format._fetch_uses_deltas
 
597
 
 
598
    @property
 
599
    def _fetch_reconcile(self):
 
600
        self._ensure_real()
 
601
        return self._custom_format._fetch_reconcile
 
602
 
277
603
    def get_format_description(self):
278
 
        return 'bzr remote repository'
 
604
        self._ensure_real()
 
605
        return 'Remote: ' + self._custom_format.get_format_description()
279
606
 
280
607
    def __eq__(self, other):
281
 
        return self.__class__ == other.__class__
282
 
 
283
 
    def check_conversion_target(self, target_format):
284
 
        if self.rich_root_data and not target_format.rich_root_data:
285
 
            raise errors.BadConversionTarget(
286
 
                'Does not support rich root data.', target_format)
287
 
        if (self.supports_tree_reference and
288
 
            not getattr(target_format, 'supports_tree_reference', False)):
289
 
            raise errors.BadConversionTarget(
290
 
                'Does not support nested trees', target_format)
291
 
 
292
 
 
293
 
class RemoteRepository(_RpcHelper):
 
608
        return self.__class__ is other.__class__
 
609
 
 
610
    def network_name(self):
 
611
        if self._network_name:
 
612
            return self._network_name
 
613
        self._creating_repo._ensure_real()
 
614
        return self._creating_repo._real_repository._format.network_name()
 
615
 
 
616
    @property
 
617
    def pack_compresses(self):
 
618
        self._ensure_real()
 
619
        return self._custom_format.pack_compresses
 
620
 
 
621
    @property
 
622
    def _serializer(self):
 
623
        self._ensure_real()
 
624
        return self._custom_format._serializer
 
625
 
 
626
 
 
627
class RemoteRepository(_RpcHelper, lock._RelockDebugMixin):
294
628
    """Repository accessed over rpc.
295
629
 
296
630
    For the moment most operations are performed using local transport-backed
299
633
 
300
634
    def __init__(self, remote_bzrdir, format, real_repository=None, _client=None):
301
635
        """Create a RemoteRepository instance.
302
 
        
 
636
 
303
637
        :param remote_bzrdir: The bzrdir hosting this repository.
304
638
        :param format: The RemoteFormat object to use.
305
639
        :param real_repository: If not None, a local implementation of the
322
656
        self._lock_token = None
323
657
        self._lock_count = 0
324
658
        self._leave_lock = False
 
659
        # Cache of revision parents; misses are cached during read locks, and
 
660
        # write locks when no _real_repository has been set.
325
661
        self._unstacked_provider = graph.CachingParentsProvider(
326
662
            get_parent_map=self._get_parent_map_rpc)
327
663
        self._unstacked_provider.disable_cache()
344
680
 
345
681
    def abort_write_group(self, suppress_errors=False):
346
682
        """Complete a write group on the decorated repository.
347
 
        
348
 
        Smart methods peform operations in a single step so this api
 
683
 
 
684
        Smart methods perform operations in a single step so this API
349
685
        is not really applicable except as a compatibility thunk
350
686
        for older plugins that don't use e.g. the CommitBuilder
351
687
        facility.
356
692
        return self._real_repository.abort_write_group(
357
693
            suppress_errors=suppress_errors)
358
694
 
 
695
    @property
 
696
    def chk_bytes(self):
 
697
        """Decorate the real repository for now.
 
698
 
 
699
        In the long term a full blown network facility is needed to avoid
 
700
        creating a real repository object locally.
 
701
        """
 
702
        self._ensure_real()
 
703
        return self._real_repository.chk_bytes
 
704
 
359
705
    def commit_write_group(self):
360
706
        """Complete a write group on the decorated repository.
361
 
        
362
 
        Smart methods peform operations in a single step so this api
 
707
 
 
708
        Smart methods perform operations in a single step so this API
363
709
        is not really applicable except as a compatibility thunk
364
710
        for older plugins that don't use e.g. the CommitBuilder
365
711
        facility.
367
713
        self._ensure_real()
368
714
        return self._real_repository.commit_write_group()
369
715
 
 
716
    def resume_write_group(self, tokens):
 
717
        self._ensure_real()
 
718
        return self._real_repository.resume_write_group(tokens)
 
719
 
 
720
    def suspend_write_group(self):
 
721
        self._ensure_real()
 
722
        return self._real_repository.suspend_write_group()
 
723
 
 
724
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
725
        self._ensure_real()
 
726
        return self._real_repository.get_missing_parent_inventories(
 
727
            check_for_missing_texts=check_for_missing_texts)
 
728
 
 
729
    def _get_rev_id_for_revno_vfs(self, revno, known_pair):
 
730
        self._ensure_real()
 
731
        return self._real_repository.get_rev_id_for_revno(
 
732
            revno, known_pair)
 
733
 
 
734
    def get_rev_id_for_revno(self, revno, known_pair):
 
735
        """See Repository.get_rev_id_for_revno."""
 
736
        path = self.bzrdir._path_for_remote_call(self._client)
 
737
        try:
 
738
            if self._client._medium._is_remote_before((1, 17)):
 
739
                return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
740
            response = self._call(
 
741
                'Repository.get_rev_id_for_revno', path, revno, known_pair)
 
742
        except errors.UnknownSmartMethod:
 
743
            self._client._medium._remember_remote_is_before((1, 17))
 
744
            return self._get_rev_id_for_revno_vfs(revno, known_pair)
 
745
        if response[0] == 'ok':
 
746
            return True, response[1]
 
747
        elif response[0] == 'history-incomplete':
 
748
            known_pair = response[1:3]
 
749
            for fallback in self._fallback_repositories:
 
750
                found, result = fallback.get_rev_id_for_revno(revno, known_pair)
 
751
                if found:
 
752
                    return True, result
 
753
                else:
 
754
                    known_pair = result
 
755
            # Not found in any fallbacks
 
756
            return False, known_pair
 
757
        else:
 
758
            raise errors.UnexpectedSmartServerResponse(response)
 
759
 
370
760
    def _ensure_real(self):
371
761
        """Ensure that there is a _real_repository set.
372
762
 
373
763
        Used before calls to self._real_repository.
 
764
 
 
765
        Note that _ensure_real causes many roundtrips to the server which are
 
766
        not desirable, and prevents the use of smart one-roundtrip RPC's to
 
767
        perform complex operations (such as accessing parent data, streaming
 
768
        revisions etc). Adding calls to _ensure_real should only be done when
 
769
        bringing up new functionality, adding fallbacks for smart methods that
 
770
        require a fallback path, and never to replace an existing smart method
 
771
        invocation. If in doubt chat to the bzr network team.
374
772
        """
375
773
        if self._real_repository is None:
 
774
            if 'hpssvfs' in debug.debug_flags:
 
775
                import traceback
 
776
                warning('VFS Repository access triggered\n%s',
 
777
                    ''.join(traceback.format_stack()))
 
778
            self._unstacked_provider.missing_keys.clear()
376
779
            self.bzrdir._ensure_real()
377
780
            self._set_real_repository(
378
781
                self.bzrdir._real_bzrdir.open_repository())
405
808
        self._ensure_real()
406
809
        return self._real_repository._generate_text_key_index()
407
810
 
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
811
    def _get_revision_graph(self, revision_id):
414
812
        """Private method for using with old (< 1.2) servers to fallback."""
415
813
        if revision_id is None:
432
830
        for line in lines:
433
831
            d = tuple(line.split())
434
832
            revision_graph[d[0]] = d[1:]
435
 
            
 
833
 
436
834
        return revision_graph
437
835
 
 
836
    def _get_sink(self):
 
837
        """See Repository._get_sink()."""
 
838
        return RemoteStreamSink(self)
 
839
 
 
840
    def _get_source(self, to_format):
 
841
        """Return a source for streaming from this repository."""
 
842
        return RemoteStreamSource(self, to_format)
 
843
 
 
844
    @needs_read_lock
438
845
    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
 
846
        """True if this repository has a copy of the revision."""
 
847
        # Copy of bzrlib.repository.Repository.has_revision
 
848
        return revision_id in self.has_revisions((revision_id,))
453
849
 
 
850
    @needs_read_lock
454
851
    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)
 
852
        """Probe to find out the presence of multiple revisions.
 
853
 
 
854
        :param revision_ids: An iterable of revision_ids.
 
855
        :return: A set of the revision_ids that were present.
 
856
        """
 
857
        # Copy of bzrlib.repository.Repository.has_revisions
 
858
        parent_map = self.get_parent_map(revision_ids)
 
859
        result = set(parent_map)
 
860
        if _mod_revision.NULL_REVISION in revision_ids:
 
861
            result.add(_mod_revision.NULL_REVISION)
462
862
        return result
463
863
 
 
864
    def _has_same_fallbacks(self, other_repo):
 
865
        """Returns true if the repositories have the same fallbacks."""
 
866
        # XXX: copied from Repository; it should be unified into a base class
 
867
        # <https://bugs.edge.launchpad.net/bzr/+bug/401622>
 
868
        my_fb = self._fallback_repositories
 
869
        other_fb = other_repo._fallback_repositories
 
870
        if len(my_fb) != len(other_fb):
 
871
            return False
 
872
        for f, g in zip(my_fb, other_fb):
 
873
            if not f.has_same_location(g):
 
874
                return False
 
875
        return True
 
876
 
464
877
    def has_same_location(self, other):
465
 
        return (self.__class__ == other.__class__ and
 
878
        # TODO: Move to RepositoryBase and unify with the regular Repository
 
879
        # one; unfortunately the tests rely on slightly different behaviour at
 
880
        # present -- mbp 20090710
 
881
        return (self.__class__ is other.__class__ and
466
882
                self.bzrdir.transport.base == other.bzrdir.transport.base)
467
883
 
468
884
    def get_graph(self, other_repository=None):
535
951
    def is_write_locked(self):
536
952
        return self._lock_mode == 'w'
537
953
 
 
954
    def _warn_if_deprecated(self, branch=None):
 
955
        # If we have a real repository, the check will be done there, if we
 
956
        # don't the check will be done remotely.
 
957
        pass
 
958
 
538
959
    def lock_read(self):
539
960
        # wrong eventually - want a local lock cache context
540
961
        if not self._lock_mode:
 
962
            self._note_lock('r')
541
963
            self._lock_mode = 'r'
542
964
            self._lock_count = 1
543
 
            self._unstacked_provider.enable_cache(cache_misses=False)
 
965
            self._unstacked_provider.enable_cache(cache_misses=True)
544
966
            if self._real_repository is not None:
545
967
                self._real_repository.lock_read()
 
968
            for repo in self._fallback_repositories:
 
969
                repo.lock_read()
546
970
        else:
547
971
            self._lock_count += 1
548
972
 
561
985
 
562
986
    def lock_write(self, token=None, _skip_rpc=False):
563
987
        if not self._lock_mode:
 
988
            self._note_lock('w')
564
989
            if _skip_rpc:
565
990
                if self._lock_token is not None:
566
991
                    if token != self._lock_token:
580
1005
                self._leave_lock = False
581
1006
            self._lock_mode = 'w'
582
1007
            self._lock_count = 1
583
 
            self._unstacked_provider.enable_cache(cache_misses=False)
 
1008
            cache_misses = self._real_repository is None
 
1009
            self._unstacked_provider.enable_cache(cache_misses=cache_misses)
 
1010
            for repo in self._fallback_repositories:
 
1011
                # Writes don't affect fallback repos
 
1012
                repo.lock_read()
584
1013
        elif self._lock_mode == 'r':
585
1014
            raise errors.ReadOnlyError(self)
586
1015
        else:
604
1033
            implemented operations.
605
1034
        """
606
1035
        if self._real_repository is not None:
607
 
            raise AssertionError('_real_repository is already set')
 
1036
            # Replacing an already set real repository.
 
1037
            # We cannot do this [currently] if the repository is locked -
 
1038
            # synchronised state might be lost.
 
1039
            if self.is_locked():
 
1040
                raise AssertionError('_real_repository is already set')
608
1041
        if isinstance(repository, RemoteRepository):
609
1042
            raise AssertionError()
610
1043
        self._real_repository = repository
 
1044
        # three code paths happen here:
 
1045
        # 1) old servers, RemoteBranch.open() calls _ensure_real before setting
 
1046
        # up stacking. In this case self._fallback_repositories is [], and the
 
1047
        # real repo is already setup. Preserve the real repo and
 
1048
        # RemoteRepository.add_fallback_repository will avoid adding
 
1049
        # duplicates.
 
1050
        # 2) new servers, RemoteBranch.open() sets up stacking, and when
 
1051
        # ensure_real is triggered from a branch, the real repository to
 
1052
        # set already has a matching list with separate instances, but
 
1053
        # as they are also RemoteRepositories we don't worry about making the
 
1054
        # lists be identical.
 
1055
        # 3) new servers, RemoteRepository.ensure_real is triggered before
 
1056
        # RemoteBranch.ensure real, in this case we get a repo with no fallbacks
 
1057
        # and need to populate it.
 
1058
        if (self._fallback_repositories and
 
1059
            len(self._real_repository._fallback_repositories) !=
 
1060
            len(self._fallback_repositories)):
 
1061
            if len(self._real_repository._fallback_repositories):
 
1062
                raise AssertionError(
 
1063
                    "cannot cleanly remove existing _fallback_repositories")
611
1064
        for fb in self._fallback_repositories:
612
1065
            self._real_repository.add_fallback_repository(fb)
613
1066
        if self._lock_mode == 'w':
619
1072
 
620
1073
    def start_write_group(self):
621
1074
        """Start a write group on the decorated repository.
622
 
        
623
 
        Smart methods peform operations in a single step so this api
 
1075
 
 
1076
        Smart methods perform operations in a single step so this API
624
1077
        is not really applicable except as a compatibility thunk
625
1078
        for older plugins that don't use e.g. the CommitBuilder
626
1079
        facility.
641
1094
        else:
642
1095
            raise errors.UnexpectedSmartServerResponse(response)
643
1096
 
 
1097
    @only_raises(errors.LockNotHeld, errors.LockBroken)
644
1098
    def unlock(self):
 
1099
        if not self._lock_count:
 
1100
            return lock.cant_unlock_not_held(self)
645
1101
        self._lock_count -= 1
646
1102
        if self._lock_count > 0:
647
1103
            return
661
1117
            # problem releasing the vfs-based lock.
662
1118
            if old_mode == 'w':
663
1119
                # Only write-locked repositories need to make a remote method
664
 
                # call to perfom the unlock.
 
1120
                # call to perform the unlock.
665
1121
                old_token = self._lock_token
666
1122
                self._lock_token = None
667
1123
                if not self._leave_lock:
668
1124
                    self._unlock(old_token)
 
1125
        # Fallbacks are always 'lock_read()' so we don't pay attention to
 
1126
        # self._leave_lock
 
1127
        for repo in self._fallback_repositories:
 
1128
            repo.unlock()
669
1129
 
670
1130
    def break_lock(self):
671
1131
        # should hand off to the network
674
1134
 
675
1135
    def _get_tarball(self, compression):
676
1136
        """Return a TemporaryFile containing a repository tarball.
677
 
        
 
1137
 
678
1138
        Returns None if the server does not support sending tarballs.
679
1139
        """
680
1140
        import tempfile
726
1186
 
727
1187
    def add_fallback_repository(self, repository):
728
1188
        """Add a repository to use for looking up data not held locally.
729
 
        
 
1189
 
730
1190
        :param repository: A repository.
731
1191
        """
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
 
        #
 
1192
        if not self._format.supports_external_lookups:
 
1193
            raise errors.UnstackableRepositoryFormat(
 
1194
                self._format.network_name(), self.base)
738
1195
        # We need to accumulate additional repositories here, to pass them in
739
1196
        # on various RPC's.
 
1197
        #
 
1198
        if self.is_locked():
 
1199
            # We will call fallback.unlock() when we transition to the unlocked
 
1200
            # state, so always add a lock here. If a caller passes us a locked
 
1201
            # repository, they are responsible for unlocking it later.
 
1202
            repository.lock_read()
740
1203
        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()
 
1204
        # If self._real_repository was parameterised already (e.g. because a
 
1205
        # _real_branch had its get_stacked_on_url method called), then the
 
1206
        # repository to be added may already be in the _real_repositories list.
 
1207
        if self._real_repository is not None:
 
1208
            fallback_locations = [repo.bzrdir.root_transport.base for repo in
 
1209
                self._real_repository._fallback_repositories]
 
1210
            if repository.bzrdir.root_transport.base not in fallback_locations:
 
1211
                self._real_repository.add_fallback_repository(repository)
744
1212
 
745
1213
    def add_inventory(self, revid, inv, parents):
746
1214
        self._ensure_real()
762
1230
        self._ensure_real()
763
1231
        return self._real_repository.get_inventory(revision_id)
764
1232
 
765
 
    def iter_inventories(self, revision_ids):
 
1233
    def iter_inventories(self, revision_ids, ordering=None):
766
1234
        self._ensure_real()
767
 
        return self._real_repository.iter_inventories(revision_ids)
 
1235
        return self._real_repository.iter_inventories(revision_ids, ordering)
768
1236
 
769
1237
    @needs_read_lock
770
1238
    def get_revision(self, revision_id):
785
1253
        self._ensure_real()
786
1254
        return self._real_repository.make_working_trees()
787
1255
 
 
1256
    def refresh_data(self):
 
1257
        """Re-read any data needed to to synchronise with disk.
 
1258
 
 
1259
        This method is intended to be called after another repository instance
 
1260
        (such as one used by a smart server) has inserted data into the
 
1261
        repository. It may not be called during a write group, but may be
 
1262
        called at any other time.
 
1263
        """
 
1264
        if self.is_in_write_group():
 
1265
            raise errors.InternalBzrError(
 
1266
                "May not refresh_data while in a write group.")
 
1267
        if self._real_repository is not None:
 
1268
            self._real_repository.refresh_data()
 
1269
 
788
1270
    def revision_ids_to_search_result(self, result_set):
789
1271
        """Convert a set of revision ids to a graph SearchResult."""
790
1272
        result_parents = set()
801
1283
    @needs_read_lock
802
1284
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
803
1285
        """Return the revision ids that other has that this does not.
804
 
        
 
1286
 
805
1287
        These are returned in topological order.
806
1288
 
807
1289
        revision_id: only return revision ids included by revision_id.
809
1291
        return repository.InterRepository.get(
810
1292
            other, self).search_missing_revision_ids(revision_id, find_ghosts)
811
1293
 
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):
 
1294
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
1295
            fetch_spec=None):
 
1296
        # No base implementation to use as RemoteRepository is not a subclass
 
1297
        # of Repository; so this is a copy of Repository.fetch().
 
1298
        if fetch_spec is not None and revision_id is not None:
 
1299
            raise AssertionError(
 
1300
                "fetch_spec and revision_id are mutually exclusive.")
 
1301
        if self.is_in_write_group():
 
1302
            raise errors.InternalBzrError(
 
1303
                "May not fetch while in a write group.")
 
1304
        # fast path same-url fetch operations
 
1305
        if (self.has_same_location(source)
 
1306
            and fetch_spec is None
 
1307
            and self._has_same_fallbacks(source)):
816
1308
            # check that last_revision is in 'from' and then return a
817
1309
            # no-operation.
818
1310
            if (revision_id is not None and
819
1311
                not revision.is_null(revision_id)):
820
1312
                self.get_revision(revision_id)
821
1313
            return 0, []
 
1314
        # if there is no specific appropriate InterRepository, this will get
 
1315
        # the InterRepository base class, which raises an
 
1316
        # IncompatibleRepositories when asked to fetch.
822
1317
        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)
 
1318
        return inter.fetch(revision_id=revision_id, pb=pb,
 
1319
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
827
1320
 
828
1321
    def create_bundle(self, target, base, fileobj, format=None):
829
1322
        self._ensure_real()
842
1335
        self._ensure_real()
843
1336
        return self._real_repository._get_versioned_file_checker(
844
1337
            revisions, revision_versions_cache)
845
 
        
 
1338
 
846
1339
    def iter_files_bytes(self, desired_files):
847
1340
        """See Repository.iter_file_bytes.
848
1341
        """
849
1342
        self._ensure_real()
850
1343
        return self._real_repository.iter_files_bytes(desired_files)
851
1344
 
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
1345
    def get_parent_map(self, revision_ids):
883
1346
        """See bzrlib.Graph.get_parent_map()."""
884
1347
        return self._make_parents_provider().get_parent_map(revision_ids)
890
1353
            # We already found out that the server can't understand
891
1354
            # Repository.get_parent_map requests, so just fetch the whole
892
1355
            # 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
 
1356
            #
 
1357
            # Note that this reads the whole graph, when only some keys are
 
1358
            # wanted.  On this old server there's no way (?) to get them all
 
1359
            # in one go, and the user probably will have seen a warning about
 
1360
            # the server being old anyhow.
 
1361
            rg = self._get_revision_graph(None)
 
1362
            # There is an API discrepancy between get_parent_map and
899
1363
            # get_revision_graph. Specifically, a "key:()" pair in
900
1364
            # get_revision_graph just means a node has no parents. For
901
1365
            # "get_parent_map" it means the node is a ghost. So fix up the
931
1395
        # TODO: Manage this incrementally to avoid covering the same path
932
1396
        # repeatedly. (The server will have to on each request, but the less
933
1397
        # work done the better).
 
1398
        #
 
1399
        # Negative caching notes:
 
1400
        # new server sends missing when a request including the revid
 
1401
        # 'include-missing:' is present in the request.
 
1402
        # missing keys are serialised as missing:X, and we then call
 
1403
        # provider.note_missing(X) for-all X
934
1404
        parents_map = self._unstacked_provider.get_cached_map()
935
1405
        if parents_map is None:
936
1406
            # Repository is not locked, so there's no cache.
937
1407
            parents_map = {}
 
1408
        # start_set is all the keys in the cache
938
1409
        start_set = set(parents_map)
 
1410
        # result set is all the references to keys in the cache
939
1411
        result_parents = set()
940
1412
        for parents in parents_map.itervalues():
941
1413
            result_parents.update(parents)
942
1414
        stop_keys = result_parents.difference(start_set)
 
1415
        # We don't need to send ghosts back to the server as a position to
 
1416
        # stop either.
 
1417
        stop_keys.difference_update(self._unstacked_provider.missing_keys)
 
1418
        key_count = len(parents_map)
 
1419
        if (NULL_REVISION in result_parents
 
1420
            and NULL_REVISION in self._unstacked_provider.missing_keys):
 
1421
            # If we pruned NULL_REVISION from the stop_keys because it's also
 
1422
            # in our cache of "missing" keys we need to increment our key count
 
1423
            # by 1, because the reconsitituted SearchResult on the server will
 
1424
            # still consider NULL_REVISION to be an included key.
 
1425
            key_count += 1
943
1426
        included_keys = start_set.intersection(result_parents)
944
1427
        start_set.difference_update(included_keys)
945
 
        recipe = (start_set, stop_keys, len(parents_map))
 
1428
        recipe = ('manual', start_set, stop_keys, key_count)
946
1429
        body = self._serialise_search_recipe(recipe)
947
1430
        path = self.bzrdir._path_for_remote_call(self._client)
948
1431
        for key in keys:
950
1433
                raise ValueError(
951
1434
                    "key %r not a plain string" % (key,))
952
1435
        verb = 'Repository.get_parent_map'
953
 
        args = (path,) + tuple(keys)
 
1436
        args = (path, 'include-missing:') + tuple(keys)
954
1437
        try:
955
1438
            response = self._call_with_body_bytes_expecting_body(
956
1439
                verb, args, body)
966
1449
            # To avoid having to disconnect repeatedly, we keep track of the
967
1450
            # fact the server doesn't understand remote methods added in 1.2.
968
1451
            medium._remember_remote_is_before((1, 2))
969
 
            return self.get_revision_graph(None)
 
1452
            # Recurse just once and we should use the fallback code.
 
1453
            return self._get_parent_map_rpc(keys)
970
1454
        response_tuple, response_handler = response
971
1455
        if response_tuple[0] not in ['ok']:
972
1456
            response_handler.cancel_read_body()
983
1467
                if len(d) > 1:
984
1468
                    revision_graph[d[0]] = d[1:]
985
1469
                else:
986
 
                    # No parents - so give the Graph result (NULL_REVISION,).
987
 
                    revision_graph[d[0]] = (NULL_REVISION,)
 
1470
                    # No parents:
 
1471
                    if d[0].startswith('missing:'):
 
1472
                        revid = d[0][8:]
 
1473
                        self._unstacked_provider.note_missing_key(revid)
 
1474
                    else:
 
1475
                        # no parents - so give the Graph result
 
1476
                        # (NULL_REVISION,).
 
1477
                        revision_graph[d[0]] = (NULL_REVISION,)
988
1478
            return revision_graph
989
1479
 
990
1480
    @needs_read_lock
993
1483
        return self._real_repository.get_signature_text(revision_id)
994
1484
 
995
1485
    @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
1486
    def get_inventory_xml(self, revision_id):
1004
1487
        self._ensure_real()
1005
1488
        return self._real_repository.get_inventory_xml(revision_id)
1011
1494
    def reconcile(self, other=None, thorough=False):
1012
1495
        self._ensure_real()
1013
1496
        return self._real_repository.reconcile(other=other, thorough=thorough)
1014
 
        
 
1497
 
1015
1498
    def all_revision_ids(self):
1016
1499
        self._ensure_real()
1017
1500
        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)
 
1501
 
 
1502
    @needs_read_lock
 
1503
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
 
1504
        self._ensure_real()
 
1505
        return self._real_repository.get_deltas_for_revisions(revisions,
 
1506
            specific_fileids=specific_fileids)
 
1507
 
 
1508
    @needs_read_lock
 
1509
    def get_revision_delta(self, revision_id, specific_fileids=None):
 
1510
        self._ensure_real()
 
1511
        return self._real_repository.get_revision_delta(revision_id,
 
1512
            specific_fileids=specific_fileids)
1028
1513
 
1029
1514
    @needs_read_lock
1030
1515
    def revision_trees(self, revision_ids):
1037
1522
        return self._real_repository.get_revision_reconcile(revision_id)
1038
1523
 
1039
1524
    @needs_read_lock
1040
 
    def check(self, revision_ids=None):
 
1525
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
1041
1526
        self._ensure_real()
1042
 
        return self._real_repository.check(revision_ids=revision_ids)
 
1527
        return self._real_repository.check(revision_ids=revision_ids,
 
1528
            callback_refs=callback_refs, check_repo=check_repo)
1043
1529
 
1044
1530
    def copy_content_into(self, destination, revision_id=None):
1045
1531
        self._ensure_real()
1085
1571
        return self._real_repository.inventories
1086
1572
 
1087
1573
    @needs_write_lock
1088
 
    def pack(self):
 
1574
    def pack(self, hint=None):
1089
1575
        """Compress the data within the repository.
1090
1576
 
1091
1577
        This is not currently implemented within the smart server.
1092
1578
        """
1093
1579
        self._ensure_real()
1094
 
        return self._real_repository.pack()
 
1580
        return self._real_repository.pack(hint=hint)
1095
1581
 
1096
1582
    @property
1097
1583
    def revisions(self):
1106
1592
        return self._real_repository.revisions
1107
1593
 
1108
1594
    def set_make_working_trees(self, new_value):
1109
 
        self._ensure_real()
1110
 
        self._real_repository.set_make_working_trees(new_value)
 
1595
        if new_value:
 
1596
            new_value_str = "True"
 
1597
        else:
 
1598
            new_value_str = "False"
 
1599
        path = self.bzrdir._path_for_remote_call(self._client)
 
1600
        try:
 
1601
            response = self._call(
 
1602
                'Repository.set_make_working_trees', path, new_value_str)
 
1603
        except errors.UnknownSmartMethod:
 
1604
            self._ensure_real()
 
1605
            self._real_repository.set_make_working_trees(new_value)
 
1606
        else:
 
1607
            if response[0] != 'ok':
 
1608
                raise errors.UnexpectedSmartServerResponse(response)
1111
1609
 
1112
1610
    @property
1113
1611
    def signatures(self):
1140
1638
        return self._real_repository.get_revisions(revision_ids)
1141
1639
 
1142
1640
    def supports_rich_root(self):
1143
 
        self._ensure_real()
1144
 
        return self._real_repository.supports_rich_root()
 
1641
        return self._format.rich_root_data
1145
1642
 
1146
1643
    def iter_reverse_revision_history(self, revision_id):
1147
1644
        self._ensure_real()
1149
1646
 
1150
1647
    @property
1151
1648
    def _serializer(self):
1152
 
        self._ensure_real()
1153
 
        return self._real_repository._serializer
 
1649
        return self._format._serializer
1154
1650
 
1155
1651
    def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
1156
1652
        self._ensure_real()
1175
1671
        self._ensure_real()
1176
1672
        return self._real_repository.revision_graph_can_have_wrong_parents()
1177
1673
 
1178
 
    def _find_inconsistent_revision_parents(self):
 
1674
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1179
1675
        self._ensure_real()
1180
 
        return self._real_repository._find_inconsistent_revision_parents()
 
1676
        return self._real_repository._find_inconsistent_revision_parents(
 
1677
            revisions_iterator)
1181
1678
 
1182
1679
    def _check_for_inconsistent_revision_parents(self):
1183
1680
        self._ensure_real()
1189
1686
            providers.insert(0, other)
1190
1687
        providers.extend(r._make_parents_provider() for r in
1191
1688
                         self._fallback_repositories)
1192
 
        return graph._StackedParentsProvider(providers)
 
1689
        return graph.StackedParentsProvider(providers)
1193
1690
 
1194
1691
    def _serialise_search_recipe(self, recipe):
1195
1692
        """Serialise a graph search recipe.
1197
1694
        :param recipe: A search recipe (start, stop, count).
1198
1695
        :return: Serialised bytes.
1199
1696
        """
1200
 
        start_keys = ' '.join(recipe[0])
1201
 
        stop_keys = ' '.join(recipe[1])
1202
 
        count = str(recipe[2])
 
1697
        start_keys = ' '.join(recipe[1])
 
1698
        stop_keys = ' '.join(recipe[2])
 
1699
        count = str(recipe[3])
1203
1700
        return '\n'.join((start_keys, stop_keys, count))
1204
1701
 
 
1702
    def _serialise_search_result(self, search_result):
 
1703
        if isinstance(search_result, graph.PendingAncestryResult):
 
1704
            parts = ['ancestry-of']
 
1705
            parts.extend(search_result.heads)
 
1706
        else:
 
1707
            recipe = search_result.get_recipe()
 
1708
            parts = [recipe[0], self._serialise_search_recipe(recipe)]
 
1709
        return '\n'.join(parts)
 
1710
 
1205
1711
    def autopack(self):
1206
1712
        path = self.bzrdir._path_for_remote_call(self._client)
1207
1713
        try:
1210
1716
            self._ensure_real()
1211
1717
            self._real_repository._pack_collection.autopack()
1212
1718
            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()
 
1719
        self.refresh_data()
1219
1720
        if response[0] != 'ok':
1220
1721
            raise errors.UnexpectedSmartServerResponse(response)
1221
1722
 
1222
1723
 
 
1724
class RemoteStreamSink(repository.StreamSink):
 
1725
 
 
1726
    def _insert_real(self, stream, src_format, resume_tokens):
 
1727
        self.target_repo._ensure_real()
 
1728
        sink = self.target_repo._real_repository._get_sink()
 
1729
        result = sink.insert_stream(stream, src_format, resume_tokens)
 
1730
        if not result:
 
1731
            self.target_repo.autopack()
 
1732
        return result
 
1733
 
 
1734
    def insert_stream(self, stream, src_format, resume_tokens):
 
1735
        target = self.target_repo
 
1736
        target._unstacked_provider.missing_keys.clear()
 
1737
        candidate_calls = [('Repository.insert_stream_1.19', (1, 19))]
 
1738
        if target._lock_token:
 
1739
            candidate_calls.append(('Repository.insert_stream_locked', (1, 14)))
 
1740
            lock_args = (target._lock_token or '',)
 
1741
        else:
 
1742
            candidate_calls.append(('Repository.insert_stream', (1, 13)))
 
1743
            lock_args = ()
 
1744
        client = target._client
 
1745
        medium = client._medium
 
1746
        path = target.bzrdir._path_for_remote_call(client)
 
1747
        # Probe for the verb to use with an empty stream before sending the
 
1748
        # real stream to it.  We do this both to avoid the risk of sending a
 
1749
        # large request that is then rejected, and because we don't want to
 
1750
        # implement a way to buffer, rewind, or restart the stream.
 
1751
        found_verb = False
 
1752
        for verb, required_version in candidate_calls:
 
1753
            if medium._is_remote_before(required_version):
 
1754
                continue
 
1755
            if resume_tokens:
 
1756
                # We've already done the probing (and set _is_remote_before) on
 
1757
                # a previous insert.
 
1758
                found_verb = True
 
1759
                break
 
1760
            byte_stream = smart_repo._stream_to_byte_stream([], src_format)
 
1761
            try:
 
1762
                response = client.call_with_body_stream(
 
1763
                    (verb, path, '') + lock_args, byte_stream)
 
1764
            except errors.UnknownSmartMethod:
 
1765
                medium._remember_remote_is_before(required_version)
 
1766
            else:
 
1767
                found_verb = True
 
1768
                break
 
1769
        if not found_verb:
 
1770
            # Have to use VFS.
 
1771
            return self._insert_real(stream, src_format, resume_tokens)
 
1772
        self._last_inv_record = None
 
1773
        self._last_substream = None
 
1774
        if required_version < (1, 19):
 
1775
            # Remote side doesn't support inventory deltas.  Wrap the stream to
 
1776
            # make sure we don't send any.  If the stream contains inventory
 
1777
            # deltas we'll interrupt the smart insert_stream request and
 
1778
            # fallback to VFS.
 
1779
            stream = self._stop_stream_if_inventory_delta(stream)
 
1780
        byte_stream = smart_repo._stream_to_byte_stream(
 
1781
            stream, src_format)
 
1782
        resume_tokens = ' '.join(resume_tokens)
 
1783
        response = client.call_with_body_stream(
 
1784
            (verb, path, resume_tokens) + lock_args, byte_stream)
 
1785
        if response[0][0] not in ('ok', 'missing-basis'):
 
1786
            raise errors.UnexpectedSmartServerResponse(response)
 
1787
        if self._last_substream is not None:
 
1788
            # The stream included an inventory-delta record, but the remote
 
1789
            # side isn't new enough to support them.  So we need to send the
 
1790
            # rest of the stream via VFS.
 
1791
            self.target_repo.refresh_data()
 
1792
            return self._resume_stream_with_vfs(response, src_format)
 
1793
        if response[0][0] == 'missing-basis':
 
1794
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
 
1795
            resume_tokens = tokens
 
1796
            return resume_tokens, set(missing_keys)
 
1797
        else:
 
1798
            self.target_repo.refresh_data()
 
1799
            return [], set()
 
1800
 
 
1801
    def _resume_stream_with_vfs(self, response, src_format):
 
1802
        """Resume sending a stream via VFS, first resending the record and
 
1803
        substream that couldn't be sent via an insert_stream verb.
 
1804
        """
 
1805
        if response[0][0] == 'missing-basis':
 
1806
            tokens, missing_keys = bencode.bdecode_as_tuple(response[0][1])
 
1807
            # Ignore missing_keys, we haven't finished inserting yet
 
1808
        else:
 
1809
            tokens = []
 
1810
        def resume_substream():
 
1811
            # Yield the substream that was interrupted.
 
1812
            for record in self._last_substream:
 
1813
                yield record
 
1814
            self._last_substream = None
 
1815
        def resume_stream():
 
1816
            # Finish sending the interrupted substream
 
1817
            yield ('inventory-deltas', resume_substream())
 
1818
            # Then simply continue sending the rest of the stream.
 
1819
            for substream_kind, substream in self._last_stream:
 
1820
                yield substream_kind, substream
 
1821
        return self._insert_real(resume_stream(), src_format, tokens)
 
1822
 
 
1823
    def _stop_stream_if_inventory_delta(self, stream):
 
1824
        """Normally this just lets the original stream pass-through unchanged.
 
1825
 
 
1826
        However if any 'inventory-deltas' substream occurs it will stop
 
1827
        streaming, and store the interrupted substream and stream in
 
1828
        self._last_substream and self._last_stream so that the stream can be
 
1829
        resumed by _resume_stream_with_vfs.
 
1830
        """
 
1831
                    
 
1832
        stream_iter = iter(stream)
 
1833
        for substream_kind, substream in stream_iter:
 
1834
            if substream_kind == 'inventory-deltas':
 
1835
                self._last_substream = substream
 
1836
                self._last_stream = stream_iter
 
1837
                return
 
1838
            else:
 
1839
                yield substream_kind, substream
 
1840
            
 
1841
 
 
1842
class RemoteStreamSource(repository.StreamSource):
 
1843
    """Stream data from a remote server."""
 
1844
 
 
1845
    def get_stream(self, search):
 
1846
        if (self.from_repository._fallback_repositories and
 
1847
            self.to_format._fetch_order == 'topological'):
 
1848
            return self._real_stream(self.from_repository, search)
 
1849
        sources = []
 
1850
        seen = set()
 
1851
        repos = [self.from_repository]
 
1852
        while repos:
 
1853
            repo = repos.pop(0)
 
1854
            if repo in seen:
 
1855
                continue
 
1856
            seen.add(repo)
 
1857
            repos.extend(repo._fallback_repositories)
 
1858
            sources.append(repo)
 
1859
        return self.missing_parents_chain(search, sources)
 
1860
 
 
1861
    def get_stream_for_missing_keys(self, missing_keys):
 
1862
        self.from_repository._ensure_real()
 
1863
        real_repo = self.from_repository._real_repository
 
1864
        real_source = real_repo._get_source(self.to_format)
 
1865
        return real_source.get_stream_for_missing_keys(missing_keys)
 
1866
 
 
1867
    def _real_stream(self, repo, search):
 
1868
        """Get a stream for search from repo.
 
1869
        
 
1870
        This never called RemoteStreamSource.get_stream, and is a heler
 
1871
        for RemoteStreamSource._get_stream to allow getting a stream 
 
1872
        reliably whether fallback back because of old servers or trying
 
1873
        to stream from a non-RemoteRepository (which the stacked support
 
1874
        code will do).
 
1875
        """
 
1876
        source = repo._get_source(self.to_format)
 
1877
        if isinstance(source, RemoteStreamSource):
 
1878
            repo._ensure_real()
 
1879
            source = repo._real_repository._get_source(self.to_format)
 
1880
        return source.get_stream(search)
 
1881
 
 
1882
    def _get_stream(self, repo, search):
 
1883
        """Core worker to get a stream from repo for search.
 
1884
 
 
1885
        This is used by both get_stream and the stacking support logic. It
 
1886
        deliberately gets a stream for repo which does not need to be
 
1887
        self.from_repository. In the event that repo is not Remote, or
 
1888
        cannot do a smart stream, a fallback is made to the generic
 
1889
        repository._get_stream() interface, via self._real_stream.
 
1890
 
 
1891
        In the event of stacking, streams from _get_stream will not
 
1892
        contain all the data for search - this is normal (see get_stream).
 
1893
 
 
1894
        :param repo: A repository.
 
1895
        :param search: A search.
 
1896
        """
 
1897
        # Fallbacks may be non-smart
 
1898
        if not isinstance(repo, RemoteRepository):
 
1899
            return self._real_stream(repo, search)
 
1900
        client = repo._client
 
1901
        medium = client._medium
 
1902
        path = repo.bzrdir._path_for_remote_call(client)
 
1903
        search_bytes = repo._serialise_search_result(search)
 
1904
        args = (path, self.to_format.network_name())
 
1905
        candidate_verbs = [
 
1906
            ('Repository.get_stream_1.19', (1, 19)),
 
1907
            ('Repository.get_stream', (1, 13))]
 
1908
        found_verb = False
 
1909
        for verb, version in candidate_verbs:
 
1910
            if medium._is_remote_before(version):
 
1911
                continue
 
1912
            try:
 
1913
                response = repo._call_with_body_bytes_expecting_body(
 
1914
                    verb, args, search_bytes)
 
1915
            except errors.UnknownSmartMethod:
 
1916
                medium._remember_remote_is_before(version)
 
1917
            else:
 
1918
                response_tuple, response_handler = response
 
1919
                found_verb = True
 
1920
                break
 
1921
        if not found_verb:
 
1922
            return self._real_stream(repo, search)
 
1923
        if response_tuple[0] != 'ok':
 
1924
            raise errors.UnexpectedSmartServerResponse(response_tuple)
 
1925
        byte_stream = response_handler.read_streamed_body()
 
1926
        src_format, stream = smart_repo._byte_stream_to_stream(byte_stream)
 
1927
        if src_format.network_name() != repo._format.network_name():
 
1928
            raise AssertionError(
 
1929
                "Mismatched RemoteRepository and stream src %r, %r" % (
 
1930
                src_format.network_name(), repo._format.network_name()))
 
1931
        return stream
 
1932
 
 
1933
    def missing_parents_chain(self, search, sources):
 
1934
        """Chain multiple streams together to handle stacking.
 
1935
 
 
1936
        :param search: The overall search to satisfy with streams.
 
1937
        :param sources: A list of Repository objects to query.
 
1938
        """
 
1939
        self.from_serialiser = self.from_repository._format._serializer
 
1940
        self.seen_revs = set()
 
1941
        self.referenced_revs = set()
 
1942
        # If there are heads in the search, or the key count is > 0, we are not
 
1943
        # done.
 
1944
        while not search.is_empty() and len(sources) > 1:
 
1945
            source = sources.pop(0)
 
1946
            stream = self._get_stream(source, search)
 
1947
            for kind, substream in stream:
 
1948
                if kind != 'revisions':
 
1949
                    yield kind, substream
 
1950
                else:
 
1951
                    yield kind, self.missing_parents_rev_handler(substream)
 
1952
            search = search.refine(self.seen_revs, self.referenced_revs)
 
1953
            self.seen_revs = set()
 
1954
            self.referenced_revs = set()
 
1955
        if not search.is_empty():
 
1956
            for kind, stream in self._get_stream(sources[0], search):
 
1957
                yield kind, stream
 
1958
 
 
1959
    def missing_parents_rev_handler(self, substream):
 
1960
        for content in substream:
 
1961
            revision_bytes = content.get_bytes_as('fulltext')
 
1962
            revision = self.from_serialiser.read_revision_from_string(
 
1963
                revision_bytes)
 
1964
            self.seen_revs.add(content.key[-1])
 
1965
            self.referenced_revs.update(revision.parent_ids)
 
1966
            yield content
 
1967
 
 
1968
 
1223
1969
class RemoteBranchLockableFiles(LockableFiles):
1224
1970
    """A 'LockableFiles' implementation that talks to a smart server.
1225
 
    
 
1971
 
1226
1972
    This is not a public interface class.
1227
1973
    """
1228
1974
 
1242
1988
 
1243
1989
class RemoteBranchFormat(branch.BranchFormat):
1244
1990
 
1245
 
    def __init__(self):
 
1991
    def __init__(self, network_name=None):
1246
1992
        super(RemoteBranchFormat, self).__init__()
1247
1993
        self._matchingbzrdir = RemoteBzrDirFormat()
1248
1994
        self._matchingbzrdir.set_branch_format(self)
 
1995
        self._custom_format = None
 
1996
        self._network_name = network_name
1249
1997
 
1250
1998
    def __eq__(self, other):
1251
 
        return (isinstance(other, RemoteBranchFormat) and 
 
1999
        return (isinstance(other, RemoteBranchFormat) and
1252
2000
            self.__dict__ == other.__dict__)
1253
2001
 
 
2002
    def _ensure_real(self):
 
2003
        if self._custom_format is None:
 
2004
            self._custom_format = branch.network_format_registry.get(
 
2005
                self._network_name)
 
2006
 
1254
2007
    def get_format_description(self):
1255
 
        return 'Remote BZR Branch'
1256
 
 
1257
 
    def get_format_string(self):
1258
 
        return 'Remote BZR Branch'
1259
 
 
1260
 
    def open(self, a_bzrdir):
1261
 
        return a_bzrdir.open_branch()
 
2008
        self._ensure_real()
 
2009
        return 'Remote: ' + self._custom_format.get_format_description()
 
2010
 
 
2011
    def network_name(self):
 
2012
        return self._network_name
 
2013
 
 
2014
    def open(self, a_bzrdir, ignore_fallbacks=False):
 
2015
        return a_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
 
2016
 
 
2017
    def _vfs_initialize(self, a_bzrdir):
 
2018
        # Initialisation when using a local bzrdir object, or a non-vfs init
 
2019
        # method is not available on the server.
 
2020
        # self._custom_format is always set - the start of initialize ensures
 
2021
        # that.
 
2022
        if isinstance(a_bzrdir, RemoteBzrDir):
 
2023
            a_bzrdir._ensure_real()
 
2024
            result = self._custom_format.initialize(a_bzrdir._real_bzrdir)
 
2025
        else:
 
2026
            # We assume the bzrdir is parameterised; it may not be.
 
2027
            result = self._custom_format.initialize(a_bzrdir)
 
2028
        if (isinstance(a_bzrdir, RemoteBzrDir) and
 
2029
            not isinstance(result, RemoteBranch)):
 
2030
            result = RemoteBranch(a_bzrdir, a_bzrdir.find_repository(), result)
 
2031
        return result
1262
2032
 
1263
2033
    def initialize(self, a_bzrdir):
1264
 
        return a_bzrdir.create_branch()
 
2034
        # 1) get the network name to use.
 
2035
        if self._custom_format:
 
2036
            network_name = self._custom_format.network_name()
 
2037
        else:
 
2038
            # Select the current bzrlib default and ask for that.
 
2039
            reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
2040
            reference_format = reference_bzrdir_format.get_branch_format()
 
2041
            self._custom_format = reference_format
 
2042
            network_name = reference_format.network_name()
 
2043
        # Being asked to create on a non RemoteBzrDir:
 
2044
        if not isinstance(a_bzrdir, RemoteBzrDir):
 
2045
            return self._vfs_initialize(a_bzrdir)
 
2046
        medium = a_bzrdir._client._medium
 
2047
        if medium._is_remote_before((1, 13)):
 
2048
            return self._vfs_initialize(a_bzrdir)
 
2049
        # Creating on a remote bzr dir.
 
2050
        # 2) try direct creation via RPC
 
2051
        path = a_bzrdir._path_for_remote_call(a_bzrdir._client)
 
2052
        verb = 'BzrDir.create_branch'
 
2053
        try:
 
2054
            response = a_bzrdir._call(verb, path, network_name)
 
2055
        except errors.UnknownSmartMethod:
 
2056
            # Fallback - use vfs methods
 
2057
            medium._remember_remote_is_before((1, 13))
 
2058
            return self._vfs_initialize(a_bzrdir)
 
2059
        if response[0] != 'ok':
 
2060
            raise errors.UnexpectedSmartServerResponse(response)
 
2061
        # Turn the response into a RemoteRepository object.
 
2062
        format = RemoteBranchFormat(network_name=response[1])
 
2063
        repo_format = response_tuple_to_repo_format(response[3:])
 
2064
        if response[2] == '':
 
2065
            repo_bzrdir = a_bzrdir
 
2066
        else:
 
2067
            repo_bzrdir = RemoteBzrDir(
 
2068
                a_bzrdir.root_transport.clone(response[2]), a_bzrdir._format,
 
2069
                a_bzrdir._client)
 
2070
        remote_repo = RemoteRepository(repo_bzrdir, repo_format)
 
2071
        remote_branch = RemoteBranch(a_bzrdir, remote_repo,
 
2072
            format=format, setup_stacking=False)
 
2073
        # XXX: We know this is a new branch, so it must have revno 0, revid
 
2074
        # NULL_REVISION. Creating the branch locked would make this be unable
 
2075
        # to be wrong; here its simply very unlikely to be wrong. RBC 20090225
 
2076
        remote_branch._last_revision_info_cache = 0, NULL_REVISION
 
2077
        return remote_branch
 
2078
 
 
2079
    def make_tags(self, branch):
 
2080
        self._ensure_real()
 
2081
        return self._custom_format.make_tags(branch)
1265
2082
 
1266
2083
    def supports_tags(self):
1267
2084
        # Remote branches might support tags, but we won't know until we
1268
2085
        # access the real remote branch.
1269
 
        return True
1270
 
 
1271
 
 
1272
 
class RemoteBranch(branch.Branch, _RpcHelper):
 
2086
        self._ensure_real()
 
2087
        return self._custom_format.supports_tags()
 
2088
 
 
2089
    def supports_stacking(self):
 
2090
        self._ensure_real()
 
2091
        return self._custom_format.supports_stacking()
 
2092
 
 
2093
    def supports_set_append_revisions_only(self):
 
2094
        self._ensure_real()
 
2095
        return self._custom_format.supports_set_append_revisions_only()
 
2096
 
 
2097
 
 
2098
class RemoteBranch(branch.Branch, _RpcHelper, lock._RelockDebugMixin):
1273
2099
    """Branch stored on a server accessed by HPSS RPC.
1274
2100
 
1275
2101
    At the moment most operations are mapped down to simple file operations.
1276
2102
    """
1277
2103
 
1278
2104
    def __init__(self, remote_bzrdir, remote_repository, real_branch=None,
1279
 
        _client=None):
 
2105
        _client=None, format=None, setup_stacking=True):
1280
2106
        """Create a RemoteBranch instance.
1281
2107
 
1282
2108
        :param real_branch: An optional local implementation of the branch
1283
2109
            format, usually accessing the data via the VFS.
1284
2110
        :param _client: Private parameter for testing.
 
2111
        :param format: A RemoteBranchFormat object, None to create one
 
2112
            automatically. If supplied it should have a network_name already
 
2113
            supplied.
 
2114
        :param setup_stacking: If True make an RPC call to determine the
 
2115
            stacked (or not) status of the branch. If False assume the branch
 
2116
            is not stacked.
1285
2117
        """
1286
2118
        # We intentionally don't call the parent class's __init__, because it
1287
2119
        # will try to assign to self.tags, which is a property in this subclass.
1288
2120
        # 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
2121
        self.bzrdir = remote_bzrdir
1295
2122
        if _client is not None:
1296
2123
            self._client = _client
1309
2136
            self._real_branch.repository = self.repository
1310
2137
        else:
1311
2138
            self._real_branch = None
1312
 
        # Fill out expected attributes of branch for bzrlib api users.
1313
 
        self._format = RemoteBranchFormat()
 
2139
        # Fill out expected attributes of branch for bzrlib API users.
 
2140
        self._clear_cached_state()
1314
2141
        self.base = self.bzrdir.root_transport.base
1315
2142
        self._control_files = None
1316
2143
        self._lock_mode = None
1318
2145
        self._repo_lock_token = None
1319
2146
        self._lock_count = 0
1320
2147
        self._leave_lock = False
 
2148
        # Setup a format: note that we cannot call _ensure_real until all the
 
2149
        # attributes above are set: This code cannot be moved higher up in this
 
2150
        # function.
 
2151
        if format is None:
 
2152
            self._format = RemoteBranchFormat()
 
2153
            if real_branch is not None:
 
2154
                self._format._network_name = \
 
2155
                    self._real_branch._format.network_name()
 
2156
        else:
 
2157
            self._format = format
 
2158
        # when we do _ensure_real we may need to pass ignore_fallbacks to the
 
2159
        # branch.open_branch method.
 
2160
        self._real_ignore_fallbacks = not setup_stacking
 
2161
        if not self._format._network_name:
 
2162
            # Did not get from open_branchV2 - old server.
 
2163
            self._ensure_real()
 
2164
            self._format._network_name = \
 
2165
                self._real_branch._format.network_name()
 
2166
        self.tags = self._format.make_tags(self)
1321
2167
        # The base class init is not called, so we duplicate this:
1322
2168
        hooks = branch.Branch.hooks['open']
1323
2169
        for hook in hooks:
1324
2170
            hook(self)
1325
 
        self._setup_stacking()
 
2171
        self._is_stacked = False
 
2172
        if setup_stacking:
 
2173
            self._setup_stacking()
1326
2174
 
1327
2175
    def _setup_stacking(self):
1328
2176
        # configure stacking into the remote repository, by reading it from
1332
2180
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1333
2181
            errors.UnstackableRepositoryFormat), e:
1334
2182
            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)
 
2183
        self._is_stacked = True
 
2184
        self._activate_fallback_location(fallback_url)
 
2185
 
 
2186
    def _get_config(self):
 
2187
        return RemoteBranchConfig(self)
1343
2188
 
1344
2189
    def _get_real_transport(self):
1345
2190
        # if we try vfs access, return the real branch's vfs transport
1363
2208
                raise AssertionError('smart server vfs must be enabled '
1364
2209
                    'to use vfs implementation')
1365
2210
            self.bzrdir._ensure_real()
1366
 
            self._real_branch = self.bzrdir._real_bzrdir.open_branch()
 
2211
            self._real_branch = self.bzrdir._real_bzrdir.open_branch(
 
2212
                ignore_fallbacks=self._real_ignore_fallbacks)
1367
2213
            if self.repository._real_repository is None:
1368
2214
                # Give the remote repository the matching real repo.
1369
2215
                real_repo = self._real_branch.repository
1398
2244
        too, in fact doing so might harm performance.
1399
2245
        """
1400
2246
        super(RemoteBranch, self)._clear_cached_state()
1401
 
        
 
2247
 
1402
2248
    @property
1403
2249
    def control_files(self):
1404
2250
        # Defer actually creating RemoteBranchLockableFiles until its needed,
1443
2289
            raise errors.UnexpectedSmartServerResponse(response)
1444
2290
        return response[1]
1445
2291
 
 
2292
    def set_stacked_on_url(self, url):
 
2293
        branch.Branch.set_stacked_on_url(self, url)
 
2294
        if not url:
 
2295
            self._is_stacked = False
 
2296
        else:
 
2297
            self._is_stacked = True
 
2298
        
 
2299
    def _vfs_get_tags_bytes(self):
 
2300
        self._ensure_real()
 
2301
        return self._real_branch._get_tags_bytes()
 
2302
 
 
2303
    def _get_tags_bytes(self):
 
2304
        medium = self._client._medium
 
2305
        if medium._is_remote_before((1, 13)):
 
2306
            return self._vfs_get_tags_bytes()
 
2307
        try:
 
2308
            response = self._call('Branch.get_tags_bytes', self._remote_path())
 
2309
        except errors.UnknownSmartMethod:
 
2310
            medium._remember_remote_is_before((1, 13))
 
2311
            return self._vfs_get_tags_bytes()
 
2312
        return response[0]
 
2313
 
 
2314
    def _vfs_set_tags_bytes(self, bytes):
 
2315
        self._ensure_real()
 
2316
        return self._real_branch._set_tags_bytes(bytes)
 
2317
 
 
2318
    def _set_tags_bytes(self, bytes):
 
2319
        medium = self._client._medium
 
2320
        if medium._is_remote_before((1, 18)):
 
2321
            self._vfs_set_tags_bytes(bytes)
 
2322
            return
 
2323
        try:
 
2324
            args = (
 
2325
                self._remote_path(), self._lock_token, self._repo_lock_token)
 
2326
            response = self._call_with_body_bytes(
 
2327
                'Branch.set_tags_bytes', args, bytes)
 
2328
        except errors.UnknownSmartMethod:
 
2329
            medium._remember_remote_is_before((1, 18))
 
2330
            self._vfs_set_tags_bytes(bytes)
 
2331
 
1446
2332
    def lock_read(self):
1447
2333
        self.repository.lock_read()
1448
2334
        if not self._lock_mode:
 
2335
            self._note_lock('r')
1449
2336
            self._lock_mode = 'r'
1450
2337
            self._lock_count = 1
1451
2338
            if self._real_branch is not None:
1468
2355
            raise errors.UnexpectedSmartServerResponse(response)
1469
2356
        ok, branch_token, repo_token = response
1470
2357
        return branch_token, repo_token
1471
 
            
 
2358
 
1472
2359
    def lock_write(self, token=None):
1473
2360
        if not self._lock_mode:
 
2361
            self._note_lock('w')
1474
2362
            # Lock the branch and repo in one remote call.
1475
2363
            remote_tokens = self._remote_lock_write(token)
1476
2364
            self._lock_token, self._repo_lock_token = remote_tokens
1511
2399
            return
1512
2400
        raise errors.UnexpectedSmartServerResponse(response)
1513
2401
 
 
2402
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1514
2403
    def unlock(self):
1515
2404
        try:
1516
2405
            self._lock_count -= 1
1529
2418
                    self._real_branch.unlock()
1530
2419
                if mode != 'w':
1531
2420
                    # Only write-locked branched need to make a remote method
1532
 
                    # call to perfom the unlock.
 
2421
                    # call to perform the unlock.
1533
2422
                    return
1534
2423
                if not self._lock_token:
1535
2424
                    raise AssertionError('Locked, but no token!')
1556
2445
            raise NotImplementedError(self.dont_leave_lock_in_place)
1557
2446
        self._leave_lock = False
1558
2447
 
 
2448
    @needs_read_lock
 
2449
    def get_rev_id(self, revno, history=None):
 
2450
        if revno == 0:
 
2451
            return _mod_revision.NULL_REVISION
 
2452
        last_revision_info = self.last_revision_info()
 
2453
        ok, result = self.repository.get_rev_id_for_revno(
 
2454
            revno, last_revision_info)
 
2455
        if ok:
 
2456
            return result
 
2457
        missing_parent = result[1]
 
2458
        # Either the revision named by the server is missing, or its parent
 
2459
        # is.  Call get_parent_map to determine which, so that we report a
 
2460
        # useful error.
 
2461
        parent_map = self.repository.get_parent_map([missing_parent])
 
2462
        if missing_parent in parent_map:
 
2463
            missing_parent = parent_map[missing_parent]
 
2464
        raise errors.RevisionNotPresent(missing_parent, self.repository)
 
2465
 
1559
2466
    def _last_revision_info(self):
1560
2467
        response = self._call('Branch.last_revision_info', self._remote_path())
1561
2468
        if response[0] != 'ok':
1566
2473
 
1567
2474
    def _gen_revision_history(self):
1568
2475
        """See Branch._gen_revision_history()."""
 
2476
        if self._is_stacked:
 
2477
            self._ensure_real()
 
2478
            return self._real_branch._gen_revision_history()
1569
2479
        response_tuple, response_handler = self._call_expecting_body(
1570
2480
            'Branch.revision_history', self._remote_path())
1571
2481
        if response_tuple[0] != 'ok':
1580
2490
 
1581
2491
    def _set_last_revision_descendant(self, revision_id, other_branch,
1582
2492
            allow_diverged=False, allow_overwrite_descendant=False):
 
2493
        # This performs additional work to meet the hook contract; while its
 
2494
        # undesirable, we have to synthesise the revno to call the hook, and
 
2495
        # not calling the hook is worse as it means changes can't be prevented.
 
2496
        # Having calculated this though, we can't just call into
 
2497
        # set_last_revision_info as a simple call, because there is a set_rh
 
2498
        # hook that some folk may still be using.
 
2499
        old_revno, old_revid = self.last_revision_info()
 
2500
        history = self._lefthand_history(revision_id)
 
2501
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1583
2502
        err_context = {'other_branch': other_branch}
1584
2503
        response = self._call('Branch.set_last_revision_ex',
1585
2504
            self._remote_path(), self._lock_token, self._repo_lock_token,
1590
2509
            raise errors.UnexpectedSmartServerResponse(response)
1591
2510
        new_revno, new_revision_id = response[1:]
1592
2511
        self._last_revision_info_cache = new_revno, new_revision_id
 
2512
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1593
2513
        if self._real_branch is not None:
1594
2514
            cache = new_revno, new_revision_id
1595
2515
            self._real_branch._last_revision_info_cache = cache
1596
2516
 
1597
2517
    def _set_last_revision(self, revision_id):
 
2518
        old_revno, old_revid = self.last_revision_info()
 
2519
        # This performs additional work to meet the hook contract; while its
 
2520
        # undesirable, we have to synthesise the revno to call the hook, and
 
2521
        # not calling the hook is worse as it means changes can't be prevented.
 
2522
        # Having calculated this though, we can't just call into
 
2523
        # set_last_revision_info as a simple call, because there is a set_rh
 
2524
        # hook that some folk may still be using.
 
2525
        history = self._lefthand_history(revision_id)
 
2526
        self._run_pre_change_branch_tip_hooks(len(history), revision_id)
1598
2527
        self._clear_cached_state()
1599
2528
        response = self._call('Branch.set_last_revision',
1600
2529
            self._remote_path(), self._lock_token, self._repo_lock_token,
1601
2530
            revision_id)
1602
2531
        if response != ('ok',):
1603
2532
            raise errors.UnexpectedSmartServerResponse(response)
 
2533
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1604
2534
 
1605
2535
    @needs_write_lock
1606
2536
    def set_revision_history(self, rev_history):
1612
2542
        else:
1613
2543
            rev_id = rev_history[-1]
1614
2544
        self._set_last_revision(rev_id)
 
2545
        for hook in branch.Branch.hooks['set_rh']:
 
2546
            hook(self, rev_history)
1615
2547
        self._cache_revision_history(rev_history)
1616
2548
 
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
 
2549
    def _get_parent_location(self):
 
2550
        medium = self._client._medium
 
2551
        if medium._is_remote_before((1, 13)):
 
2552
            return self._vfs_get_parent_location()
 
2553
        try:
 
2554
            response = self._call('Branch.get_parent', self._remote_path())
 
2555
        except errors.UnknownSmartMethod:
 
2556
            medium._remember_remote_is_before((1, 13))
 
2557
            return self._vfs_get_parent_location()
 
2558
        if len(response) != 1:
 
2559
            raise errors.UnexpectedSmartServerResponse(response)
 
2560
        parent_location = response[0]
 
2561
        if parent_location == '':
 
2562
            return None
 
2563
        return parent_location
 
2564
 
 
2565
    def _vfs_get_parent_location(self):
 
2566
        self._ensure_real()
 
2567
        return self._real_branch._get_parent_location()
 
2568
 
 
2569
    def _set_parent_location(self, url):
 
2570
        medium = self._client._medium
 
2571
        if medium._is_remote_before((1, 15)):
 
2572
            return self._vfs_set_parent_location(url)
 
2573
        try:
 
2574
            call_url = url or ''
 
2575
            if type(call_url) is not str:
 
2576
                raise AssertionError('url must be a str or None (%s)' % url)
 
2577
            response = self._call('Branch.set_parent_location',
 
2578
                self._remote_path(), self._lock_token, self._repo_lock_token,
 
2579
                call_url)
 
2580
        except errors.UnknownSmartMethod:
 
2581
            medium._remember_remote_is_before((1, 15))
 
2582
            return self._vfs_set_parent_location(url)
 
2583
        if response != ():
 
2584
            raise errors.UnexpectedSmartServerResponse(response)
 
2585
 
 
2586
    def _vfs_set_parent_location(self, url):
 
2587
        self._ensure_real()
 
2588
        return self._real_branch._set_parent_location(url)
1654
2589
 
1655
2590
    @needs_write_lock
1656
2591
    def pull(self, source, overwrite=False, stop_revision=None,
1678
2613
 
1679
2614
    @needs_write_lock
1680
2615
    def set_last_revision_info(self, revno, revision_id):
 
2616
        # XXX: These should be returned by the set_last_revision_info verb
 
2617
        old_revno, old_revid = self.last_revision_info()
 
2618
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
1681
2619
        revision_id = ensure_null(revision_id)
1682
2620
        try:
1683
2621
            response = self._call('Branch.set_last_revision_info',
1692
2630
        if response == ('ok',):
1693
2631
            self._clear_cached_state()
1694
2632
            self._last_revision_info_cache = revno, revision_id
 
2633
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1695
2634
            # Update the _real_branch's cache too.
1696
2635
            if self._real_branch is not None:
1697
2636
                cache = self._last_revision_info_cache
1704
2643
                                  other_branch=None):
1705
2644
        medium = self._client._medium
1706
2645
        if not medium._is_remote_before((1, 6)):
 
2646
            # Use a smart method for 1.6 and above servers
1707
2647
            try:
1708
2648
                self._set_last_revision_descendant(revision_id, other_branch,
1709
2649
                    allow_diverged=True, allow_overwrite_descendant=True)
1711
2651
            except errors.UnknownSmartMethod:
1712
2652
                medium._remember_remote_is_before((1, 6))
1713
2653
        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
 
2654
        self.set_revision_history(self._lefthand_history(revision_id,
 
2655
            last_rev=last_rev,other_branch=other_branch))
1722
2656
 
1723
2657
    def set_push_location(self, location):
1724
2658
        self._ensure_real()
1725
2659
        return self._real_branch.set_push_location(location)
1726
2660
 
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()
 
2661
 
 
2662
class RemoteConfig(object):
 
2663
    """A Config that reads and writes from smart verbs.
 
2664
 
 
2665
    It is a low-level object that considers config data to be name/value pairs
 
2666
    that may be associated with a section. Assigning meaning to the these
 
2667
    values is done at higher levels like bzrlib.config.TreeConfig.
 
2668
    """
 
2669
 
 
2670
    def get_option(self, name, section=None, default=None):
 
2671
        """Return the value associated with a named option.
 
2672
 
 
2673
        :param name: The name of the value
 
2674
        :param section: The section the option is in (if any)
 
2675
        :param default: The value to return if the value is not set
 
2676
        :return: The value or default value
 
2677
        """
1732
2678
        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)
 
2679
            configobj = self._get_configobj()
 
2680
            if section is None:
 
2681
                section_obj = configobj
1744
2682
            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()
 
2683
                try:
 
2684
                    section_obj = configobj[section]
 
2685
                except KeyError:
 
2686
                    return default
 
2687
            return section_obj.get(name, default)
 
2688
        except errors.UnknownSmartMethod:
 
2689
            return self._vfs_get_option(name, section, default)
 
2690
 
 
2691
    def _response_to_configobj(self, response):
 
2692
        if len(response[0]) and response[0][0] != 'ok':
 
2693
            raise errors.UnexpectedSmartServerResponse(response)
 
2694
        lines = response[1].read_body_bytes().splitlines()
 
2695
        return config.ConfigObj(lines, encoding='utf-8')
 
2696
 
 
2697
 
 
2698
class RemoteBranchConfig(RemoteConfig):
 
2699
    """A RemoteConfig for Branches."""
 
2700
 
 
2701
    def __init__(self, branch):
 
2702
        self._branch = branch
 
2703
 
 
2704
    def _get_configobj(self):
 
2705
        path = self._branch._remote_path()
 
2706
        response = self._branch._client.call_expecting_body(
 
2707
            'Branch.get_config_file', path)
 
2708
        return self._response_to_configobj(response)
 
2709
 
 
2710
    def set_option(self, value, name, section=None):
 
2711
        """Set the value associated with a named option.
 
2712
 
 
2713
        :param value: The value to set
 
2714
        :param name: The name of the value to set
 
2715
        :param section: The section the option is in (if any)
 
2716
        """
 
2717
        medium = self._branch._client._medium
 
2718
        if medium._is_remote_before((1, 14)):
 
2719
            return self._vfs_set_option(value, name, section)
 
2720
        try:
 
2721
            path = self._branch._remote_path()
 
2722
            response = self._branch._client.call('Branch.set_config_option',
 
2723
                path, self._branch._lock_token, self._branch._repo_lock_token,
 
2724
                value.encode('utf8'), name, section or '')
 
2725
        except errors.UnknownSmartMethod:
 
2726
            medium._remember_remote_is_before((1, 14))
 
2727
            return self._vfs_set_option(value, name, section)
 
2728
        if response != ():
 
2729
            raise errors.UnexpectedSmartServerResponse(response)
 
2730
 
 
2731
    def _real_object(self):
 
2732
        self._branch._ensure_real()
 
2733
        return self._branch._real_branch
 
2734
 
 
2735
    def _vfs_set_option(self, value, name, section=None):
 
2736
        return self._real_object()._get_config().set_option(
 
2737
            value, name, section)
 
2738
 
 
2739
 
 
2740
class RemoteBzrDirConfig(RemoteConfig):
 
2741
    """A RemoteConfig for BzrDirs."""
 
2742
 
 
2743
    def __init__(self, bzrdir):
 
2744
        self._bzrdir = bzrdir
 
2745
 
 
2746
    def _get_configobj(self):
 
2747
        medium = self._bzrdir._client._medium
 
2748
        verb = 'BzrDir.get_config_file'
 
2749
        if medium._is_remote_before((1, 15)):
 
2750
            raise errors.UnknownSmartMethod(verb)
 
2751
        path = self._bzrdir._path_for_remote_call(self._bzrdir._client)
 
2752
        response = self._bzrdir._call_expecting_body(
 
2753
            verb, path)
 
2754
        return self._response_to_configobj(response)
 
2755
 
 
2756
    def _vfs_get_option(self, name, section, default):
 
2757
        return self._real_object()._get_config().get_option(
 
2758
            name, section, default)
 
2759
 
 
2760
    def set_option(self, value, name, section=None):
 
2761
        """Set the value associated with a named option.
 
2762
 
 
2763
        :param value: The value to set
 
2764
        :param name: The name of the value to set
 
2765
        :param section: The section the option is in (if any)
 
2766
        """
 
2767
        return self._real_object()._get_config().set_option(
 
2768
            value, name, section)
 
2769
 
 
2770
    def _real_object(self):
 
2771
        self._bzrdir._ensure_real()
 
2772
        return self._bzrdir._real_bzrdir
 
2773
 
1765
2774
 
1766
2775
 
1767
2776
def _extract_tar(tar, to_dir):
1807
2816
                    'Missing key %r in context %r', key_err.args[0], context)
1808
2817
                raise err
1809
2818
 
1810
 
    if err.error_verb == 'NoSuchRevision':
 
2819
    if err.error_verb == 'IncompatibleRepositories':
 
2820
        raise errors.IncompatibleRepositories(err.error_args[0],
 
2821
            err.error_args[1], err.error_args[2])
 
2822
    elif err.error_verb == 'NoSuchRevision':
1811
2823
        raise NoSuchRevision(find('branch'), err.error_args[0])
1812
2824
    elif err.error_verb == 'nosuchrevision':
1813
2825
        raise NoSuchRevision(find('repository'), err.error_args[0])