/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bzr/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2018-06-15 13:10:28 UTC
  • mto: (6973.12.2 python3-k)
  • mto: This revision was merged to the branch mainline in revision 6993.
  • Revision ID: jelmer@jelmer.uk-20180615131028-abolpmqrid8th0cd
More bees.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012 Canonical Ltd
 
2
# Copyright (C) 2017 Breezy Developers
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
from __future__ import absolute_import
 
19
 
 
20
import sys
 
21
 
 
22
from ..lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
from breezy import (
 
25
    cache_utf8,
 
26
    config as _mod_config,
 
27
    lockable_files,
 
28
    lockdir,
 
29
    rio,
 
30
    shelf,
 
31
    tag as _mod_tag,
 
32
    )
 
33
""")
 
34
 
 
35
from . import bzrdir
 
36
from .. import (
 
37
    controldir,
 
38
    errors,
 
39
    revision as _mod_revision,
 
40
    urlutils,
 
41
    )
 
42
from ..branch import (
 
43
    Branch,
 
44
    BranchFormat,
 
45
    BranchWriteLockResult,
 
46
    format_registry,
 
47
    UnstackableBranchFormat,
 
48
    )
 
49
from ..decorators import (
 
50
    only_raises,
 
51
    )
 
52
from ..lock import _RelockDebugMixin, LogicalLockResult
 
53
from ..sixish import (
 
54
    BytesIO,
 
55
    text_type,
 
56
    viewitems,
 
57
    )
 
58
from ..trace import (
 
59
    mutter,
 
60
    )
 
61
 
 
62
 
 
63
class BzrBranch(Branch, _RelockDebugMixin):
 
64
    """A branch stored in the actual filesystem.
 
65
 
 
66
    Note that it's "local" in the context of the filesystem; it doesn't
 
67
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
68
    it's writable, and can be accessed via the normal filesystem API.
 
69
 
 
70
    :ivar _transport: Transport for file operations on this branch's
 
71
        control files, typically pointing to the .bzr/branch directory.
 
72
    :ivar repository: Repository for this branch.
 
73
    :ivar base: The url of the base directory for this branch; the one
 
74
        containing the .bzr directory.
 
75
    :ivar name: Optional colocated branch name as it exists in the control
 
76
        directory.
 
77
    """
 
78
 
 
79
    def __init__(self, _format=None,
 
80
                 _control_files=None, a_controldir=None, name=None,
 
81
                 _repository=None, ignore_fallbacks=False,
 
82
                 possible_transports=None):
 
83
        """Create new branch object at a particular location."""
 
84
        if a_controldir is None:
 
85
            raise ValueError('a_controldir must be supplied')
 
86
        if name is None:
 
87
            raise ValueError('name must be supplied')
 
88
        self.controldir = a_controldir
 
89
        self._user_transport = self.controldir.transport.clone('..')
 
90
        if name != u"":
 
91
            self._user_transport.set_segment_parameter(
 
92
                "branch", urlutils.escape(name).encode('utf-8'))
 
93
        self._base = self._user_transport.base
 
94
        self.name = name
 
95
        self._format = _format
 
96
        if _control_files is None:
 
97
            raise ValueError('BzrBranch _control_files is None')
 
98
        self.control_files = _control_files
 
99
        self._transport = _control_files._transport
 
100
        self.repository = _repository
 
101
        self.conf_store = None
 
102
        Branch.__init__(self, possible_transports)
 
103
        self._tags_bytes = None
 
104
 
 
105
    def __str__(self):
 
106
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
107
 
 
108
    __repr__ = __str__
 
109
 
 
110
    def _get_base(self):
 
111
        """Returns the directory containing the control directory."""
 
112
        return self._base
 
113
 
 
114
    base = property(_get_base, doc="The URL for the root of this branch.")
 
115
 
 
116
    @property
 
117
    def user_transport(self):
 
118
        return self._user_transport
 
119
 
 
120
    def _get_config(self):
 
121
        """Get the concrete config for just the config in this branch.
 
122
 
 
123
        This is not intended for client use; see Branch.get_config for the
 
124
        public API.
 
125
 
 
126
        Added in 1.14.
 
127
 
 
128
        :return: An object supporting get_option and set_option.
 
129
        """
 
130
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
 
131
 
 
132
    def _get_config_store(self):
 
133
        if self.conf_store is None:
 
134
            self.conf_store =  _mod_config.BranchStore(self)
 
135
        return self.conf_store
 
136
 
 
137
    def _uncommitted_branch(self):
 
138
        """Return the branch that may contain uncommitted changes."""
 
139
        master = self.get_master_branch()
 
140
        if master is not None:
 
141
            return master
 
142
        else:
 
143
            return self
 
144
 
 
145
    def store_uncommitted(self, creator):
 
146
        """Store uncommitted changes from a ShelfCreator.
 
147
 
 
148
        :param creator: The ShelfCreator containing uncommitted changes, or
 
149
            None to delete any stored changes.
 
150
        :raises: ChangesAlreadyStored if the branch already has changes.
 
151
        """
 
152
        branch = self._uncommitted_branch()
 
153
        if creator is None:
 
154
            branch._transport.delete('stored-transform')
 
155
            return
 
156
        if branch._transport.has('stored-transform'):
 
157
            raise errors.ChangesAlreadyStored
 
158
        transform = BytesIO()
 
159
        creator.write_shelf(transform)
 
160
        transform.seek(0)
 
161
        branch._transport.put_file('stored-transform', transform)
 
162
 
 
163
    def get_unshelver(self, tree):
 
164
        """Return a shelf.Unshelver for this branch and tree.
 
165
 
 
166
        :param tree: The tree to use to construct the Unshelver.
 
167
        :return: an Unshelver or None if no changes are stored.
 
168
        """
 
169
        branch = self._uncommitted_branch()
 
170
        try:
 
171
            transform = branch._transport.get('stored-transform')
 
172
        except errors.NoSuchFile:
 
173
            return None
 
174
        return shelf.Unshelver.from_tree_and_shelf(tree, transform)
 
175
 
 
176
    def is_locked(self):
 
177
        return self.control_files.is_locked()
 
178
 
 
179
    def lock_write(self, token=None):
 
180
        """Lock the branch for write operations.
 
181
 
 
182
        :param token: A token to permit reacquiring a previously held and
 
183
            preserved lock.
 
184
        :return: A BranchWriteLockResult.
 
185
        """
 
186
        if not self.is_locked():
 
187
            self._note_lock('w')
 
188
            self.repository._warn_if_deprecated(self)
 
189
            self.repository.lock_write()
 
190
            took_lock = True
 
191
        else:
 
192
            took_lock = False
 
193
        try:
 
194
            return BranchWriteLockResult(
 
195
                self.unlock,
 
196
                self.control_files.lock_write(token=token))
 
197
        except:
 
198
            if took_lock:
 
199
                self.repository.unlock()
 
200
            raise
 
201
 
 
202
    def lock_read(self):
 
203
        """Lock the branch for read operations.
 
204
 
 
205
        :return: A breezy.lock.LogicalLockResult.
 
206
        """
 
207
        if not self.is_locked():
 
208
            self._note_lock('r')
 
209
            self.repository._warn_if_deprecated(self)
 
210
            self.repository.lock_read()
 
211
            took_lock = True
 
212
        else:
 
213
            took_lock = False
 
214
        try:
 
215
            self.control_files.lock_read()
 
216
            return LogicalLockResult(self.unlock)
 
217
        except:
 
218
            if took_lock:
 
219
                self.repository.unlock()
 
220
            raise
 
221
 
 
222
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
223
    def unlock(self):
 
224
        if self.control_files._lock_count == 1 and self.conf_store is not None:
 
225
            self.conf_store.save_changes()
 
226
        try:
 
227
            self.control_files.unlock()
 
228
        finally:
 
229
            if not self.control_files.is_locked():
 
230
                self.repository.unlock()
 
231
                # we just released the lock
 
232
                self._clear_cached_state()
 
233
 
 
234
    def peek_lock_mode(self):
 
235
        if self.control_files._lock_count == 0:
 
236
            return None
 
237
        else:
 
238
            return self.control_files._lock_mode
 
239
 
 
240
    def get_physical_lock_status(self):
 
241
        return self.control_files.get_physical_lock_status()
 
242
 
 
243
    def set_last_revision_info(self, revno, revision_id):
 
244
        if not revision_id or not isinstance(revision_id, bytes):
 
245
            raise errors.InvalidRevisionId(
 
246
                    revision_id=revision_id, branch=self)
 
247
        revision_id = _mod_revision.ensure_null(revision_id)
 
248
        with self.lock_write():
 
249
            old_revno, old_revid = self.last_revision_info()
 
250
            if self.get_append_revisions_only():
 
251
                self._check_history_violation(revision_id)
 
252
            self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
253
            self._write_last_revision_info(revno, revision_id)
 
254
            self._clear_cached_state()
 
255
            self._last_revision_info_cache = revno, revision_id
 
256
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
257
 
 
258
    def basis_tree(self):
 
259
        """See Branch.basis_tree."""
 
260
        return self.repository.revision_tree(self.last_revision())
 
261
 
 
262
    def _get_parent_location(self):
 
263
        _locs = ['parent', 'pull', 'x-pull']
 
264
        for l in _locs:
 
265
            try:
 
266
                return self._transport.get_bytes(l).strip(b'\n')
 
267
            except errors.NoSuchFile:
 
268
                pass
 
269
        return None
 
270
 
 
271
    def get_stacked_on_url(self):
 
272
        raise UnstackableBranchFormat(self._format, self.user_url)
 
273
 
 
274
    def set_push_location(self, location):
 
275
        """See Branch.set_push_location."""
 
276
        self.get_config().set_user_option(
 
277
            'push_location', location,
 
278
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
279
 
 
280
    def _set_parent_location(self, url):
 
281
        if url is None:
 
282
            self._transport.delete('parent')
 
283
        else:
 
284
            if isinstance(url, text_type):
 
285
                url = url.encode('utf-8')
 
286
            self._transport.put_bytes('parent', url + b'\n',
 
287
                mode=self.controldir._get_file_mode())
 
288
 
 
289
    def unbind(self):
 
290
        """If bound, unbind"""
 
291
        with self.lock_write():
 
292
            return self.set_bound_location(None)
 
293
 
 
294
    def bind(self, other):
 
295
        """Bind this branch to the branch other.
 
296
 
 
297
        This does not push or pull data between the branches, though it does
 
298
        check for divergence to raise an error when the branches are not
 
299
        either the same, or one a prefix of the other. That behaviour may not
 
300
        be useful, so that check may be removed in future.
 
301
 
 
302
        :param other: The branch to bind to
 
303
        :type other: Branch
 
304
        """
 
305
        # TODO: jam 20051230 Consider checking if the target is bound
 
306
        #       It is debatable whether you should be able to bind to
 
307
        #       a branch which is itself bound.
 
308
        #       Committing is obviously forbidden,
 
309
        #       but binding itself may not be.
 
310
        #       Since we *have* to check at commit time, we don't
 
311
        #       *need* to check here
 
312
 
 
313
        # we want to raise diverged if:
 
314
        # last_rev is not in the other_last_rev history, AND
 
315
        # other_last_rev is not in our history, and do it without pulling
 
316
        # history around
 
317
        with self.lock_write():
 
318
            self.set_bound_location(other.base)
 
319
 
 
320
    def get_bound_location(self):
 
321
        try:
 
322
            return self._transport.get_bytes('bound')[:-1]
 
323
        except errors.NoSuchFile:
 
324
            return None
 
325
 
 
326
    def get_master_branch(self, possible_transports=None):
 
327
        """Return the branch we are bound to.
 
328
 
 
329
        :return: Either a Branch, or None
 
330
        """
 
331
        with self.lock_read():
 
332
            if self._master_branch_cache is None:
 
333
                self._master_branch_cache = self._get_master_branch(
 
334
                    possible_transports)
 
335
            return self._master_branch_cache
 
336
 
 
337
    def _get_master_branch(self, possible_transports):
 
338
        bound_loc = self.get_bound_location()
 
339
        if not bound_loc:
 
340
            return None
 
341
        try:
 
342
            return Branch.open(bound_loc,
 
343
                               possible_transports=possible_transports)
 
344
        except (errors.NotBranchError, errors.ConnectionError) as e:
 
345
            raise errors.BoundBranchConnectionFailure(
 
346
                    self, bound_loc, e)
 
347
 
 
348
    def set_bound_location(self, location):
 
349
        """Set the target where this branch is bound to.
 
350
 
 
351
        :param location: URL to the target branch
 
352
        """
 
353
        with self.lock_write():
 
354
            self._master_branch_cache = None
 
355
            if location:
 
356
                self._transport.put_bytes('bound', location.encode('utf-8')+b'\n',
 
357
                    mode=self.controldir._get_file_mode())
 
358
            else:
 
359
                try:
 
360
                    self._transport.delete('bound')
 
361
                except errors.NoSuchFile:
 
362
                    return False
 
363
                return True
 
364
 
 
365
    def update(self, possible_transports=None):
 
366
        """Synchronise this branch with the master branch if any.
 
367
 
 
368
        :return: None or the last_revision that was pivoted out during the
 
369
                 update.
 
370
        """
 
371
        with self.lock_write():
 
372
            master = self.get_master_branch(possible_transports)
 
373
            if master is not None:
 
374
                old_tip = _mod_revision.ensure_null(self.last_revision())
 
375
                self.pull(master, overwrite=True)
 
376
                if self.repository.get_graph().is_ancestor(old_tip,
 
377
                    _mod_revision.ensure_null(self.last_revision())):
 
378
                    return None
 
379
                return old_tip
 
380
            return None
 
381
 
 
382
    def _read_last_revision_info(self):
 
383
        revision_string = self._transport.get_bytes('last-revision')
 
384
        revno, revision_id = revision_string.rstrip(b'\n').split(b' ', 1)
 
385
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
386
        revno = int(revno)
 
387
        return revno, revision_id
 
388
 
 
389
    def _write_last_revision_info(self, revno, revision_id):
 
390
        """Simply write out the revision id, with no checks.
 
391
 
 
392
        Use set_last_revision_info to perform this safely.
 
393
 
 
394
        Does not update the revision_history cache.
 
395
        """
 
396
        revision_id = _mod_revision.ensure_null(revision_id)
 
397
        out_string = b'%d %s\n' % (revno, revision_id)
 
398
        self._transport.put_bytes('last-revision', out_string,
 
399
            mode=self.controldir._get_file_mode())
 
400
 
 
401
    def update_feature_flags(self, updated_flags):
 
402
        """Update the feature flags for this branch.
 
403
 
 
404
        :param updated_flags: Dictionary mapping feature names to necessities
 
405
            A necessity can be None to indicate the feature should be removed
 
406
        """
 
407
        with self.lock_write():
 
408
            self._format._update_feature_flags(updated_flags)
 
409
            self.control_transport.put_bytes('format', self._format.as_string())
 
410
 
 
411
    def _get_tags_bytes(self):
 
412
        """Get the bytes of a serialised tags dict.
 
413
 
 
414
        Note that not all branches support tags, nor do all use the same tags
 
415
        logic: this method is specific to BasicTags. Other tag implementations
 
416
        may use the same method name and behave differently, safely, because
 
417
        of the double-dispatch via
 
418
        format.make_tags->tags_instance->get_tags_dict.
 
419
 
 
420
        :return: The bytes of the tags file.
 
421
        :seealso: Branch._set_tags_bytes.
 
422
        """
 
423
        with self.lock_read():
 
424
            if self._tags_bytes is None:
 
425
                self._tags_bytes = self._transport.get_bytes('tags')
 
426
            return self._tags_bytes
 
427
 
 
428
    def _set_tags_bytes(self, bytes):
 
429
        """Mirror method for _get_tags_bytes.
 
430
 
 
431
        :seealso: Branch._get_tags_bytes.
 
432
        """
 
433
        with self.lock_write():
 
434
            self._tags_bytes = bytes
 
435
            return self._transport.put_bytes('tags', bytes)
 
436
 
 
437
    def _clear_cached_state(self):
 
438
        super(BzrBranch, self)._clear_cached_state()
 
439
        self._tags_bytes = None
 
440
 
 
441
 
 
442
class BzrBranch8(BzrBranch):
 
443
    """A branch that stores tree-reference locations."""
 
444
 
 
445
    def _open_hook(self, possible_transports=None):
 
446
        if self._ignore_fallbacks:
 
447
            return
 
448
        if possible_transports is None:
 
449
            possible_transports = [self.controldir.root_transport]
 
450
        try:
 
451
            url = self.get_stacked_on_url()
 
452
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
453
            UnstackableBranchFormat):
 
454
            pass
 
455
        else:
 
456
            for hook in Branch.hooks['transform_fallback_location']:
 
457
                url = hook(self, url)
 
458
                if url is None:
 
459
                    hook_name = Branch.hooks.get_hook_name(hook)
 
460
                    raise AssertionError(
 
461
                        "'transform_fallback_location' hook %s returned "
 
462
                        "None, not a URL." % hook_name)
 
463
            self._activate_fallback_location(url,
 
464
                possible_transports=possible_transports)
 
465
 
 
466
    def __init__(self, *args, **kwargs):
 
467
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
 
468
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
469
        self._last_revision_info_cache = None
 
470
        self._reference_info = None
 
471
 
 
472
    def _clear_cached_state(self):
 
473
        super(BzrBranch8, self)._clear_cached_state()
 
474
        self._last_revision_info_cache = None
 
475
        self._reference_info = None
 
476
 
 
477
    def _check_history_violation(self, revision_id):
 
478
        current_revid = self.last_revision()
 
479
        last_revision = _mod_revision.ensure_null(current_revid)
 
480
        if _mod_revision.is_null(last_revision):
 
481
            return
 
482
        graph = self.repository.get_graph()
 
483
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
 
484
            if lh_ancestor == current_revid:
 
485
                return
 
486
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
487
 
 
488
    def _gen_revision_history(self):
 
489
        """Generate the revision history from last revision
 
490
        """
 
491
        last_revno, last_revision = self.last_revision_info()
 
492
        self._extend_partial_history(stop_index=last_revno-1)
 
493
        return list(reversed(self._partial_revision_history_cache))
 
494
 
 
495
    def _set_parent_location(self, url):
 
496
        """Set the parent branch"""
 
497
        with self.lock_write():
 
498
            self._set_config_location('parent_location', url, make_relative=True)
 
499
 
 
500
    def _get_parent_location(self):
 
501
        """Set the parent branch"""
 
502
        with self.lock_read():
 
503
            return self._get_config_location('parent_location')
 
504
 
 
505
    def _set_all_reference_info(self, info_dict):
 
506
        """Replace all reference info stored in a branch.
 
507
 
 
508
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
509
        """
 
510
        s = BytesIO()
 
511
        writer = rio.RioWriter(s)
 
512
        for tree_path, ( branch_location, file_id) in viewitems(info_dict):
 
513
            stanza = rio.Stanza(tree_path=tree_path,
 
514
                                branch_location=branch_location)
 
515
            if file_id is not None:
 
516
                stanza.add('file_id', file_id)
 
517
            writer.write_stanza(stanza)
 
518
        with self.lock_write():
 
519
            self._transport.put_bytes('references', s.getvalue())
 
520
            self._reference_info = info_dict
 
521
 
 
522
    def _get_all_reference_info(self):
 
523
        """Return all the reference info stored in a branch.
 
524
 
 
525
        :return: A dict of {tree_path: (branch_location, file_id)}
 
526
        """
 
527
        with self.lock_read():
 
528
            if self._reference_info is not None:
 
529
                return self._reference_info
 
530
            with self._transport.get('references') as rio_file:
 
531
                stanzas = rio.read_stanzas(rio_file)
 
532
                info_dict = {
 
533
                    s['tree_path']: (
 
534
                        s['branch_location'],
 
535
                        s['file_id'].encode('ascii') if 'file_id' in s else None)
 
536
                    for s in stanzas}
 
537
            self._reference_info = info_dict
 
538
            return info_dict
 
539
 
 
540
    def set_reference_info(self, tree_path, branch_location, file_id=None):
 
541
        """Set the branch location to use for a tree reference.
 
542
 
 
543
        :param tree_path: The path of the tree reference in the tree.
 
544
        :param branch_location: The location of the branch to retrieve tree
 
545
            references from.
 
546
        :param file_id: The file-id of the tree reference.
 
547
        """
 
548
        info_dict = self._get_all_reference_info()
 
549
        info_dict[tree_path] = (branch_location, file_id)
 
550
        if branch_location is None:
 
551
            del info_dict[tree_path]
 
552
        self._set_all_reference_info(info_dict)
 
553
 
 
554
    def get_reference_info(self, path):
 
555
        """Get the tree_path and branch_location for a tree reference.
 
556
 
 
557
        :return: a tuple of (branch_location, file_id)
 
558
        """
 
559
        return self._get_all_reference_info().get(path, (None, None))
 
560
 
 
561
    def reference_parent(self, path, file_id=None, possible_transports=None):
 
562
        """Return the parent branch for a tree-reference file_id.
 
563
 
 
564
        :param file_id: The file_id of the tree reference
 
565
        :param path: The path of the file_id in the tree
 
566
        :return: A branch associated with the file_id
 
567
        """
 
568
        branch_location = self.get_reference_info(path)[0]
 
569
        if branch_location is None:
 
570
            return Branch.reference_parent(self, path, file_id,
 
571
                                           possible_transports)
 
572
        branch_location = urlutils.join(self.user_url, branch_location)
 
573
        return Branch.open(branch_location,
 
574
                           possible_transports=possible_transports)
 
575
 
 
576
    def set_push_location(self, location):
 
577
        """See Branch.set_push_location."""
 
578
        self._set_config_location('push_location', location)
 
579
 
 
580
    def set_bound_location(self, location):
 
581
        """See Branch.set_push_location."""
 
582
        self._master_branch_cache = None
 
583
        result = None
 
584
        conf = self.get_config_stack()
 
585
        if location is None:
 
586
            if not conf.get('bound'):
 
587
                return False
 
588
            else:
 
589
                conf.set('bound', 'False')
 
590
                return True
 
591
        else:
 
592
            self._set_config_location('bound_location', location,
 
593
                                      config=conf)
 
594
            conf.set('bound', 'True')
 
595
        return True
 
596
 
 
597
    def _get_bound_location(self, bound):
 
598
        """Return the bound location in the config file.
 
599
 
 
600
        Return None if the bound parameter does not match"""
 
601
        conf = self.get_config_stack()
 
602
        if conf.get('bound') != bound:
 
603
            return None
 
604
        return self._get_config_location('bound_location', config=conf)
 
605
 
 
606
    def get_bound_location(self):
 
607
        """See Branch.get_bound_location."""
 
608
        return self._get_bound_location(True)
 
609
 
 
610
    def get_old_bound_location(self):
 
611
        """See Branch.get_old_bound_location"""
 
612
        return self._get_bound_location(False)
 
613
 
 
614
    def get_stacked_on_url(self):
 
615
        # you can always ask for the URL; but you might not be able to use it
 
616
        # if the repo can't support stacking.
 
617
        ## self._check_stackable_repo()
 
618
        # stacked_on_location is only ever defined in branch.conf, so don't
 
619
        # waste effort reading the whole stack of config files.
 
620
        conf = _mod_config.BranchOnlyStack(self)
 
621
        stacked_url = self._get_config_location('stacked_on_location',
 
622
                                                config=conf)
 
623
        if stacked_url is None:
 
624
            raise errors.NotStacked(self)
 
625
        if sys.version_info[0] == 2:
 
626
            return stacked_url.encode('utf-8')
 
627
        else:
 
628
            return stacked_url
 
629
 
 
630
    def get_rev_id(self, revno, history=None):
 
631
        """Find the revision id of the specified revno."""
 
632
        if revno == 0:
 
633
            return _mod_revision.NULL_REVISION
 
634
 
 
635
        with self.lock_read():
 
636
            last_revno, last_revision_id = self.last_revision_info()
 
637
            if revno <= 0 or revno > last_revno:
 
638
                raise errors.NoSuchRevision(self, revno)
 
639
 
 
640
            if history is not None:
 
641
                return history[revno - 1]
 
642
 
 
643
            index = last_revno - revno
 
644
            if len(self._partial_revision_history_cache) <= index:
 
645
                self._extend_partial_history(stop_index=index)
 
646
            if len(self._partial_revision_history_cache) > index:
 
647
                return self._partial_revision_history_cache[index]
 
648
            else:
 
649
                raise errors.NoSuchRevision(self, revno)
 
650
 
 
651
    def revision_id_to_revno(self, revision_id):
 
652
        """Given a revision id, return its revno"""
 
653
        if _mod_revision.is_null(revision_id):
 
654
            return 0
 
655
        with self.lock_read():
 
656
            try:
 
657
                index = self._partial_revision_history_cache.index(revision_id)
 
658
            except ValueError:
 
659
                try:
 
660
                    self._extend_partial_history(stop_revision=revision_id)
 
661
                except errors.RevisionNotPresent as e:
 
662
                    raise errors.GhostRevisionsHaveNoRevno(
 
663
                            revision_id, e.revision_id)
 
664
                index = len(self._partial_revision_history_cache) - 1
 
665
                if index < 0:
 
666
                    raise errors.NoSuchRevision(self, revision_id)
 
667
                if self._partial_revision_history_cache[index] != revision_id:
 
668
                    raise errors.NoSuchRevision(self, revision_id)
 
669
            return self.revno() - index
 
670
 
 
671
 
 
672
class BzrBranch7(BzrBranch8):
 
673
    """A branch with support for a fallback repository."""
 
674
 
 
675
    def set_reference_info(self, tree_path, branch_location, file_id=None):
 
676
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
677
 
 
678
    def get_reference_info(self, path):
 
679
        Branch.get_reference_info(self, path)
 
680
 
 
681
    def reference_parent(self, path, file_id=None, possible_transports=None):
 
682
        return Branch.reference_parent(self, path, file_id, possible_transports)
 
683
 
 
684
 
 
685
class BzrBranch6(BzrBranch7):
 
686
    """See BzrBranchFormat6 for the capabilities of this branch.
 
687
 
 
688
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
689
    i.e. stacking.
 
690
    """
 
691
 
 
692
    def get_stacked_on_url(self):
 
693
        raise UnstackableBranchFormat(self._format, self.user_url)
 
694
 
 
695
 
 
696
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
 
697
    """Base class for branch formats that live in meta directories.
 
698
    """
 
699
 
 
700
    def __init__(self):
 
701
        BranchFormat.__init__(self)
 
702
        bzrdir.BzrFormat.__init__(self)
 
703
 
 
704
    @classmethod
 
705
    def find_format(klass, controldir, name=None):
 
706
        """Return the format for the branch object in controldir."""
 
707
        try:
 
708
            transport = controldir.get_branch_transport(None, name=name)
 
709
        except errors.NoSuchFile:
 
710
            raise errors.NotBranchError(path=name, controldir=controldir)
 
711
        try:
 
712
            format_string = transport.get_bytes("format")
 
713
        except errors.NoSuchFile:
 
714
            raise errors.NotBranchError(
 
715
                path=transport.base, controldir=controldir)
 
716
        return klass._find_format(format_registry, 'branch', format_string)
 
717
 
 
718
    def _branch_class(self):
 
719
        """What class to instantiate on open calls."""
 
720
        raise NotImplementedError(self._branch_class)
 
721
 
 
722
    def _get_initial_config(self, append_revisions_only=None):
 
723
        if append_revisions_only:
 
724
            return b"append_revisions_only = True\n"
 
725
        else:
 
726
            # Avoid writing anything if append_revisions_only is disabled,
 
727
            # as that is the default.
 
728
            return b""
 
729
 
 
730
    def _initialize_helper(self, a_controldir, utf8_files, name=None,
 
731
                           repository=None):
 
732
        """Initialize a branch in a control dir, with specified files
 
733
 
 
734
        :param a_controldir: The bzrdir to initialize the branch in
 
735
        :param utf8_files: The files to create as a list of
 
736
            (filename, content) tuples
 
737
        :param name: Name of colocated branch to create, if any
 
738
        :return: a branch in this format
 
739
        """
 
740
        if name is None:
 
741
            name = a_controldir._get_selected_branch()
 
742
        mutter('creating branch %r in %s', self, a_controldir.user_url)
 
743
        branch_transport = a_controldir.get_branch_transport(self, name=name)
 
744
        control_files = lockable_files.LockableFiles(branch_transport,
 
745
            'lock', lockdir.LockDir)
 
746
        control_files.create_lock()
 
747
        control_files.lock_write()
 
748
        try:
 
749
            utf8_files += [('format', self.as_string())]
 
750
            for (filename, content) in utf8_files:
 
751
                branch_transport.put_bytes(
 
752
                    filename, content,
 
753
                    mode=a_controldir._get_file_mode())
 
754
        finally:
 
755
            control_files.unlock()
 
756
        branch = self.open(a_controldir, name, _found=True,
 
757
                found_repository=repository)
 
758
        self._run_post_branch_init_hooks(a_controldir, name, branch)
 
759
        return branch
 
760
 
 
761
    def open(self, a_controldir, name=None, _found=False, ignore_fallbacks=False,
 
762
            found_repository=None, possible_transports=None):
 
763
        """See BranchFormat.open()."""
 
764
        if name is None:
 
765
            name = a_controldir._get_selected_branch()
 
766
        if not _found:
 
767
            format = BranchFormatMetadir.find_format(a_controldir, name=name)
 
768
            if format.__class__ != self.__class__:
 
769
                raise AssertionError("wrong format %r found for %r" %
 
770
                    (format, self))
 
771
        transport = a_controldir.get_branch_transport(None, name=name)
 
772
        try:
 
773
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
774
                                                         lockdir.LockDir)
 
775
            if found_repository is None:
 
776
                found_repository = a_controldir.find_repository()
 
777
            return self._branch_class()(_format=self,
 
778
                              _control_files=control_files,
 
779
                              name=name,
 
780
                              a_controldir=a_controldir,
 
781
                              _repository=found_repository,
 
782
                              ignore_fallbacks=ignore_fallbacks,
 
783
                              possible_transports=possible_transports)
 
784
        except errors.NoSuchFile:
 
785
            raise errors.NotBranchError(path=transport.base, controldir=a_controldir)
 
786
 
 
787
    @property
 
788
    def _matchingcontroldir(self):
 
789
        ret = bzrdir.BzrDirMetaFormat1()
 
790
        ret.set_branch_format(self)
 
791
        return ret
 
792
 
 
793
    def supports_tags(self):
 
794
        return True
 
795
 
 
796
    def supports_leaving_lock(self):
 
797
        return True
 
798
 
 
799
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
800
            basedir=None):
 
801
        BranchFormat.check_support_status(self,
 
802
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
 
803
            basedir=basedir)
 
804
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
 
805
            recommend_upgrade=recommend_upgrade, basedir=basedir)
 
806
 
 
807
 
 
808
class BzrBranchFormat6(BranchFormatMetadir):
 
809
    """Branch format with last-revision and tags.
 
810
 
 
811
    Unlike previous formats, this has no explicit revision history. Instead,
 
812
    this just stores the last-revision, and the left-hand history leading
 
813
    up to there is the history.
 
814
 
 
815
    This format was introduced in bzr 0.15
 
816
    and became the default in 0.91.
 
817
    """
 
818
 
 
819
    def _branch_class(self):
 
820
        return BzrBranch6
 
821
 
 
822
    @classmethod
 
823
    def get_format_string(cls):
 
824
        """See BranchFormat.get_format_string()."""
 
825
        return b"Bazaar Branch Format 6 (bzr 0.15)\n"
 
826
 
 
827
    def get_format_description(self):
 
828
        """See BranchFormat.get_format_description()."""
 
829
        return "Branch format 6"
 
830
 
 
831
    def initialize(self, a_controldir, name=None, repository=None,
 
832
                   append_revisions_only=None):
 
833
        """Create a branch of this format in a_controldir."""
 
834
        utf8_files = [('last-revision', b'0 null:\n'),
 
835
                      ('branch.conf',
 
836
                          self._get_initial_config(append_revisions_only)),
 
837
                      ('tags', b''),
 
838
                      ]
 
839
        return self._initialize_helper(a_controldir, utf8_files, name, repository)
 
840
 
 
841
    def make_tags(self, branch):
 
842
        """See breezy.branch.BranchFormat.make_tags()."""
 
843
        return _mod_tag.BasicTags(branch)
 
844
 
 
845
    def supports_set_append_revisions_only(self):
 
846
        return True
 
847
 
 
848
 
 
849
class BzrBranchFormat8(BranchFormatMetadir):
 
850
    """Metadir format supporting storing locations of subtree branches."""
 
851
 
 
852
    def _branch_class(self):
 
853
        return BzrBranch8
 
854
 
 
855
    @classmethod
 
856
    def get_format_string(cls):
 
857
        """See BranchFormat.get_format_string()."""
 
858
        return b"Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
859
 
 
860
    def get_format_description(self):
 
861
        """See BranchFormat.get_format_description()."""
 
862
        return "Branch format 8"
 
863
 
 
864
    def initialize(self, a_controldir, name=None, repository=None,
 
865
                   append_revisions_only=None):
 
866
        """Create a branch of this format in a_controldir."""
 
867
        utf8_files = [('last-revision', b'0 null:\n'),
 
868
                      ('branch.conf',
 
869
                          self._get_initial_config(append_revisions_only)),
 
870
                      ('tags', b''),
 
871
                      ('references', b'')
 
872
                      ]
 
873
        return self._initialize_helper(a_controldir, utf8_files, name, repository)
 
874
 
 
875
    def make_tags(self, branch):
 
876
        """See breezy.branch.BranchFormat.make_tags()."""
 
877
        return _mod_tag.BasicTags(branch)
 
878
 
 
879
    def supports_set_append_revisions_only(self):
 
880
        return True
 
881
 
 
882
    def supports_stacking(self):
 
883
        return True
 
884
 
 
885
    supports_reference_locations = True
 
886
 
 
887
 
 
888
class BzrBranchFormat7(BranchFormatMetadir):
 
889
    """Branch format with last-revision, tags, and a stacked location pointer.
 
890
 
 
891
    The stacked location pointer is passed down to the repository and requires
 
892
    a repository format with supports_external_lookups = True.
 
893
 
 
894
    This format was introduced in bzr 1.6.
 
895
    """
 
896
 
 
897
    def initialize(self, a_controldir, name=None, repository=None,
 
898
                   append_revisions_only=None):
 
899
        """Create a branch of this format in a_controldir."""
 
900
        utf8_files = [('last-revision', b'0 null:\n'),
 
901
                      ('branch.conf',
 
902
                          self._get_initial_config(append_revisions_only)),
 
903
                      ('tags', b''),
 
904
                      ]
 
905
        return self._initialize_helper(a_controldir, utf8_files, name, repository)
 
906
 
 
907
    def _branch_class(self):
 
908
        return BzrBranch7
 
909
 
 
910
    @classmethod
 
911
    def get_format_string(cls):
 
912
        """See BranchFormat.get_format_string()."""
 
913
        return b"Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
914
 
 
915
    def get_format_description(self):
 
916
        """See BranchFormat.get_format_description()."""
 
917
        return "Branch format 7"
 
918
 
 
919
    def supports_set_append_revisions_only(self):
 
920
        return True
 
921
 
 
922
    def supports_stacking(self):
 
923
        return True
 
924
 
 
925
    def make_tags(self, branch):
 
926
        """See breezy.branch.BranchFormat.make_tags()."""
 
927
        return _mod_tag.BasicTags(branch)
 
928
 
 
929
    supports_reference_locations = False
 
930
 
 
931
 
 
932
class BranchReferenceFormat(BranchFormatMetadir):
 
933
    """Bzr branch reference format.
 
934
 
 
935
    Branch references are used in implementing checkouts, they
 
936
    act as an alias to the real branch which is at some other url.
 
937
 
 
938
    This format has:
 
939
     - A location file
 
940
     - a format string
 
941
    """
 
942
 
 
943
    @classmethod
 
944
    def get_format_string(cls):
 
945
        """See BranchFormat.get_format_string()."""
 
946
        return b"Bazaar-NG Branch Reference Format 1\n"
 
947
 
 
948
    def get_format_description(self):
 
949
        """See BranchFormat.get_format_description()."""
 
950
        return "Checkout reference format 1"
 
951
 
 
952
    def get_reference(self, a_controldir, name=None):
 
953
        """See BranchFormat.get_reference()."""
 
954
        transport = a_controldir.get_branch_transport(None, name=name)
 
955
        url = urlutils.split_segment_parameters(a_controldir.user_url)[0]
 
956
        return urlutils.join(url, transport.get_bytes('location').decode('utf-8'))
 
957
 
 
958
    def _write_reference(self, a_controldir, transport, to_branch):
 
959
        to_url = to_branch.user_url
 
960
        if a_controldir.control_url == to_branch.controldir.control_url:
 
961
            # Write relative paths for colocated branches, but absolute
 
962
            # paths for everything else. This is for the benefit
 
963
            # of older bzr versions that don't support relative paths.
 
964
            to_url = urlutils.relative_url(a_controldir.user_url, to_branch.user_url)
 
965
        transport.put_bytes('location', to_url.encode('utf-8'))
 
966
 
 
967
    def set_reference(self, a_controldir, name, to_branch):
 
968
        """See BranchFormat.set_reference()."""
 
969
        transport = a_controldir.get_branch_transport(None, name=name)
 
970
        self._write_reference(a_controldir, transport, to_branch)
 
971
 
 
972
    def initialize(self, a_controldir, name=None, target_branch=None,
 
973
            repository=None, append_revisions_only=None):
 
974
        """Create a branch of this format in a_controldir."""
 
975
        if target_branch is None:
 
976
            # this format does not implement branch itself, thus the implicit
 
977
            # creation contract must see it as uninitializable
 
978
            raise errors.UninitializableFormat(self)
 
979
        mutter('creating branch reference in %s', a_controldir.user_url)
 
980
        if a_controldir._format.fixed_components:
 
981
            raise errors.IncompatibleFormat(self, a_controldir._format)
 
982
        if name is None:
 
983
            name = a_controldir._get_selected_branch()
 
984
        branch_transport = a_controldir.get_branch_transport(self, name=name)
 
985
        self._write_reference(a_controldir, branch_transport, target_branch)
 
986
        branch_transport.put_bytes('format', self.as_string())
 
987
        branch = self.open(a_controldir, name, _found=True,
 
988
            possible_transports=[target_branch.controldir.root_transport])
 
989
        self._run_post_branch_init_hooks(a_controldir, name, branch)
 
990
        return branch
 
991
 
 
992
    def _make_reference_clone_function(format, a_branch):
 
993
        """Create a clone() routine for a branch dynamically."""
 
994
        def clone(to_bzrdir, revision_id=None,
 
995
            repository_policy=None):
 
996
            """See Branch.clone()."""
 
997
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
998
            # cannot obey revision_id limits when cloning a reference ...
 
999
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
1000
            # emit some sort of warning/error to the caller ?!
 
1001
        return clone
 
1002
 
 
1003
    def open(self, a_controldir, name=None, _found=False, location=None,
 
1004
             possible_transports=None, ignore_fallbacks=False,
 
1005
             found_repository=None):
 
1006
        """Return the branch that the branch reference in a_controldir points at.
 
1007
 
 
1008
        :param a_controldir: A BzrDir that contains a branch.
 
1009
        :param name: Name of colocated branch to open, if any
 
1010
        :param _found: a private parameter, do not use it. It is used to
 
1011
            indicate if format probing has already be done.
 
1012
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1013
            (if there are any).  Default is to open fallbacks.
 
1014
        :param location: The location of the referenced branch.  If
 
1015
            unspecified, this will be determined from the branch reference in
 
1016
            a_controldir.
 
1017
        :param possible_transports: An optional reusable transports list.
 
1018
        """
 
1019
        if name is None:
 
1020
            name = a_controldir._get_selected_branch()
 
1021
        if not _found:
 
1022
            format = BranchFormatMetadir.find_format(a_controldir, name=name)
 
1023
            if format.__class__ != self.__class__:
 
1024
                raise AssertionError("wrong format %r found for %r" %
 
1025
                    (format, self))
 
1026
        if location is None:
 
1027
            location = self.get_reference(a_controldir, name)
 
1028
        real_bzrdir = controldir.ControlDir.open(
 
1029
            location, possible_transports=possible_transports)
 
1030
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
 
1031
            possible_transports=possible_transports)
 
1032
        # this changes the behaviour of result.clone to create a new reference
 
1033
        # rather than a copy of the content of the branch.
 
1034
        # I did not use a proxy object because that needs much more extensive
 
1035
        # testing, and we are only changing one behaviour at the moment.
 
1036
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
1037
        # then this should be refactored to introduce a tested proxy branch
 
1038
        # and a subclass of that for use in overriding clone() and ....
 
1039
        # - RBC 20060210
 
1040
        result.clone = self._make_reference_clone_function(result)
 
1041
        return result
 
1042
 
 
1043
 
 
1044
class Converter5to6(object):
 
1045
    """Perform an in-place upgrade of format 5 to format 6"""
 
1046
 
 
1047
    def convert(self, branch):
 
1048
        # Data for 5 and 6 can peacefully coexist.
 
1049
        format = BzrBranchFormat6()
 
1050
        new_branch = format.open(branch.controldir, _found=True)
 
1051
 
 
1052
        # Copy source data into target
 
1053
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
1054
        new_branch.lock_write()
 
1055
        try:
 
1056
            new_branch.set_parent(branch.get_parent())
 
1057
            new_branch.set_bound_location(branch.get_bound_location())
 
1058
            new_branch.set_push_location(branch.get_push_location())
 
1059
        finally:
 
1060
            new_branch.unlock()
 
1061
 
 
1062
        # New branch has no tags by default
 
1063
        new_branch.tags._set_tag_dict({})
 
1064
 
 
1065
        # Copying done; now update target format
 
1066
        new_branch._transport.put_bytes('format',
 
1067
            format.as_string(),
 
1068
            mode=new_branch.controldir._get_file_mode())
 
1069
 
 
1070
        # Clean up old files
 
1071
        new_branch._transport.delete('revision-history')
 
1072
        branch.lock_write()
 
1073
        try:
 
1074
            try:
 
1075
                branch.set_parent(None)
 
1076
            except errors.NoSuchFile:
 
1077
                pass
 
1078
            branch.set_bound_location(None)
 
1079
        finally:
 
1080
            branch.unlock()
 
1081
 
 
1082
 
 
1083
class Converter6to7(object):
 
1084
    """Perform an in-place upgrade of format 6 to format 7"""
 
1085
 
 
1086
    def convert(self, branch):
 
1087
        format = BzrBranchFormat7()
 
1088
        branch._set_config_location('stacked_on_location', '')
 
1089
        # update target format
 
1090
        branch._transport.put_bytes('format', format.as_string())
 
1091
 
 
1092
 
 
1093
class Converter7to8(object):
 
1094
    """Perform an in-place upgrade of format 7 to format 8"""
 
1095
 
 
1096
    def convert(self, branch):
 
1097
        format = BzrBranchFormat8()
 
1098
        branch._transport.put_bytes('references', '')
 
1099
        # update target format
 
1100
        branch._transport.put_bytes('format', format.as_string())
 
1101
 
 
1102
 
 
1103