~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-10-13 06:08:53 UTC
  • mfrom: (4737.1.1 merge-2.0-into-devel)
  • Revision ID: pqm@pqm.ubuntu.com-20091013060853-erk2aaj80fnkrv25
(andrew) Merge lp:bzr/2.0 into lp:bzr, including fixes for #322807,
        #389413, #402623 and documentation improvements.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012 Canonical Ltd
 
1
# Copyright (C) 2005, 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
 
import bzrlib.bzrdir
20
17
 
21
18
from cStringIO import StringIO
 
19
import sys
22
20
 
23
21
from bzrlib.lazy_import import lazy_import
24
22
lazy_import(globals(), """
25
 
import itertools
 
23
from itertools import chain
26
24
from bzrlib import (
27
 
    bzrdir,
28
 
    controldir,
29
 
    cache_utf8,
30
 
    cleanup,
31
 
    config as _mod_config,
32
 
    debug,
33
 
    errors,
34
 
    fetch,
35
 
    graph as _mod_graph,
36
 
    lockdir,
37
 
    lockable_files,
38
 
    remote,
39
 
    repository,
40
 
    revision as _mod_revision,
41
 
    rio,
42
 
    tag as _mod_tag,
43
 
    transport,
44
 
    ui,
45
 
    urlutils,
46
 
    vf_search,
 
25
        bzrdir,
 
26
        cache_utf8,
 
27
        config as _mod_config,
 
28
        debug,
 
29
        errors,
 
30
        lockdir,
 
31
        lockable_files,
 
32
        repository,
 
33
        revision as _mod_revision,
 
34
        rio,
 
35
        symbol_versioning,
 
36
        transport,
 
37
        tsort,
 
38
        ui,
 
39
        urlutils,
 
40
        )
 
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
43
from bzrlib.tag import (
 
44
    BasicTags,
 
45
    DisabledTags,
47
46
    )
48
 
from bzrlib.i18n import gettext, ngettext
49
47
""")
50
48
 
51
 
# Explicitly import bzrlib.bzrdir so that the BzrProber
52
 
# is guaranteed to be registered.
53
 
import bzrlib.bzrdir
54
 
 
55
 
from bzrlib import (
56
 
    bzrdir,
57
 
    controldir,
58
 
    )
59
 
from bzrlib.decorators import (
60
 
    needs_read_lock,
61
 
    needs_write_lock,
62
 
    only_raises,
63
 
    )
64
 
from bzrlib.hooks import Hooks
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
50
from bzrlib.hooks import HookPoint, Hooks
65
51
from bzrlib.inter import InterObject
66
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
67
53
from bzrlib import registry
68
54
from bzrlib.symbol_versioning import (
69
55
    deprecated_in,
72
58
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
73
59
 
74
60
 
75
 
class Branch(controldir.ControlComponent):
 
61
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
62
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
64
 
 
65
 
 
66
# TODO: Maybe include checks for common corruption of newlines, etc?
 
67
 
 
68
# TODO: Some operations like log might retrieve the same revisions
 
69
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
70
# cache in memory to make this faster.  In general anything can be
 
71
# cached in memory between lock and unlock operations. .. nb thats
 
72
# what the transaction identity map provides
 
73
 
 
74
 
 
75
######################################################################
 
76
# branch objects
 
77
 
 
78
class Branch(object):
76
79
    """Branch holding a history of revisions.
77
80
 
78
 
    :ivar base:
79
 
        Base directory/url of the branch; using control_url and
80
 
        control_transport is more standardized.
81
 
    :ivar hooks: An instance of BranchHooks.
82
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
83
 
        _clear_cached_state.
 
81
    base
 
82
        Base directory/url of the branch.
 
83
 
 
84
    hooks: An instance of BranchHooks.
84
85
    """
85
86
    # this is really an instance variable - FIXME move it there
86
87
    # - RBC 20060112
87
88
    base = None
88
89
 
89
 
    @property
90
 
    def control_transport(self):
91
 
        return self._transport
92
 
 
93
 
    @property
94
 
    def user_transport(self):
95
 
        return self.bzrdir.user_transport
96
 
 
97
 
    def __init__(self, possible_transports=None):
 
90
    def __init__(self, *ignored, **ignored_too):
98
91
        self.tags = self._format.make_tags(self)
99
92
        self._revision_history_cache = None
100
93
        self._revision_id_to_revno_cache = None
101
94
        self._partial_revision_id_to_revno_cache = {}
102
95
        self._partial_revision_history_cache = []
103
 
        self._tags_bytes = None
104
96
        self._last_revision_info_cache = None
105
 
        self._master_branch_cache = None
106
97
        self._merge_sorted_revisions_cache = None
107
 
        self._open_hook(possible_transports)
 
98
        self._open_hook()
108
99
        hooks = Branch.hooks['open']
109
100
        for hook in hooks:
110
101
            hook(self)
111
102
 
112
 
    def _open_hook(self, possible_transports):
 
103
    def _open_hook(self):
113
104
        """Called by init to allow simpler extension of the base class."""
114
105
 
115
 
    def _activate_fallback_location(self, url, possible_transports):
 
106
    def _activate_fallback_location(self, url):
116
107
        """Activate the branch/repository from url as a fallback repository."""
117
 
        for existing_fallback_repo in self.repository._fallback_repositories:
118
 
            if existing_fallback_repo.user_url == url:
119
 
                # This fallback is already configured.  This probably only
120
 
                # happens because ControlDir.sprout is a horrible mess.  To avoid
121
 
                # confusing _unstack we don't add this a second time.
122
 
                mutter('duplicate activation of fallback %r on %r', url, self)
123
 
                return
124
 
        repo = self._get_fallback_repository(url, possible_transports)
 
108
        repo = self._get_fallback_repository(url)
125
109
        if repo.has_same_location(self.repository):
126
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
110
            raise errors.UnstackableLocationError(self.base, url)
127
111
        self.repository.add_fallback_repository(repo)
128
112
 
129
113
    def break_lock(self):
181
165
        For instance, if the branch is at URL/.bzr/branch,
182
166
        Branch.open(URL) -> a Branch instance.
183
167
        """
184
 
        control = controldir.ControlDir.open(base,
185
 
            possible_transports=possible_transports, _unsupported=_unsupported)
186
 
        return control.open_branch(unsupported=_unsupported,
187
 
            possible_transports=possible_transports)
 
168
        control = bzrdir.BzrDir.open(base, _unsupported,
 
169
                                     possible_transports=possible_transports)
 
170
        return control.open_branch(_unsupported)
188
171
 
189
172
    @staticmethod
190
 
    def open_from_transport(transport, name=None, _unsupported=False,
191
 
            possible_transports=None):
 
173
    def open_from_transport(transport, _unsupported=False):
192
174
        """Open the branch rooted at transport"""
193
 
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
194
 
        return control.open_branch(name=name, unsupported=_unsupported,
195
 
            possible_transports=possible_transports)
 
175
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
176
        return control.open_branch(_unsupported)
196
177
 
197
178
    @staticmethod
198
179
    def open_containing(url, possible_transports=None):
206
187
        format, UnknownFormatError or UnsupportedFormatError are raised.
207
188
        If there is one, it is returned, along with the unused portion of url.
208
189
        """
209
 
        control, relpath = controldir.ControlDir.open_containing(url,
 
190
        control, relpath = bzrdir.BzrDir.open_containing(url,
210
191
                                                         possible_transports)
211
 
        branch = control.open_branch(possible_transports=possible_transports)
212
 
        return (branch, relpath)
 
192
        return control.open_branch(), relpath
213
193
 
214
194
    def _push_should_merge_tags(self):
215
195
        """Should _basic_push merge this branch's tags into the target?
220
200
        return self.supports_tags() and self.tags.get_tag_dict()
221
201
 
222
202
    def get_config(self):
223
 
        """Get a bzrlib.config.BranchConfig for this Branch.
224
 
 
225
 
        This can then be used to get and set configuration options for the
226
 
        branch.
227
 
 
228
 
        :return: A bzrlib.config.BranchConfig.
229
 
        """
230
 
        return _mod_config.BranchConfig(self)
231
 
 
232
 
    def get_config_stack(self):
233
 
        """Get a bzrlib.config.BranchStack for this Branch.
234
 
 
235
 
        This can then be used to get and set configuration options for the
236
 
        branch.
237
 
 
238
 
        :return: A bzrlib.config.BranchStack.
239
 
        """
240
 
        return _mod_config.BranchStack(self)
 
203
        return BranchConfig(self)
241
204
 
242
205
    def _get_config(self):
243
206
        """Get the concrete config for just the config in this branch.
251
214
        """
252
215
        raise NotImplementedError(self._get_config)
253
216
 
254
 
    def _get_fallback_repository(self, url, possible_transports):
 
217
    def _get_fallback_repository(self, url):
255
218
        """Get the repository we fallback to at url."""
256
219
        url = urlutils.join(self.base, url)
257
 
        a_branch = Branch.open(url, possible_transports=possible_transports)
258
 
        return a_branch.repository
 
220
        a_bzrdir = bzrdir.BzrDir.open(url,
 
221
            possible_transports=[self.bzrdir.root_transport])
 
222
        return a_bzrdir.open_branch().repository
259
223
 
260
 
    @needs_read_lock
261
224
    def _get_tags_bytes(self):
262
225
        """Get the bytes of a serialised tags dict.
263
226
 
270
233
        :return: The bytes of the tags file.
271
234
        :seealso: Branch._set_tags_bytes.
272
235
        """
273
 
        if self._tags_bytes is None:
274
 
            self._tags_bytes = self._transport.get_bytes('tags')
275
 
        return self._tags_bytes
 
236
        return self._transport.get_bytes('tags')
276
237
 
277
238
    def _get_nick(self, local=False, possible_transports=None):
278
239
        config = self.get_config()
280
241
        if not local and not config.has_explicit_nickname():
281
242
            try:
282
243
                master = self.get_master_branch(possible_transports)
283
 
                if master and self.user_url == master.user_url:
284
 
                    raise errors.RecursiveBind(self.user_url)
285
244
                if master is not None:
286
245
                    # return the master branch value
287
246
                    return master.nick
288
 
            except errors.RecursiveBind, e:
289
 
                raise e
290
247
            except errors.BzrError, e:
291
248
                # Silently fall back to local implicit nick if the master is
292
249
                # unavailable
329
286
        new_history.reverse()
330
287
        return new_history
331
288
 
332
 
    def lock_write(self, token=None):
333
 
        """Lock the branch for write operations.
334
 
 
335
 
        :param token: A token to permit reacquiring a previously held and
336
 
            preserved lock.
337
 
        :return: A BranchWriteLockResult.
338
 
        """
 
289
    def lock_write(self):
339
290
        raise NotImplementedError(self.lock_write)
340
291
 
341
292
    def lock_read(self):
342
 
        """Lock the branch for read operations.
343
 
 
344
 
        :return: A bzrlib.lock.LogicalLockResult.
345
 
        """
346
293
        raise NotImplementedError(self.lock_read)
347
294
 
348
295
    def unlock(self):
469
416
            after. If None, the rest of history is included.
470
417
        :param stop_rule: if stop_revision_id is not None, the precise rule
471
418
            to use for termination:
472
 
 
473
419
            * 'exclude' - leave the stop revision out of the result (default)
474
420
            * 'include' - the stop revision is the last item in the result
475
421
            * 'with-merges' - include the stop revision and all of its
476
422
              merged revisions in the result
477
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
478
 
              that are in both ancestries
479
423
        :param direction: either 'reverse' or 'forward':
480
 
 
481
424
            * reverse means return the start_revision_id first, i.e.
482
425
              start at the most recent revision and go backwards in history
483
426
            * forward returns tuples in the opposite order to reverse.
504
447
        # start_revision_id.
505
448
        if self._merge_sorted_revisions_cache is None:
506
449
            last_revision = self.last_revision()
507
 
            known_graph = self.repository.get_known_graph_ancestry(
508
 
                [last_revision])
 
450
            last_key = (last_revision,)
 
451
            known_graph = self.repository.revisions.get_known_graph_ancestry(
 
452
                [last_key])
509
453
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
510
 
                last_revision)
 
454
                last_key)
511
455
        filtered = self._filter_merge_sorted_revisions(
512
456
            self._merge_sorted_revisions_cache, start_revision_id,
513
457
            stop_revision_id, stop_rule)
514
 
        # Make sure we don't return revisions that are not part of the
515
 
        # start_revision_id ancestry.
516
 
        filtered = self._filter_start_non_ancestors(filtered)
517
458
        if direction == 'reverse':
518
459
            return filtered
519
460
        if direction == 'forward':
527
468
        rev_iter = iter(merge_sorted_revisions)
528
469
        if start_revision_id is not None:
529
470
            for node in rev_iter:
530
 
                rev_id = node.key
 
471
                rev_id = node.key[-1]
531
472
                if rev_id != start_revision_id:
532
473
                    continue
533
474
                else:
534
475
                    # The decision to include the start or not
535
476
                    # depends on the stop_rule if a stop is provided
536
477
                    # so pop this node back into the iterator
537
 
                    rev_iter = itertools.chain(iter([node]), rev_iter)
 
478
                    rev_iter = chain(iter([node]), rev_iter)
538
479
                    break
539
480
        if stop_revision_id is None:
540
481
            # Yield everything
541
482
            for node in rev_iter:
542
 
                rev_id = node.key
 
483
                rev_id = node.key[-1]
543
484
                yield (rev_id, node.merge_depth, node.revno,
544
485
                       node.end_of_merge)
545
486
        elif stop_rule == 'exclude':
546
487
            for node in rev_iter:
547
 
                rev_id = node.key
 
488
                rev_id = node.key[-1]
548
489
                if rev_id == stop_revision_id:
549
490
                    return
550
491
                yield (rev_id, node.merge_depth, node.revno,
551
492
                       node.end_of_merge)
552
493
        elif stop_rule == 'include':
553
494
            for node in rev_iter:
554
 
                rev_id = node.key
 
495
                rev_id = node.key[-1]
555
496
                yield (rev_id, node.merge_depth, node.revno,
556
497
                       node.end_of_merge)
557
498
                if rev_id == stop_revision_id:
558
499
                    return
559
 
        elif stop_rule == 'with-merges-without-common-ancestry':
560
 
            # We want to exclude all revisions that are already part of the
561
 
            # stop_revision_id ancestry.
562
 
            graph = self.repository.get_graph()
563
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
564
 
                                                    [stop_revision_id])
565
 
            for node in rev_iter:
566
 
                rev_id = node.key
567
 
                if rev_id not in ancestors:
568
 
                    continue
569
 
                yield (rev_id, node.merge_depth, node.revno,
570
 
                       node.end_of_merge)
571
500
        elif stop_rule == 'with-merges':
572
501
            stop_rev = self.repository.get_revision(stop_revision_id)
573
502
            if stop_rev.parent_ids:
574
503
                left_parent = stop_rev.parent_ids[0]
575
504
            else:
576
505
                left_parent = _mod_revision.NULL_REVISION
577
 
            # left_parent is the actual revision we want to stop logging at,
578
 
            # since we want to show the merged revisions after the stop_rev too
579
 
            reached_stop_revision_id = False
580
 
            revision_id_whitelist = []
581
506
            for node in rev_iter:
582
 
                rev_id = node.key
 
507
                rev_id = node.key[-1]
583
508
                if rev_id == left_parent:
584
 
                    # reached the left parent after the stop_revision
585
509
                    return
586
 
                if (not reached_stop_revision_id or
587
 
                        rev_id in revision_id_whitelist):
588
 
                    yield (rev_id, node.merge_depth, node.revno,
 
510
                yield (rev_id, node.merge_depth, node.revno,
589
511
                       node.end_of_merge)
590
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
591
 
                        # only do the merged revs of rev_id from now on
592
 
                        rev = self.repository.get_revision(rev_id)
593
 
                        if rev.parent_ids:
594
 
                            reached_stop_revision_id = True
595
 
                            revision_id_whitelist.extend(rev.parent_ids)
596
512
        else:
597
513
            raise ValueError('invalid stop_rule %r' % stop_rule)
598
514
 
599
 
    def _filter_start_non_ancestors(self, rev_iter):
600
 
        # If we started from a dotted revno, we want to consider it as a tip
601
 
        # and don't want to yield revisions that are not part of its
602
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
603
 
        # uninteresting descendants of the first parent of our tip before the
604
 
        # tip itself.
605
 
        first = rev_iter.next()
606
 
        (rev_id, merge_depth, revno, end_of_merge) = first
607
 
        yield first
608
 
        if not merge_depth:
609
 
            # We start at a mainline revision so by definition, all others
610
 
            # revisions in rev_iter are ancestors
611
 
            for node in rev_iter:
612
 
                yield node
613
 
 
614
 
        clean = False
615
 
        whitelist = set()
616
 
        pmap = self.repository.get_parent_map([rev_id])
617
 
        parents = pmap.get(rev_id, [])
618
 
        if parents:
619
 
            whitelist.update(parents)
620
 
        else:
621
 
            # If there is no parents, there is nothing of interest left
622
 
 
623
 
            # FIXME: It's hard to test this scenario here as this code is never
624
 
            # called in that case. -- vila 20100322
625
 
            return
626
 
 
627
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
628
 
            if not clean:
629
 
                if rev_id in whitelist:
630
 
                    pmap = self.repository.get_parent_map([rev_id])
631
 
                    parents = pmap.get(rev_id, [])
632
 
                    whitelist.remove(rev_id)
633
 
                    whitelist.update(parents)
634
 
                    if merge_depth == 0:
635
 
                        # We've reached the mainline, there is nothing left to
636
 
                        # filter
637
 
                        clean = True
638
 
                else:
639
 
                    # A revision that is not part of the ancestry of our
640
 
                    # starting revision.
641
 
                    continue
642
 
            yield (rev_id, merge_depth, revno, end_of_merge)
643
 
 
644
515
    def leave_lock_in_place(self):
645
516
        """Tell this branch object not to release the physical lock when this
646
517
        object is unlocked.
663
534
        :param other: The branch to bind to
664
535
        :type other: Branch
665
536
        """
666
 
        raise errors.UpgradeRequired(self.user_url)
667
 
 
668
 
    def get_append_revisions_only(self):
669
 
        """Whether it is only possible to append revisions to the history.
670
 
        """
671
 
        if not self._format.supports_set_append_revisions_only():
672
 
            return False
673
 
        return self.get_config_stack().get('append_revisions_only')
 
537
        raise errors.UpgradeRequired(self.base)
674
538
 
675
539
    def set_append_revisions_only(self, enabled):
676
540
        if not self._format.supports_set_append_revisions_only():
677
 
            raise errors.UpgradeRequired(self.user_url)
678
 
        self.get_config_stack().set('append_revisions_only', enabled)
 
541
            raise errors.UpgradeRequired(self.base)
 
542
        if enabled:
 
543
            value = 'True'
 
544
        else:
 
545
            value = 'False'
 
546
        self.get_config().set_user_option('append_revisions_only', value,
 
547
            warn_masked=True)
679
548
 
680
549
    def set_reference_info(self, file_id, tree_path, branch_location):
681
550
        """Set the branch location to use for a tree reference."""
686
555
        raise errors.UnsupportedOperation(self.get_reference_info, self)
687
556
 
688
557
    @needs_write_lock
689
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
558
    def fetch(self, from_branch, last_revision=None, pb=None):
690
559
        """Copy revisions from from_branch into this branch.
691
560
 
692
561
        :param from_branch: Where to copy from.
693
562
        :param last_revision: What revision to stop at (None for at the end
694
563
                              of the branch.
695
 
        :param limit: Optional rough limit of revisions to fetch
 
564
        :param pb: An optional progress bar to use.
696
565
        :return: None
697
566
        """
698
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
567
        if self.base == from_branch.base:
 
568
            return (0, [])
 
569
        if pb is not None:
 
570
            symbol_versioning.warn(
 
571
                symbol_versioning.deprecated_in((1, 14, 0))
 
572
                % "pb parameter to fetch()")
 
573
        from_branch.lock_read()
 
574
        try:
 
575
            if last_revision is None:
 
576
                last_revision = from_branch.last_revision()
 
577
                last_revision = _mod_revision.ensure_null(last_revision)
 
578
            return self.repository.fetch(from_branch.repository,
 
579
                                         revision_id=last_revision,
 
580
                                         pb=pb)
 
581
        finally:
 
582
            from_branch.unlock()
699
583
 
700
584
    def get_bound_location(self):
701
585
        """Return the URL of the branch we are bound to.
708
592
    def get_old_bound_location(self):
709
593
        """Return the URL of the branch we used to be bound to
710
594
        """
711
 
        raise errors.UpgradeRequired(self.user_url)
 
595
        raise errors.UpgradeRequired(self.base)
712
596
 
713
 
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
 
597
    def get_commit_builder(self, parents, config=None, timestamp=None,
714
598
                           timezone=None, committer=None, revprops=None,
715
 
                           revision_id=None, lossy=False):
 
599
                           revision_id=None):
716
600
        """Obtain a CommitBuilder for this branch.
717
601
 
718
602
        :param parents: Revision ids of the parents of the new revision.
722
606
        :param committer: Optional committer to set for commit.
723
607
        :param revprops: Optional dictionary of revision properties.
724
608
        :param revision_id: Optional revision id.
725
 
        :param lossy: Whether to discard data that can not be natively
726
 
            represented, when pushing to a foreign VCS 
727
609
        """
728
610
 
729
 
        if config_stack is None:
730
 
            config_stack = self.get_config_stack()
 
611
        if config is None:
 
612
            config = self.get_config()
731
613
 
732
 
        return self.repository.get_commit_builder(self, parents, config_stack,
733
 
            timestamp, timezone, committer, revprops, revision_id,
734
 
            lossy)
 
614
        return self.repository.get_commit_builder(self, parents, config,
 
615
            timestamp, timezone, committer, revprops, revision_id)
735
616
 
736
617
    def get_master_branch(self, possible_transports=None):
737
618
        """Return the branch we are bound to.
740
621
        """
741
622
        return None
742
623
 
743
 
    @deprecated_method(deprecated_in((2, 5, 0)))
744
624
    def get_revision_delta(self, revno):
745
625
        """Return the delta for one revision.
746
626
 
747
627
        The delta is relative to its mainline predecessor, or the
748
628
        empty tree for revision 1.
749
629
        """
750
 
        try:
751
 
            revid = self.get_rev_id(revno)
752
 
        except errors.NoSuchRevision:
 
630
        rh = self.revision_history()
 
631
        if not (1 <= revno <= len(rh)):
753
632
            raise errors.InvalidRevisionNumber(revno)
754
 
        return self.repository.get_revision_delta(revid)
 
633
        return self.repository.get_revision_delta(rh[revno-1])
755
634
 
756
635
    def get_stacked_on_url(self):
757
636
        """Get the URL this branch is stacked against.
766
645
        """Print `file` to stdout."""
767
646
        raise NotImplementedError(self.print_file)
768
647
 
769
 
    @needs_write_lock
770
 
    def set_last_revision_info(self, revno, revision_id):
771
 
        """Set the last revision of this branch.
772
 
 
773
 
        The caller is responsible for checking that the revno is correct
774
 
        for this revision id.
775
 
 
776
 
        It may be possible to set the branch last revision to an id not
777
 
        present in the repository.  However, branches can also be
778
 
        configured to check constraints on history, in which case this may not
779
 
        be permitted.
780
 
        """
781
 
        raise NotImplementedError(self.set_last_revision_info)
782
 
 
783
 
    @needs_write_lock
784
 
    def generate_revision_history(self, revision_id, last_rev=None,
785
 
                                  other_branch=None):
786
 
        """See Branch.generate_revision_history"""
787
 
        graph = self.repository.get_graph()
788
 
        (last_revno, last_revid) = self.last_revision_info()
789
 
        known_revision_ids = [
790
 
            (last_revid, last_revno),
791
 
            (_mod_revision.NULL_REVISION, 0),
792
 
            ]
793
 
        if last_rev is not None:
794
 
            if not graph.is_ancestor(last_rev, revision_id):
795
 
                # our previous tip is not merged into stop_revision
796
 
                raise errors.DivergedBranches(self, other_branch)
797
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
798
 
        self.set_last_revision_info(revno, revision_id)
 
648
    def set_revision_history(self, rev_history):
 
649
        raise NotImplementedError(self.set_revision_history)
799
650
 
800
651
    @needs_write_lock
801
652
    def set_parent(self, url):
825
676
            stacking.
826
677
        """
827
678
        if not self._format.supports_stacking():
828
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
679
            raise errors.UnstackableBranchFormat(self._format, self.base)
829
680
        # XXX: Changing from one fallback repository to another does not check
830
681
        # that all the data you need is present in the new fallback.
831
682
        # Possibly it should.
838
689
                return
839
690
            self._unstack()
840
691
        else:
841
 
            self._activate_fallback_location(url,
842
 
                possible_transports=[self.bzrdir.root_transport])
 
692
            self._activate_fallback_location(url)
843
693
        # write this out after the repository is stacked to avoid setting a
844
694
        # stacked config that doesn't work.
845
695
        self._set_config_location('stacked_on_location', url)
846
696
 
847
697
    def _unstack(self):
848
698
        """Change a branch to be unstacked, copying data as needed.
849
 
 
 
699
        
850
700
        Don't call this directly, use set_stacked_on_url(None).
851
701
        """
852
702
        pb = ui.ui_factory.nested_progress_bar()
853
703
        try:
854
 
            pb.update(gettext("Unstacking"))
 
704
            pb.update("Unstacking")
855
705
            # The basic approach here is to fetch the tip of the branch,
856
706
            # including all available ghosts, from the existing stacked
857
707
            # repository into a new repository object without the fallbacks. 
861
711
            old_repository = self.repository
862
712
            if len(old_repository._fallback_repositories) != 1:
863
713
                raise AssertionError("can't cope with fallback repositories "
864
 
                    "of %r (fallbacks: %r)" % (old_repository,
865
 
                        old_repository._fallback_repositories))
866
 
            # Open the new repository object.
867
 
            # Repositories don't offer an interface to remove fallback
868
 
            # repositories today; take the conceptually simpler option and just
869
 
            # reopen it.  We reopen it starting from the URL so that we
870
 
            # get a separate connection for RemoteRepositories and can
871
 
            # stream from one of them to the other.  This does mean doing
872
 
            # separate SSH connection setup, but unstacking is not a
873
 
            # common operation so it's tolerable.
874
 
            new_bzrdir = controldir.ControlDir.open(
875
 
                self.bzrdir.root_transport.base)
876
 
            new_repository = new_bzrdir.find_repository()
877
 
            if new_repository._fallback_repositories:
878
 
                raise AssertionError("didn't expect %r to have "
879
 
                    "fallback_repositories"
880
 
                    % (self.repository,))
881
 
            # Replace self.repository with the new repository.
882
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
883
 
            # lock count) of self.repository to the new repository.
884
 
            lock_token = old_repository.lock_write().repository_token
885
 
            self.repository = new_repository
886
 
            if isinstance(self, remote.RemoteBranch):
887
 
                # Remote branches can have a second reference to the old
888
 
                # repository that need to be replaced.
889
 
                if self._real_branch is not None:
890
 
                    self._real_branch.repository = new_repository
891
 
            self.repository.lock_write(token=lock_token)
892
 
            if lock_token is not None:
893
 
                old_repository.leave_lock_in_place()
 
714
                    "of %r" % (self.repository,))
 
715
            # unlock it, including unlocking the fallback
894
716
            old_repository.unlock()
895
 
            if lock_token is not None:
896
 
                # XXX: self.repository.leave_lock_in_place() before this
897
 
                # function will not be preserved.  Fortunately that doesn't
898
 
                # affect the current default format (2a), and would be a
899
 
                # corner-case anyway.
900
 
                #  - Andrew Bennetts, 2010/06/30
901
 
                self.repository.dont_leave_lock_in_place()
902
 
            old_lock_count = 0
903
 
            while True:
904
 
                try:
905
 
                    old_repository.unlock()
906
 
                except errors.LockNotHeld:
907
 
                    break
908
 
                old_lock_count += 1
909
 
            if old_lock_count == 0:
910
 
                raise AssertionError(
911
 
                    'old_repository should have been locked at least once.')
912
 
            for i in range(old_lock_count-1):
 
717
            old_repository.lock_read()
 
718
            try:
 
719
                # Repositories don't offer an interface to remove fallback
 
720
                # repositories today; take the conceptually simpler option and just
 
721
                # reopen it.  We reopen it starting from the URL so that we
 
722
                # get a separate connection for RemoteRepositories and can
 
723
                # stream from one of them to the other.  This does mean doing
 
724
                # separate SSH connection setup, but unstacking is not a
 
725
                # common operation so it's tolerable.
 
726
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
727
                new_repository = new_bzrdir.find_repository()
 
728
                self.repository = new_repository
 
729
                if self.repository._fallback_repositories:
 
730
                    raise AssertionError("didn't expect %r to have "
 
731
                        "fallback_repositories"
 
732
                        % (self.repository,))
 
733
                # this is not paired with an unlock because it's just restoring
 
734
                # the previous state; the lock's released when set_stacked_on_url
 
735
                # returns
913
736
                self.repository.lock_write()
914
 
            # Fetch from the old repository into the new.
915
 
            old_repository.lock_read()
916
 
            try:
917
737
                # XXX: If you unstack a branch while it has a working tree
918
738
                # with a pending merge, the pending-merged revisions will no
919
739
                # longer be present.  You can (probably) revert and remerge.
920
 
                try:
921
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
922
 
                except errors.TagsNotSupported:
923
 
                    tags_to_fetch = set()
924
 
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
925
 
                    old_repository, required_ids=[self.last_revision()],
926
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
927
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
740
                #
 
741
                # XXX: This only fetches up to the tip of the repository; it
 
742
                # doesn't bring across any tags.  That's fairly consistent
 
743
                # with how branch works, but perhaps not ideal.
 
744
                self.repository.fetch(old_repository,
 
745
                    revision_id=self.last_revision(),
 
746
                    find_ghosts=True)
928
747
            finally:
929
748
                old_repository.unlock()
930
749
        finally:
935
754
 
936
755
        :seealso: Branch._get_tags_bytes.
937
756
        """
938
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
939
 
        op.add_cleanup(self.lock_write().unlock)
940
 
        return op.run_simple(bytes)
941
 
 
942
 
    def _set_tags_bytes_locked(self, bytes):
943
 
        self._tags_bytes = bytes
944
 
        return self._transport.put_bytes('tags', bytes)
 
757
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
758
            'tags', bytes)
945
759
 
946
760
    def _cache_revision_history(self, rev_history):
947
761
        """Set the cached revision history to rev_history.
968
782
        This means the next call to revision_history will need to call
969
783
        _gen_revision_history.
970
784
 
971
 
        This API is semi-public; it is only for use by subclasses, all other
972
 
        code should consider it to be private.
 
785
        This API is semi-public; it only for use by subclasses, all other code
 
786
        should consider it to be private.
973
787
        """
974
788
        self._revision_history_cache = None
975
789
        self._revision_id_to_revno_cache = None
976
790
        self._last_revision_info_cache = None
977
 
        self._master_branch_cache = None
978
791
        self._merge_sorted_revisions_cache = None
979
792
        self._partial_revision_history_cache = []
980
793
        self._partial_revision_id_to_revno_cache = {}
981
 
        self._tags_bytes = None
982
794
 
983
795
    def _gen_revision_history(self):
984
796
        """Return sequence of revision hashes on to this branch.
995
807
        """
996
808
        raise NotImplementedError(self._gen_revision_history)
997
809
 
998
 
    def _revision_history(self):
 
810
    @needs_read_lock
 
811
    def revision_history(self):
 
812
        """Return sequence of revision ids on this branch.
 
813
 
 
814
        This method will cache the revision history for as long as it is safe to
 
815
        do so.
 
816
        """
999
817
        if 'evil' in debug.debug_flags:
1000
818
            mutter_callsite(3, "revision_history scales with history.")
1001
819
        if self._revision_history_cache is not None:
1015
833
 
1016
834
    def unbind(self):
1017
835
        """Older format branches cannot bind or unbind."""
1018
 
        raise errors.UpgradeRequired(self.user_url)
 
836
        raise errors.UpgradeRequired(self.base)
1019
837
 
1020
838
    def last_revision(self):
1021
839
        """Return last revision id, or NULL_REVISION."""
1028
846
        :return: A tuple (revno, revision_id).
1029
847
        """
1030
848
        if self._last_revision_info_cache is None:
1031
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
849
            self._last_revision_info_cache = self._last_revision_info()
1032
850
        return self._last_revision_info_cache
1033
851
 
1034
 
    def _read_last_revision_info(self):
1035
 
        raise NotImplementedError(self._read_last_revision_info)
1036
 
 
1037
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
852
    def _last_revision_info(self):
 
853
        rh = self.revision_history()
 
854
        revno = len(rh)
 
855
        if revno:
 
856
            return (revno, rh[-1])
 
857
        else:
 
858
            return (0, _mod_revision.NULL_REVISION)
 
859
 
 
860
    @deprecated_method(deprecated_in((1, 6, 0)))
 
861
    def missing_revisions(self, other, stop_revision=None):
 
862
        """Return a list of new revisions that would perfectly fit.
 
863
 
 
864
        If self and other have not diverged, return a list of the revisions
 
865
        present in other, but missing from self.
 
866
        """
 
867
        self_history = self.revision_history()
 
868
        self_len = len(self_history)
 
869
        other_history = other.revision_history()
 
870
        other_len = len(other_history)
 
871
        common_index = min(self_len, other_len) -1
 
872
        if common_index >= 0 and \
 
873
            self_history[common_index] != other_history[common_index]:
 
874
            raise errors.DivergedBranches(self, other)
 
875
 
 
876
        if stop_revision is None:
 
877
            stop_revision = other_len
 
878
        else:
 
879
            if stop_revision > other_len:
 
880
                raise errors.NoSuchRevision(self, stop_revision)
 
881
        return other_history[self_len:stop_revision]
 
882
 
 
883
    @needs_write_lock
 
884
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
885
                         graph=None):
 
886
        """Pull in new perfect-fit revisions.
 
887
 
 
888
        :param other: Another Branch to pull from
 
889
        :param stop_revision: Updated until the given revision
 
890
        :param overwrite: Always set the branch pointer, rather than checking
 
891
            to see if it is a proper descendant.
 
892
        :param graph: A Graph object that can be used to query history
 
893
            information. This can be None.
 
894
        :return: None
 
895
        """
 
896
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
897
            overwrite, graph)
 
898
 
1038
899
    def import_last_revision_info(self, source_repo, revno, revid):
1039
900
        """Set the last revision info, importing from another repo if necessary.
1040
901
 
 
902
        This is used by the bound branch code to upload a revision to
 
903
        the master branch first before updating the tip of the local branch.
 
904
 
1041
905
        :param source_repo: Source repository to optionally fetch from
1042
906
        :param revno: Revision number of the new tip
1043
907
        :param revid: Revision id of the new tip
1046
910
            self.repository.fetch(source_repo, revision_id=revid)
1047
911
        self.set_last_revision_info(revno, revid)
1048
912
 
1049
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1050
 
                                           lossy=False):
1051
 
        """Set the last revision info, importing from another repo if necessary.
1052
 
 
1053
 
        This is used by the bound branch code to upload a revision to
1054
 
        the master branch first before updating the tip of the local branch.
1055
 
        Revisions referenced by source's tags are also transferred.
1056
 
 
1057
 
        :param source: Source branch to optionally fetch from
1058
 
        :param revno: Revision number of the new tip
1059
 
        :param revid: Revision id of the new tip
1060
 
        :param lossy: Whether to discard metadata that can not be
1061
 
            natively represented
1062
 
        :return: Tuple with the new revision number and revision id
1063
 
            (should only be different from the arguments when lossy=True)
1064
 
        """
1065
 
        if not self.repository.has_same_location(source.repository):
1066
 
            self.fetch(source, revid)
1067
 
        self.set_last_revision_info(revno, revid)
1068
 
        return (revno, revid)
1069
 
 
1070
913
    def revision_id_to_revno(self, revision_id):
1071
914
        """Given a revision id, return its revno"""
1072
915
        if _mod_revision.is_null(revision_id):
1073
916
            return 0
1074
 
        history = self._revision_history()
 
917
        history = self.revision_history()
1075
918
        try:
1076
919
            return history.index(revision_id) + 1
1077
920
        except ValueError:
1092
935
            self._extend_partial_history(distance_from_last)
1093
936
        return self._partial_revision_history_cache[distance_from_last]
1094
937
 
 
938
    @needs_write_lock
1095
939
    def pull(self, source, overwrite=False, stop_revision=None,
1096
940
             possible_transports=None, *args, **kwargs):
1097
941
        """Mirror source into this branch.
1104
948
            stop_revision=stop_revision,
1105
949
            possible_transports=possible_transports, *args, **kwargs)
1106
950
 
1107
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1108
 
            *args, **kwargs):
 
951
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
952
        **kwargs):
1109
953
        """Mirror this branch into target.
1110
954
 
1111
955
        This branch is considered to be 'local', having low latency.
1112
956
        """
1113
957
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1114
 
            lossy, *args, **kwargs)
 
958
            *args, **kwargs)
 
959
 
 
960
    def lossy_push(self, target, stop_revision=None):
 
961
        """Push deltas into another branch.
 
962
 
 
963
        :note: This does not, like push, retain the revision ids from 
 
964
            the source branch and will, rather than adding bzr-specific 
 
965
            metadata, push only those semantics of the revision that can be 
 
966
            natively represented by this branch' VCS.
 
967
 
 
968
        :param target: Target branch
 
969
        :param stop_revision: Revision to push, defaults to last revision.
 
970
        :return: BranchPushResult with an extra member revidmap: 
 
971
            A dictionary mapping revision ids from the target branch 
 
972
            to new revision ids in the target branch, for each 
 
973
            revision that was pushed.
 
974
        """
 
975
        inter = InterBranch.get(self, target)
 
976
        lossy_push = getattr(inter, "lossy_push", None)
 
977
        if lossy_push is None:
 
978
            raise errors.LossyPushToSameVCS(self, target)
 
979
        return lossy_push(stop_revision)
1115
980
 
1116
981
    def basis_tree(self):
1117
982
        """Return `Tree` object for last revision."""
1134
999
        try:
1135
1000
            return urlutils.join(self.base[:-1], parent)
1136
1001
        except errors.InvalidURLJoin, e:
1137
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
1002
            raise errors.InaccessibleParent(parent, self.base)
1138
1003
 
1139
1004
    def _get_parent_location(self):
1140
1005
        raise NotImplementedError(self._get_parent_location)
1142
1007
    def _set_config_location(self, name, url, config=None,
1143
1008
                             make_relative=False):
1144
1009
        if config is None:
1145
 
            config = self.get_config_stack()
 
1010
            config = self.get_config()
1146
1011
        if url is None:
1147
1012
            url = ''
1148
1013
        elif make_relative:
1149
1014
            url = urlutils.relative_url(self.base, url)
1150
 
        config.set(name, url)
 
1015
        config.set_user_option(name, url, warn_masked=True)
1151
1016
 
1152
1017
    def _get_config_location(self, name, config=None):
1153
1018
        if config is None:
1154
 
            config = self.get_config_stack()
1155
 
        location = config.get(name)
 
1019
            config = self.get_config()
 
1020
        location = config.get_user_option(name)
1156
1021
        if location == '':
1157
1022
            location = None
1158
1023
        return location
1159
1024
 
1160
1025
    def get_child_submit_format(self):
1161
1026
        """Return the preferred format of submissions to this branch."""
1162
 
        return self.get_config_stack().get('child_submit_format')
 
1027
        return self.get_config().get_user_option("child_submit_format")
1163
1028
 
1164
1029
    def get_submit_branch(self):
1165
1030
        """Return the submit location of the branch.
1168
1033
        pattern is that the user can override it by specifying a
1169
1034
        location.
1170
1035
        """
1171
 
        return self.get_config_stack().get('submit_branch')
 
1036
        return self.get_config().get_user_option('submit_branch')
1172
1037
 
1173
1038
    def set_submit_branch(self, location):
1174
1039
        """Return the submit location of the branch.
1177
1042
        pattern is that the user can override it by specifying a
1178
1043
        location.
1179
1044
        """
1180
 
        self.get_config_stack().set('submit_branch', location)
 
1045
        self.get_config().set_user_option('submit_branch', location,
 
1046
            warn_masked=True)
1181
1047
 
1182
1048
    def get_public_branch(self):
1183
1049
        """Return the public location of the branch.
1196
1062
        self._set_config_location('public_branch', location)
1197
1063
 
1198
1064
    def get_push_location(self):
1199
 
        """Return None or the location to push this branch to."""
1200
 
        return self.get_config_stack().get('push_location')
 
1065
        """Return the None or the location to push this branch to."""
 
1066
        push_loc = self.get_config().get_user_option('push_location')
 
1067
        return push_loc
1201
1068
 
1202
1069
    def set_push_location(self, location):
1203
1070
        """Set a new push location for this branch."""
1223
1090
        params = ChangeBranchTipParams(
1224
1091
            self, old_revno, new_revno, old_revid, new_revid)
1225
1092
        for hook in hooks:
1226
 
            hook(params)
 
1093
            try:
 
1094
                hook(params)
 
1095
            except errors.TipChangeRejected:
 
1096
                raise
 
1097
            except Exception:
 
1098
                exc_info = sys.exc_info()
 
1099
                hook_name = Branch.hooks.get_hook_name(hook)
 
1100
                raise errors.HookFailed(
 
1101
                    'pre_change_branch_tip', hook_name, exc_info)
1227
1102
 
1228
1103
    @needs_write_lock
1229
1104
    def update(self):
1270
1145
        return result
1271
1146
 
1272
1147
    @needs_read_lock
1273
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1274
 
            repository=None):
 
1148
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1275
1149
        """Create a new line of development from the branch, into to_bzrdir.
1276
1150
 
1277
1151
        to_bzrdir controls the branch format.
1282
1156
        if (repository_policy is not None and
1283
1157
            repository_policy.requires_stacking()):
1284
1158
            to_bzrdir._format.require_stacking(_skip_repo=True)
1285
 
        result = to_bzrdir.create_branch(repository=repository)
 
1159
        result = to_bzrdir.create_branch()
1286
1160
        result.lock_write()
1287
1161
        try:
1288
1162
            if repository_policy is not None:
1289
1163
                repository_policy.configure_branch(result)
1290
1164
            self.copy_content_into(result, revision_id=revision_id)
1291
 
            master_url = self.get_bound_location()
1292
 
            if master_url is None:
1293
 
                result.set_parent(self.bzrdir.root_transport.base)
1294
 
            else:
1295
 
                result.set_parent(master_url)
 
1165
            result.set_parent(self.bzrdir.root_transport.base)
1296
1166
        finally:
1297
1167
            result.unlock()
1298
1168
        return result
1322
1192
                revno = 1
1323
1193
        destination.set_last_revision_info(revno, revision_id)
1324
1194
 
 
1195
    @needs_read_lock
1325
1196
    def copy_content_into(self, destination, revision_id=None):
1326
1197
        """Copy the content of self into destination.
1327
1198
 
1328
1199
        revision_id: if not None, the revision history in the new branch will
1329
1200
                     be truncated to end with revision_id.
1330
1201
        """
1331
 
        return InterBranch.get(self, destination).copy_content_into(
1332
 
            revision_id=revision_id)
 
1202
        self.update_references(destination)
 
1203
        self._synchronize_history(destination, revision_id)
 
1204
        try:
 
1205
            parent = self.get_parent()
 
1206
        except errors.InaccessibleParent, e:
 
1207
            mutter('parent was not accessible to copy: %s', e)
 
1208
        else:
 
1209
            if parent:
 
1210
                destination.set_parent(parent)
 
1211
        if self._push_should_merge_tags():
 
1212
            self.tags.merge_to(destination.tags)
1333
1213
 
1334
1214
    def update_references(self, target):
1335
1215
        if not getattr(self._format, 'supports_reference_locations', False):
1372
1252
        # TODO: We should probably also check that self.revision_history
1373
1253
        # matches the repository for older branch formats.
1374
1254
        # If looking for the code that cross-checks repository parents against
1375
 
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1255
        # the iter_reverse_revision_history output, that is now a repository
1376
1256
        # specific check.
1377
1257
        return result
1378
1258
 
1379
 
    def _get_checkout_format(self, lightweight=False):
 
1259
    def _get_checkout_format(self):
1380
1260
        """Return the most suitable metadir for a checkout of this branch.
1381
1261
        Weaves are used if this branch's repository uses weaves.
1382
1262
        """
1383
 
        format = self.repository.bzrdir.checkout_metadir()
1384
 
        format.set_branch_format(self._format)
 
1263
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1264
            from bzrlib.repofmt import weaverepo
 
1265
            format = bzrdir.BzrDirMetaFormat1()
 
1266
            format.repository_format = weaverepo.RepositoryFormat7()
 
1267
        else:
 
1268
            format = self.repository.bzrdir.checkout_metadir()
 
1269
            format.set_branch_format(self._format)
1385
1270
        return format
1386
1271
 
1387
1272
    def create_clone_on_transport(self, to_transport, revision_id=None,
1388
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1389
 
        no_tree=None):
 
1273
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1390
1274
        """Create a clone of this branch and its bzrdir.
1391
1275
 
1392
1276
        :param to_transport: The transport to clone onto.
1399
1283
        """
1400
1284
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1401
1285
        # clone call. Or something. 20090224 RBC/spiv.
1402
 
        # XXX: Should this perhaps clone colocated branches as well, 
1403
 
        # rather than just the default branch? 20100319 JRV
1404
1286
        if revision_id is None:
1405
1287
            revision_id = self.last_revision()
1406
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1407
 
            revision_id=revision_id, stacked_on=stacked_on,
1408
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1409
 
            no_tree=no_tree)
 
1288
        try:
 
1289
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1290
                revision_id=revision_id, stacked_on=stacked_on,
 
1291
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1292
        except errors.FileExists:
 
1293
            if not use_existing_dir:
 
1294
                raise
 
1295
        except errors.NoSuchFile:
 
1296
            if not create_prefix:
 
1297
                raise
1410
1298
        return dir_to.open_branch()
1411
1299
 
1412
1300
    def create_checkout(self, to_location, revision_id=None,
1417
1305
        :param to_location: The url to produce the checkout at
1418
1306
        :param revision_id: The revision to check out
1419
1307
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1420
 
            produce a bound branch (heavyweight checkout)
 
1308
        produce a bound branch (heavyweight checkout)
1421
1309
        :param accelerator_tree: A tree which can be used for retrieving file
1422
1310
            contents more quickly than the revision tree, i.e. a workingtree.
1423
1311
            The revision tree will be used for cases where accelerator_tree's
1428
1316
        """
1429
1317
        t = transport.get_transport(to_location)
1430
1318
        t.ensure_base()
1431
 
        format = self._get_checkout_format(lightweight=lightweight)
1432
 
        try:
 
1319
        if lightweight:
 
1320
            format = self._get_checkout_format()
1433
1321
            checkout = format.initialize_on_transport(t)
1434
 
        except errors.AlreadyControlDirError:
1435
 
            # It's fine if the control directory already exists,
1436
 
            # as long as there is no existing branch and working tree.
1437
 
            checkout = controldir.ControlDir.open_from_transport(t)
1438
 
            try:
1439
 
                checkout.open_branch()
1440
 
            except errors.NotBranchError:
1441
 
                pass
1442
 
            else:
1443
 
                raise errors.AlreadyControlDirError(t.base)
1444
 
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
1445
 
                # When checking out to the same control directory,
1446
 
                # always create a lightweight checkout
1447
 
                lightweight = True
1448
 
 
1449
 
        if lightweight:
1450
 
            from_branch = checkout.set_branch_reference(target_branch=self)
 
1322
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1451
1323
        else:
1452
 
            policy = checkout.determine_repository_policy()
1453
 
            repo = policy.acquire_repository()[0]
1454
 
            checkout_branch = checkout.create_branch()
 
1324
            format = self._get_checkout_format()
 
1325
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1326
                to_location, force_new_tree=False, format=format)
 
1327
            checkout = checkout_branch.bzrdir
1455
1328
            checkout_branch.bind(self)
1456
1329
            # pull up to the specified revision_id to set the initial
1457
1330
            # branch tip correctly, and seed it with history.
1458
1331
            checkout_branch.pull(self, stop_revision=revision_id)
1459
 
            from_branch = None
 
1332
            from_branch=None
1460
1333
        tree = checkout.create_workingtree(revision_id,
1461
1334
                                           from_branch=from_branch,
1462
1335
                                           accelerator_tree=accelerator_tree,
1483
1356
 
1484
1357
    def reference_parent(self, file_id, path, possible_transports=None):
1485
1358
        """Return the parent branch for a tree-reference file_id
1486
 
 
1487
1359
        :param file_id: The file_id of the tree reference
1488
1360
        :param path: The path of the file_id in the tree
1489
1361
        :return: A branch associated with the file_id
1495
1367
    def supports_tags(self):
1496
1368
        return self._format.supports_tags()
1497
1369
 
1498
 
    def automatic_tag_name(self, revision_id):
1499
 
        """Try to automatically find the tag name for a revision.
1500
 
 
1501
 
        :param revision_id: Revision id of the revision.
1502
 
        :return: A tag name or None if no tag name could be determined.
1503
 
        """
1504
 
        for hook in Branch.hooks['automatic_tag_name']:
1505
 
            ret = hook(self, revision_id)
1506
 
            if ret is not None:
1507
 
                return ret
1508
 
        return None
1509
 
 
1510
1370
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1511
1371
                                         other_branch):
1512
1372
        """Ensure that revision_b is a descendant of revision_a.
1542
1402
        else:
1543
1403
            raise AssertionError("invalid heads: %r" % (heads,))
1544
1404
 
1545
 
    def heads_to_fetch(self):
1546
 
        """Return the heads that must and that should be fetched to copy this
1547
 
        branch into another repo.
1548
 
 
1549
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1550
 
            set of heads that must be fetched.  if_present_fetch is a set of
1551
 
            heads that must be fetched if present, but no error is necessary if
1552
 
            they are not present.
1553
 
        """
1554
 
        # For bzr native formats must_fetch is just the tip, and
1555
 
        # if_present_fetch are the tags.
1556
 
        must_fetch = set([self.last_revision()])
1557
 
        if_present_fetch = set()
1558
 
        if self.get_config_stack().get('branch.fetch_tags'):
1559
 
            try:
1560
 
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1561
 
            except errors.TagsNotSupported:
1562
 
                pass
1563
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1564
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1565
 
        return must_fetch, if_present_fetch
1566
 
 
1567
 
 
1568
 
class BranchFormat(controldir.ControlComponentFormat):
 
1405
 
 
1406
class BranchFormat(object):
1569
1407
    """An encapsulation of the initialization and open routines for a format.
1570
1408
 
1571
1409
    Formats provide three things:
1572
1410
     * An initialization routine,
1573
 
     * a format description
 
1411
     * a format string,
1574
1412
     * an open routine.
1575
1413
 
1576
1414
    Formats are placed in an dict by their format string for reference
1577
 
    during branch opening. It's not required that these be instances, they
 
1415
    during branch opening. Its not required that these be instances, they
1578
1416
    can be classes themselves with class methods - it simply depends on
1579
1417
    whether state is needed for a given format or not.
1580
1418
 
1583
1421
    object will be created every time regardless.
1584
1422
    """
1585
1423
 
 
1424
    _default_format = None
 
1425
    """The default format used for new branches."""
 
1426
 
 
1427
    _formats = {}
 
1428
    """The known formats."""
 
1429
 
 
1430
    can_set_append_revisions_only = True
 
1431
 
1586
1432
    def __eq__(self, other):
1587
1433
        return self.__class__ is other.__class__
1588
1434
 
1589
1435
    def __ne__(self, other):
1590
1436
        return not (self == other)
1591
1437
 
1592
 
    def get_reference(self, controldir, name=None):
1593
 
        """Get the target reference of the branch in controldir.
 
1438
    @classmethod
 
1439
    def find_format(klass, a_bzrdir):
 
1440
        """Return the format for the branch object in a_bzrdir."""
 
1441
        try:
 
1442
            transport = a_bzrdir.get_branch_transport(None)
 
1443
            format_string = transport.get("format").read()
 
1444
            return klass._formats[format_string]
 
1445
        except errors.NoSuchFile:
 
1446
            raise errors.NotBranchError(path=transport.base)
 
1447
        except KeyError:
 
1448
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1449
 
 
1450
    @classmethod
 
1451
    def get_default_format(klass):
 
1452
        """Return the current default format."""
 
1453
        return klass._default_format
 
1454
 
 
1455
    def get_reference(self, a_bzrdir):
 
1456
        """Get the target reference of the branch in a_bzrdir.
1594
1457
 
1595
1458
        format probing must have been completed before calling
1596
1459
        this method - it is assumed that the format of the branch
1597
 
        in controldir is correct.
 
1460
        in a_bzrdir is correct.
1598
1461
 
1599
 
        :param controldir: The controldir to get the branch data from.
1600
 
        :param name: Name of the colocated branch to fetch
 
1462
        :param a_bzrdir: The bzrdir to get the branch data from.
1601
1463
        :return: None if the branch is not a reference branch.
1602
1464
        """
1603
1465
        return None
1604
1466
 
1605
1467
    @classmethod
1606
 
    def set_reference(self, controldir, name, to_branch):
1607
 
        """Set the target reference of the branch in controldir.
 
1468
    def set_reference(self, a_bzrdir, to_branch):
 
1469
        """Set the target reference of the branch in a_bzrdir.
1608
1470
 
1609
1471
        format probing must have been completed before calling
1610
1472
        this method - it is assumed that the format of the branch
1611
 
        in controldir is correct.
 
1473
        in a_bzrdir is correct.
1612
1474
 
1613
 
        :param controldir: The controldir to set the branch reference for.
1614
 
        :param name: Name of colocated branch to set, None for default
 
1475
        :param a_bzrdir: The bzrdir to set the branch reference for.
1615
1476
        :param to_branch: branch that the checkout is to reference
1616
1477
        """
1617
1478
        raise NotImplementedError(self.set_reference)
1618
1479
 
 
1480
    def get_format_string(self):
 
1481
        """Return the ASCII format string that identifies this format."""
 
1482
        raise NotImplementedError(self.get_format_string)
 
1483
 
1619
1484
    def get_format_description(self):
1620
1485
        """Return the short format description for this format."""
1621
1486
        raise NotImplementedError(self.get_format_description)
1622
1487
 
1623
 
    def _run_post_branch_init_hooks(self, controldir, name, branch):
1624
 
        hooks = Branch.hooks['post_branch_init']
1625
 
        if not hooks:
1626
 
            return
1627
 
        params = BranchInitHookParams(self, controldir, name, branch)
1628
 
        for hook in hooks:
1629
 
            hook(params)
1630
 
 
1631
 
    def initialize(self, controldir, name=None, repository=None,
1632
 
                   append_revisions_only=None):
1633
 
        """Create a branch of this format in controldir.
1634
 
 
1635
 
        :param name: Name of the colocated branch to create.
 
1488
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1489
                           set_format=True):
 
1490
        """Initialize a branch in a bzrdir, with specified files
 
1491
 
 
1492
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1493
        :param utf8_files: The files to create as a list of
 
1494
            (filename, content) tuples
 
1495
        :param set_format: If True, set the format with
 
1496
            self.get_format_string.  (BzrBranch4 has its format set
 
1497
            elsewhere)
 
1498
        :return: a branch in this format
1636
1499
        """
 
1500
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1501
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1502
        lock_map = {
 
1503
            'metadir': ('lock', lockdir.LockDir),
 
1504
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1505
        }
 
1506
        lock_name, lock_class = lock_map[lock_type]
 
1507
        control_files = lockable_files.LockableFiles(branch_transport,
 
1508
            lock_name, lock_class)
 
1509
        control_files.create_lock()
 
1510
        try:
 
1511
            control_files.lock_write()
 
1512
        except errors.LockContention:
 
1513
            if lock_type != 'branch4':
 
1514
                raise
 
1515
            lock_taken = False
 
1516
        else:
 
1517
            lock_taken = True
 
1518
        if set_format:
 
1519
            utf8_files += [('format', self.get_format_string())]
 
1520
        try:
 
1521
            for (filename, content) in utf8_files:
 
1522
                branch_transport.put_bytes(
 
1523
                    filename, content,
 
1524
                    mode=a_bzrdir._get_file_mode())
 
1525
        finally:
 
1526
            if lock_taken:
 
1527
                control_files.unlock()
 
1528
        return self.open(a_bzrdir, _found=True)
 
1529
 
 
1530
    def initialize(self, a_bzrdir):
 
1531
        """Create a branch of this format in a_bzrdir."""
1637
1532
        raise NotImplementedError(self.initialize)
1638
1533
 
1639
1534
    def is_supported(self):
1657
1552
        Note that it is normal for branch to be a RemoteBranch when using tags
1658
1553
        on a RemoteBranch.
1659
1554
        """
1660
 
        return _mod_tag.DisabledTags(branch)
 
1555
        return DisabledTags(branch)
1661
1556
 
1662
1557
    def network_name(self):
1663
1558
        """A simple byte string uniquely identifying this format for RPC calls.
1669
1564
        """
1670
1565
        raise NotImplementedError(self.network_name)
1671
1566
 
1672
 
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1673
 
            found_repository=None, possible_transports=None):
1674
 
        """Return the branch object for controldir.
 
1567
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1568
        """Return the branch object for a_bzrdir
1675
1569
 
1676
 
        :param controldir: A ControlDir that contains a branch.
1677
 
        :param name: Name of colocated branch to open
 
1570
        :param a_bzrdir: A BzrDir that contains a branch.
1678
1571
        :param _found: a private parameter, do not use it. It is used to
1679
1572
            indicate if format probing has already be done.
1680
1573
        :param ignore_fallbacks: when set, no fallback branches will be opened
1682
1575
        """
1683
1576
        raise NotImplementedError(self.open)
1684
1577
 
 
1578
    @classmethod
 
1579
    def register_format(klass, format):
 
1580
        """Register a metadir format."""
 
1581
        klass._formats[format.get_format_string()] = format
 
1582
        # Metadir formats have a network name of their format string, and get
 
1583
        # registered as class factories.
 
1584
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1585
 
 
1586
    @classmethod
 
1587
    def set_default_format(klass, format):
 
1588
        klass._default_format = format
 
1589
 
1685
1590
    def supports_set_append_revisions_only(self):
1686
1591
        """True if this format supports set_append_revisions_only."""
1687
1592
        return False
1690
1595
        """True if this format records a stacked-on branch."""
1691
1596
        return False
1692
1597
 
1693
 
    def supports_leaving_lock(self):
1694
 
        """True if this format supports leaving locks in place."""
1695
 
        return False # by default
1696
 
 
1697
1598
    @classmethod
1698
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1699
1599
    def unregister_format(klass, format):
1700
 
        format_registry.remove(format)
 
1600
        del klass._formats[format.get_format_string()]
1701
1601
 
1702
1602
    def __str__(self):
1703
1603
        return self.get_format_description().rstrip()
1706
1606
        """True if this format supports tags stored in the branch"""
1707
1607
        return False  # by default
1708
1608
 
1709
 
    def tags_are_versioned(self):
1710
 
        """Whether the tag container for this branch versions tags."""
1711
 
        return False
1712
 
 
1713
 
    def supports_tags_referencing_ghosts(self):
1714
 
        """True if tags can reference ghost revisions."""
1715
 
        return True
1716
 
 
1717
 
 
1718
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1719
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1720
 
    
1721
 
    While none of the built in BranchFormats are lazy registered yet,
1722
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1723
 
    use it, and the bzr-loom plugin uses it as well (see
1724
 
    bzrlib.plugins.loom.formats).
1725
 
    """
1726
 
 
1727
 
    def __init__(self, format_string, module_name, member_name):
1728
 
        """Create a MetaDirBranchFormatFactory.
1729
 
 
1730
 
        :param format_string: The format string the format has.
1731
 
        :param module_name: Module to load the format class from.
1732
 
        :param member_name: Attribute name within the module for the format class.
1733
 
        """
1734
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1735
 
        self._format_string = format_string
1736
 
 
1737
 
    def get_format_string(self):
1738
 
        """See BranchFormat.get_format_string."""
1739
 
        return self._format_string
1740
 
 
1741
 
    def __call__(self):
1742
 
        """Used for network_format_registry support."""
1743
 
        return self.get_obj()()
1744
 
 
1745
1609
 
1746
1610
class BranchHooks(Hooks):
1747
1611
    """A dictionary mapping hook name to a list of callables for branch hooks.
1748
1612
 
1749
 
    e.g. ['post_push'] Is the list of items to be called when the
1750
 
    push function is invoked.
 
1613
    e.g. ['set_rh'] Is the list of items to be called when the
 
1614
    set_revision_history function is invoked.
1751
1615
    """
1752
1616
 
1753
1617
    def __init__(self):
1756
1620
        These are all empty initially, because by default nothing should get
1757
1621
        notified.
1758
1622
        """
1759
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1760
 
        self.add_hook('open',
 
1623
        Hooks.__init__(self)
 
1624
        self.create_hook(HookPoint('set_rh',
 
1625
            "Invoked whenever the revision history has been set via "
 
1626
            "set_revision_history. The api signature is (branch, "
 
1627
            "revision_history), and the branch will be write-locked. "
 
1628
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1629
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1630
        self.create_hook(HookPoint('open',
1761
1631
            "Called with the Branch object that has been opened after a "
1762
 
            "branch is opened.", (1, 8))
1763
 
        self.add_hook('post_push',
 
1632
            "branch is opened.", (1, 8), None))
 
1633
        self.create_hook(HookPoint('post_push',
1764
1634
            "Called after a push operation completes. post_push is called "
1765
1635
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1766
 
            "bzr client.", (0, 15))
1767
 
        self.add_hook('post_pull',
 
1636
            "bzr client.", (0, 15), None))
 
1637
        self.create_hook(HookPoint('post_pull',
1768
1638
            "Called after a pull operation completes. post_pull is called "
1769
1639
            "with a bzrlib.branch.PullResult object and only runs in the "
1770
 
            "bzr client.", (0, 15))
1771
 
        self.add_hook('pre_commit',
1772
 
            "Called after a commit is calculated but before it is "
 
1640
            "bzr client.", (0, 15), None))
 
1641
        self.create_hook(HookPoint('pre_commit',
 
1642
            "Called after a commit is calculated but before it is is "
1773
1643
            "completed. pre_commit is called with (local, master, old_revno, "
1774
1644
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1775
1645
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1777
1647
            "basis revision. hooks MUST NOT modify this delta. "
1778
1648
            " future_tree is an in-memory tree obtained from "
1779
1649
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1780
 
            "tree.", (0,91))
1781
 
        self.add_hook('post_commit',
 
1650
            "tree.", (0,91), None))
 
1651
        self.create_hook(HookPoint('post_commit',
1782
1652
            "Called in the bzr client after a commit has completed. "
1783
1653
            "post_commit is called with (local, master, old_revno, old_revid, "
1784
1654
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1785
 
            "commit to a branch.", (0, 15))
1786
 
        self.add_hook('post_uncommit',
 
1655
            "commit to a branch.", (0, 15), None))
 
1656
        self.create_hook(HookPoint('post_uncommit',
1787
1657
            "Called in the bzr client after an uncommit completes. "
1788
1658
            "post_uncommit is called with (local, master, old_revno, "
1789
1659
            "old_revid, new_revno, new_revid) where local is the local branch "
1790
1660
            "or None, master is the target branch, and an empty branch "
1791
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1792
 
        self.add_hook('pre_change_branch_tip',
 
1661
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1662
        self.create_hook(HookPoint('pre_change_branch_tip',
1793
1663
            "Called in bzr client and server before a change to the tip of a "
1794
1664
            "branch is made. pre_change_branch_tip is called with a "
1795
1665
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1796
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1797
 
        self.add_hook('post_change_branch_tip',
 
1666
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1667
        self.create_hook(HookPoint('post_change_branch_tip',
1798
1668
            "Called in bzr client and server after a change to the tip of a "
1799
1669
            "branch is made. post_change_branch_tip is called with a "
1800
1670
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1801
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1802
 
        self.add_hook('transform_fallback_location',
 
1671
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1672
        self.create_hook(HookPoint('transform_fallback_location',
1803
1673
            "Called when a stacked branch is activating its fallback "
1804
1674
            "locations. transform_fallback_location is called with (branch, "
1805
1675
            "url), and should return a new url. Returning the same url "
1810
1680
            "fallback locations have not been activated. When there are "
1811
1681
            "multiple hooks installed for transform_fallback_location, "
1812
1682
            "all are called with the url returned from the previous hook."
1813
 
            "The order is however undefined.", (1, 9))
1814
 
        self.add_hook('automatic_tag_name',
1815
 
            "Called to determine an automatic tag name for a revision. "
1816
 
            "automatic_tag_name is called with (branch, revision_id) and "
1817
 
            "should return a tag name or None if no tag name could be "
1818
 
            "determined. The first non-None tag name returned will be used.",
1819
 
            (2, 2))
1820
 
        self.add_hook('post_branch_init',
1821
 
            "Called after new branch initialization completes. "
1822
 
            "post_branch_init is called with a "
1823
 
            "bzrlib.branch.BranchInitHookParams. "
1824
 
            "Note that init, branch and checkout (both heavyweight and "
1825
 
            "lightweight) will all trigger this hook.", (2, 2))
1826
 
        self.add_hook('post_switch',
1827
 
            "Called after a checkout switches branch. "
1828
 
            "post_switch is called with a "
1829
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1830
 
 
 
1683
            "The order is however undefined.", (1, 9), None))
1831
1684
 
1832
1685
 
1833
1686
# install the default hooks into the Branch class.
1835
1688
 
1836
1689
 
1837
1690
class ChangeBranchTipParams(object):
1838
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1691
    """Object holding parameters passed to *_change_branch_tip hooks.
1839
1692
 
1840
1693
    There are 5 fields that hooks may wish to access:
1841
1694
 
1872
1725
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1873
1726
 
1874
1727
 
1875
 
class BranchInitHookParams(object):
1876
 
    """Object holding parameters passed to `*_branch_init` hooks.
1877
 
 
1878
 
    There are 4 fields that hooks may wish to access:
1879
 
 
1880
 
    :ivar format: the branch format
1881
 
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
1882
 
    :ivar name: name of colocated branch, if any (or None)
1883
 
    :ivar branch: the branch created
1884
 
 
1885
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1886
 
    the checkout, hence they are different from the corresponding fields in
1887
 
    branch, which refer to the original branch.
1888
 
    """
1889
 
 
1890
 
    def __init__(self, format, controldir, name, branch):
1891
 
        """Create a group of BranchInitHook parameters.
1892
 
 
1893
 
        :param format: the branch format
1894
 
        :param controldir: the ControlDir where the branch will be/has been
1895
 
            initialized
1896
 
        :param name: name of colocated branch, if any (or None)
1897
 
        :param branch: the branch created
1898
 
 
1899
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1900
 
        to the checkout, hence they are different from the corresponding fields
1901
 
        in branch, which refer to the original branch.
1902
 
        """
1903
 
        self.format = format
1904
 
        self.bzrdir = controldir
1905
 
        self.name = name
1906
 
        self.branch = branch
1907
 
 
1908
 
    def __eq__(self, other):
1909
 
        return self.__dict__ == other.__dict__
1910
 
 
1911
 
    def __repr__(self):
1912
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1913
 
 
1914
 
 
1915
 
class SwitchHookParams(object):
1916
 
    """Object holding parameters passed to `*_switch` hooks.
1917
 
 
1918
 
    There are 4 fields that hooks may wish to access:
1919
 
 
1920
 
    :ivar control_dir: ControlDir of the checkout to change
1921
 
    :ivar to_branch: branch that the checkout is to reference
1922
 
    :ivar force: skip the check for local commits in a heavy checkout
1923
 
    :ivar revision_id: revision ID to switch to (or None)
1924
 
    """
1925
 
 
1926
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1927
 
        """Create a group of SwitchHook parameters.
1928
 
 
1929
 
        :param control_dir: ControlDir of the checkout to change
1930
 
        :param to_branch: branch that the checkout is to reference
1931
 
        :param force: skip the check for local commits in a heavy checkout
1932
 
        :param revision_id: revision ID to switch to (or None)
1933
 
        """
1934
 
        self.control_dir = control_dir
1935
 
        self.to_branch = to_branch
1936
 
        self.force = force
1937
 
        self.revision_id = revision_id
1938
 
 
1939
 
    def __eq__(self, other):
1940
 
        return self.__dict__ == other.__dict__
1941
 
 
1942
 
    def __repr__(self):
1943
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1944
 
            self.control_dir, self.to_branch,
1945
 
            self.revision_id)
1946
 
 
1947
 
 
1948
 
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
1949
 
    """Base class for branch formats that live in meta directories.
1950
 
    """
 
1728
class BzrBranchFormat4(BranchFormat):
 
1729
    """Bzr branch format 4.
 
1730
 
 
1731
    This format has:
 
1732
     - a revision-history file.
 
1733
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1734
    """
 
1735
 
 
1736
    def get_format_description(self):
 
1737
        """See BranchFormat.get_format_description()."""
 
1738
        return "Branch format 4"
 
1739
 
 
1740
    def initialize(self, a_bzrdir):
 
1741
        """Create a branch of this format in a_bzrdir."""
 
1742
        utf8_files = [('revision-history', ''),
 
1743
                      ('branch-name', ''),
 
1744
                      ]
 
1745
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1746
                                       lock_type='branch4', set_format=False)
1951
1747
 
1952
1748
    def __init__(self):
1953
 
        BranchFormat.__init__(self)
1954
 
        bzrdir.BzrFormat.__init__(self)
1955
 
 
1956
 
    @classmethod
1957
 
    def find_format(klass, controldir, name=None):
1958
 
        """Return the format for the branch object in controldir."""
1959
 
        try:
1960
 
            transport = controldir.get_branch_transport(None, name=name)
1961
 
        except errors.NoSuchFile:
1962
 
            raise errors.NotBranchError(path=name, bzrdir=controldir)
1963
 
        try:
1964
 
            format_string = transport.get_bytes("format")
1965
 
        except errors.NoSuchFile:
1966
 
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1967
 
        return klass._find_format(format_registry, 'branch', format_string)
 
1749
        super(BzrBranchFormat4, self).__init__()
 
1750
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1751
 
 
1752
    def network_name(self):
 
1753
        """The network name for this format is the control dirs disk label."""
 
1754
        return self._matchingbzrdir.get_format_string()
 
1755
 
 
1756
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1757
        """See BranchFormat.open()."""
 
1758
        if not _found:
 
1759
            # we are being called directly and must probe.
 
1760
            raise NotImplementedError
 
1761
        return BzrBranch(_format=self,
 
1762
                         _control_files=a_bzrdir._control_files,
 
1763
                         a_bzrdir=a_bzrdir,
 
1764
                         _repository=a_bzrdir.open_repository())
 
1765
 
 
1766
    def __str__(self):
 
1767
        return "Bazaar-NG branch format 4"
 
1768
 
 
1769
 
 
1770
class BranchFormatMetadir(BranchFormat):
 
1771
    """Common logic for meta-dir based branch formats."""
1968
1772
 
1969
1773
    def _branch_class(self):
1970
1774
        """What class to instantiate on open calls."""
1971
1775
        raise NotImplementedError(self._branch_class)
1972
1776
 
1973
 
    def _get_initial_config(self, append_revisions_only=None):
1974
 
        if append_revisions_only:
1975
 
            return "append_revisions_only = True\n"
1976
 
        else:
1977
 
            # Avoid writing anything if append_revisions_only is disabled,
1978
 
            # as that is the default.
1979
 
            return ""
1980
 
 
1981
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1982
 
                           repository=None):
1983
 
        """Initialize a branch in a control dir, with specified files
1984
 
 
1985
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1986
 
        :param utf8_files: The files to create as a list of
1987
 
            (filename, content) tuples
1988
 
        :param name: Name of colocated branch to create, if any
1989
 
        :return: a branch in this format
 
1777
    def network_name(self):
 
1778
        """A simple byte string uniquely identifying this format for RPC calls.
 
1779
 
 
1780
        Metadir branch formats use their format string.
1990
1781
        """
1991
 
        if name is None:
1992
 
            name = a_bzrdir._get_selected_branch()
1993
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1994
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1995
 
        control_files = lockable_files.LockableFiles(branch_transport,
1996
 
            'lock', lockdir.LockDir)
1997
 
        control_files.create_lock()
1998
 
        control_files.lock_write()
1999
 
        try:
2000
 
            utf8_files += [('format', self.as_string())]
2001
 
            for (filename, content) in utf8_files:
2002
 
                branch_transport.put_bytes(
2003
 
                    filename, content,
2004
 
                    mode=a_bzrdir._get_file_mode())
2005
 
        finally:
2006
 
            control_files.unlock()
2007
 
        branch = self.open(a_bzrdir, name, _found=True,
2008
 
                found_repository=repository)
2009
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2010
 
        return branch
 
1782
        return self.get_format_string()
2011
1783
 
2012
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2013
 
            found_repository=None, possible_transports=None):
 
1784
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2014
1785
        """See BranchFormat.open()."""
2015
 
        if name is None:
2016
 
            name = a_bzrdir._get_selected_branch()
2017
1786
        if not _found:
2018
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
1787
            format = BranchFormat.find_format(a_bzrdir)
2019
1788
            if format.__class__ != self.__class__:
2020
1789
                raise AssertionError("wrong format %r found for %r" %
2021
1790
                    (format, self))
2022
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2023
1791
        try:
 
1792
            transport = a_bzrdir.get_branch_transport(None)
2024
1793
            control_files = lockable_files.LockableFiles(transport, 'lock',
2025
1794
                                                         lockdir.LockDir)
2026
 
            if found_repository is None:
2027
 
                found_repository = a_bzrdir.find_repository()
2028
1795
            return self._branch_class()(_format=self,
2029
1796
                              _control_files=control_files,
2030
 
                              name=name,
2031
1797
                              a_bzrdir=a_bzrdir,
2032
 
                              _repository=found_repository,
2033
 
                              ignore_fallbacks=ignore_fallbacks,
2034
 
                              possible_transports=possible_transports)
 
1798
                              _repository=a_bzrdir.find_repository(),
 
1799
                              ignore_fallbacks=ignore_fallbacks)
2035
1800
        except errors.NoSuchFile:
2036
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1801
            raise errors.NotBranchError(path=transport.base)
2037
1802
 
2038
 
    @property
2039
 
    def _matchingbzrdir(self):
2040
 
        ret = bzrdir.BzrDirMetaFormat1()
2041
 
        ret.set_branch_format(self)
2042
 
        return ret
 
1803
    def __init__(self):
 
1804
        super(BranchFormatMetadir, self).__init__()
 
1805
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1806
        self._matchingbzrdir.set_branch_format(self)
2043
1807
 
2044
1808
    def supports_tags(self):
2045
1809
        return True
2046
1810
 
2047
 
    def supports_leaving_lock(self):
2048
 
        return True
2049
 
 
2050
 
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
2051
 
            basedir=None):
2052
 
        BranchFormat.check_support_status(self,
2053
 
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
2054
 
            basedir=basedir)
2055
 
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
2056
 
            recommend_upgrade=recommend_upgrade, basedir=basedir)
2057
 
 
2058
1811
 
2059
1812
class BzrBranchFormat5(BranchFormatMetadir):
2060
1813
    """Bzr branch format 5.
2072
1825
    def _branch_class(self):
2073
1826
        return BzrBranch5
2074
1827
 
2075
 
    @classmethod
2076
 
    def get_format_string(cls):
 
1828
    def get_format_string(self):
2077
1829
        """See BranchFormat.get_format_string()."""
2078
1830
        return "Bazaar-NG branch format 5\n"
2079
1831
 
2081
1833
        """See BranchFormat.get_format_description()."""
2082
1834
        return "Branch format 5"
2083
1835
 
2084
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2085
 
                   append_revisions_only=None):
 
1836
    def initialize(self, a_bzrdir):
2086
1837
        """Create a branch of this format in a_bzrdir."""
2087
 
        if append_revisions_only:
2088
 
            raise errors.UpgradeRequired(a_bzrdir.user_url)
2089
1838
        utf8_files = [('revision-history', ''),
2090
1839
                      ('branch-name', ''),
2091
1840
                      ]
2092
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1841
        return self._initialize_helper(a_bzrdir, utf8_files)
2093
1842
 
2094
1843
    def supports_tags(self):
2095
1844
        return False
2109
1858
    def _branch_class(self):
2110
1859
        return BzrBranch6
2111
1860
 
2112
 
    @classmethod
2113
 
    def get_format_string(cls):
 
1861
    def get_format_string(self):
2114
1862
        """See BranchFormat.get_format_string()."""
2115
1863
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2116
1864
 
2118
1866
        """See BranchFormat.get_format_description()."""
2119
1867
        return "Branch format 6"
2120
1868
 
2121
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2122
 
                   append_revisions_only=None):
 
1869
    def initialize(self, a_bzrdir):
2123
1870
        """Create a branch of this format in a_bzrdir."""
2124
1871
        utf8_files = [('last-revision', '0 null:\n'),
2125
 
                      ('branch.conf',
2126
 
                          self._get_initial_config(append_revisions_only)),
 
1872
                      ('branch.conf', ''),
2127
1873
                      ('tags', ''),
2128
1874
                      ]
2129
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1875
        return self._initialize_helper(a_bzrdir, utf8_files)
2130
1876
 
2131
1877
    def make_tags(self, branch):
2132
1878
        """See bzrlib.branch.BranchFormat.make_tags()."""
2133
 
        return _mod_tag.BasicTags(branch)
 
1879
        return BasicTags(branch)
2134
1880
 
2135
1881
    def supports_set_append_revisions_only(self):
2136
1882
        return True
2142
1888
    def _branch_class(self):
2143
1889
        return BzrBranch8
2144
1890
 
2145
 
    @classmethod
2146
 
    def get_format_string(cls):
 
1891
    def get_format_string(self):
2147
1892
        """See BranchFormat.get_format_string()."""
2148
1893
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2149
1894
 
2151
1896
        """See BranchFormat.get_format_description()."""
2152
1897
        return "Branch format 8"
2153
1898
 
2154
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2155
 
                   append_revisions_only=None):
 
1899
    def initialize(self, a_bzrdir):
2156
1900
        """Create a branch of this format in a_bzrdir."""
2157
1901
        utf8_files = [('last-revision', '0 null:\n'),
2158
 
                      ('branch.conf',
2159
 
                          self._get_initial_config(append_revisions_only)),
 
1902
                      ('branch.conf', ''),
2160
1903
                      ('tags', ''),
2161
1904
                      ('references', '')
2162
1905
                      ]
2163
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1906
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1907
 
 
1908
    def __init__(self):
 
1909
        super(BzrBranchFormat8, self).__init__()
 
1910
        self._matchingbzrdir.repository_format = \
 
1911
            RepositoryFormatKnitPack5RichRoot()
2164
1912
 
2165
1913
    def make_tags(self, branch):
2166
1914
        """See bzrlib.branch.BranchFormat.make_tags()."""
2167
 
        return _mod_tag.BasicTags(branch)
 
1915
        return BasicTags(branch)
2168
1916
 
2169
1917
    def supports_set_append_revisions_only(self):
2170
1918
        return True
2175
1923
    supports_reference_locations = True
2176
1924
 
2177
1925
 
2178
 
class BzrBranchFormat7(BranchFormatMetadir):
 
1926
class BzrBranchFormat7(BzrBranchFormat8):
2179
1927
    """Branch format with last-revision, tags, and a stacked location pointer.
2180
1928
 
2181
1929
    The stacked location pointer is passed down to the repository and requires
2184
1932
    This format was introduced in bzr 1.6.
2185
1933
    """
2186
1934
 
2187
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2188
 
                   append_revisions_only=None):
 
1935
    def initialize(self, a_bzrdir):
2189
1936
        """Create a branch of this format in a_bzrdir."""
2190
1937
        utf8_files = [('last-revision', '0 null:\n'),
2191
 
                      ('branch.conf',
2192
 
                          self._get_initial_config(append_revisions_only)),
 
1938
                      ('branch.conf', ''),
2193
1939
                      ('tags', ''),
2194
1940
                      ]
2195
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1941
        return self._initialize_helper(a_bzrdir, utf8_files)
2196
1942
 
2197
1943
    def _branch_class(self):
2198
1944
        return BzrBranch7
2199
1945
 
2200
 
    @classmethod
2201
 
    def get_format_string(cls):
 
1946
    def get_format_string(self):
2202
1947
        """See BranchFormat.get_format_string()."""
2203
1948
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2204
1949
 
2209
1954
    def supports_set_append_revisions_only(self):
2210
1955
        return True
2211
1956
 
2212
 
    def supports_stacking(self):
2213
 
        return True
2214
 
 
2215
 
    def make_tags(self, branch):
2216
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2217
 
        return _mod_tag.BasicTags(branch)
2218
 
 
2219
1957
    supports_reference_locations = False
2220
1958
 
2221
1959
 
2222
 
class BranchReferenceFormat(BranchFormatMetadir):
 
1960
class BranchReferenceFormat(BranchFormat):
2223
1961
    """Bzr branch reference format.
2224
1962
 
2225
1963
    Branch references are used in implementing checkouts, they
2230
1968
     - a format string
2231
1969
    """
2232
1970
 
2233
 
    @classmethod
2234
 
    def get_format_string(cls):
 
1971
    def get_format_string(self):
2235
1972
        """See BranchFormat.get_format_string()."""
2236
1973
        return "Bazaar-NG Branch Reference Format 1\n"
2237
1974
 
2239
1976
        """See BranchFormat.get_format_description()."""
2240
1977
        return "Checkout reference format 1"
2241
1978
 
2242
 
    def get_reference(self, a_bzrdir, name=None):
 
1979
    def get_reference(self, a_bzrdir):
2243
1980
        """See BranchFormat.get_reference()."""
2244
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2245
 
        return transport.get_bytes('location')
 
1981
        transport = a_bzrdir.get_branch_transport(None)
 
1982
        return transport.get('location').read()
2246
1983
 
2247
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1984
    def set_reference(self, a_bzrdir, to_branch):
2248
1985
        """See BranchFormat.set_reference()."""
2249
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1986
        transport = a_bzrdir.get_branch_transport(None)
2250
1987
        location = transport.put_bytes('location', to_branch.base)
2251
1988
 
2252
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2253
 
            repository=None, append_revisions_only=None):
 
1989
    def initialize(self, a_bzrdir, target_branch=None):
2254
1990
        """Create a branch of this format in a_bzrdir."""
2255
1991
        if target_branch is None:
2256
1992
            # this format does not implement branch itself, thus the implicit
2257
1993
            # creation contract must see it as uninitializable
2258
1994
            raise errors.UninitializableFormat(self)
2259
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2260
 
        if a_bzrdir._format.fixed_components:
2261
 
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
2262
 
        if name is None:
2263
 
            name = a_bzrdir._get_selected_branch()
2264
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1995
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1996
        branch_transport = a_bzrdir.get_branch_transport(self)
2265
1997
        branch_transport.put_bytes('location',
2266
 
            target_branch.user_url)
2267
 
        branch_transport.put_bytes('format', self.as_string())
2268
 
        branch = self.open(a_bzrdir, name, _found=True,
 
1998
            target_branch.bzrdir.root_transport.base)
 
1999
        branch_transport.put_bytes('format', self.get_format_string())
 
2000
        return self.open(
 
2001
            a_bzrdir, _found=True,
2269
2002
            possible_transports=[target_branch.bzrdir.root_transport])
2270
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2271
 
        return branch
 
2003
 
 
2004
    def __init__(self):
 
2005
        super(BranchReferenceFormat, self).__init__()
 
2006
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2007
        self._matchingbzrdir.set_branch_format(self)
2272
2008
 
2273
2009
    def _make_reference_clone_function(format, a_branch):
2274
2010
        """Create a clone() routine for a branch dynamically."""
2275
2011
        def clone(to_bzrdir, revision_id=None,
2276
2012
            repository_policy=None):
2277
2013
            """See Branch.clone()."""
2278
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2014
            return format.initialize(to_bzrdir, a_branch)
2279
2015
            # cannot obey revision_id limits when cloning a reference ...
2280
2016
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2281
2017
            # emit some sort of warning/error to the caller ?!
2282
2018
        return clone
2283
2019
 
2284
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2285
 
             possible_transports=None, ignore_fallbacks=False,
2286
 
             found_repository=None):
 
2020
    def open(self, a_bzrdir, _found=False, location=None,
 
2021
             possible_transports=None, ignore_fallbacks=False):
2287
2022
        """Return the branch that the branch reference in a_bzrdir points at.
2288
2023
 
2289
2024
        :param a_bzrdir: A BzrDir that contains a branch.
2290
 
        :param name: Name of colocated branch to open, if any
2291
2025
        :param _found: a private parameter, do not use it. It is used to
2292
2026
            indicate if format probing has already be done.
2293
2027
        :param ignore_fallbacks: when set, no fallback branches will be opened
2297
2031
            a_bzrdir.
2298
2032
        :param possible_transports: An optional reusable transports list.
2299
2033
        """
2300
 
        if name is None:
2301
 
            name = a_bzrdir._get_selected_branch()
2302
2034
        if not _found:
2303
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2035
            format = BranchFormat.find_format(a_bzrdir)
2304
2036
            if format.__class__ != self.__class__:
2305
2037
                raise AssertionError("wrong format %r found for %r" %
2306
2038
                    (format, self))
2307
2039
        if location is None:
2308
 
            location = self.get_reference(a_bzrdir, name)
2309
 
        real_bzrdir = controldir.ControlDir.open(
 
2040
            location = self.get_reference(a_bzrdir)
 
2041
        real_bzrdir = bzrdir.BzrDir.open(
2310
2042
            location, possible_transports=possible_transports)
2311
 
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
2312
 
            possible_transports=possible_transports)
 
2043
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2313
2044
        # this changes the behaviour of result.clone to create a new reference
2314
2045
        # rather than a copy of the content of the branch.
2315
2046
        # I did not use a proxy object because that needs much more extensive
2322
2053
        return result
2323
2054
 
2324
2055
 
2325
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2326
 
    """Branch format registry."""
2327
 
 
2328
 
    def __init__(self, other_registry=None):
2329
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2330
 
        self._default_format = None
2331
 
 
2332
 
    def set_default(self, format):
2333
 
        self._default_format = format
2334
 
 
2335
 
    def get_default(self):
2336
 
        return self._default_format
2337
 
 
2338
 
 
2339
2056
network_format_registry = registry.FormatRegistry()
2340
2057
"""Registry of formats indexed by their network name.
2341
2058
 
2344
2061
BranchFormat.network_name() for more detail.
2345
2062
"""
2346
2063
 
2347
 
format_registry = BranchFormatRegistry(network_format_registry)
2348
 
 
2349
2064
 
2350
2065
# formats which have no format string are not discoverable
2351
2066
# and not independently creatable, so are not registered.
2353
2068
__format6 = BzrBranchFormat6()
2354
2069
__format7 = BzrBranchFormat7()
2355
2070
__format8 = BzrBranchFormat8()
2356
 
format_registry.register(__format5)
2357
 
format_registry.register(BranchReferenceFormat())
2358
 
format_registry.register(__format6)
2359
 
format_registry.register(__format7)
2360
 
format_registry.register(__format8)
2361
 
format_registry.set_default(__format7)
2362
 
 
2363
 
 
2364
 
class BranchWriteLockResult(LogicalLockResult):
2365
 
    """The result of write locking a branch.
2366
 
 
2367
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2368
 
        None.
2369
 
    :ivar unlock: A callable which will unlock the lock.
2370
 
    """
2371
 
 
2372
 
    def __init__(self, unlock, branch_token):
2373
 
        LogicalLockResult.__init__(self, unlock)
2374
 
        self.branch_token = branch_token
2375
 
 
2376
 
    def __repr__(self):
2377
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2378
 
            self.unlock)
 
2071
BranchFormat.register_format(__format5)
 
2072
BranchFormat.register_format(BranchReferenceFormat())
 
2073
BranchFormat.register_format(__format6)
 
2074
BranchFormat.register_format(__format7)
 
2075
BranchFormat.register_format(__format8)
 
2076
BranchFormat.set_default_format(__format7)
 
2077
_legacy_formats = [BzrBranchFormat4(),
 
2078
    ]
 
2079
network_format_registry.register(
 
2080
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2379
2081
 
2380
2082
 
2381
2083
class BzrBranch(Branch, _RelockDebugMixin):
2390
2092
    :ivar repository: Repository for this branch.
2391
2093
    :ivar base: The url of the base directory for this branch; the one
2392
2094
        containing the .bzr directory.
2393
 
    :ivar name: Optional colocated branch name as it exists in the control
2394
 
        directory.
2395
2095
    """
2396
2096
 
2397
2097
    def __init__(self, _format=None,
2398
 
                 _control_files=None, a_bzrdir=None, name=None,
2399
 
                 _repository=None, ignore_fallbacks=False,
2400
 
                 possible_transports=None):
 
2098
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2099
                 ignore_fallbacks=False):
2401
2100
        """Create new branch object at a particular location."""
2402
2101
        if a_bzrdir is None:
2403
2102
            raise ValueError('a_bzrdir must be supplied')
2404
 
        if name is None:
2405
 
            raise ValueError('name must be supplied')
2406
 
        self.bzrdir = a_bzrdir
2407
 
        self._user_transport = self.bzrdir.transport.clone('..')
2408
 
        if name != "":
2409
 
            self._user_transport.set_segment_parameter(
2410
 
                "branch", urlutils.escape(name))
2411
 
        self._base = self._user_transport.base
2412
 
        self.name = name
 
2103
        else:
 
2104
            self.bzrdir = a_bzrdir
 
2105
        self._base = self.bzrdir.transport.clone('..').base
 
2106
        # XXX: We should be able to just do
 
2107
        #   self.base = self.bzrdir.root_transport.base
 
2108
        # but this does not quite work yet -- mbp 20080522
2413
2109
        self._format = _format
2414
2110
        if _control_files is None:
2415
2111
            raise ValueError('BzrBranch _control_files is None')
2416
2112
        self.control_files = _control_files
2417
2113
        self._transport = _control_files._transport
2418
2114
        self.repository = _repository
2419
 
        self.conf_store = None
2420
 
        Branch.__init__(self, possible_transports)
 
2115
        Branch.__init__(self)
2421
2116
 
2422
2117
    def __str__(self):
2423
 
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2118
        return '%s(%r)' % (self.__class__.__name__, self.base)
2424
2119
 
2425
2120
    __repr__ = __str__
2426
2121
 
2430
2125
 
2431
2126
    base = property(_get_base, doc="The URL for the root of this branch.")
2432
2127
 
2433
 
    @property
2434
 
    def user_transport(self):
2435
 
        return self._user_transport
2436
 
 
2437
2128
    def _get_config(self):
2438
 
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
2439
 
 
2440
 
    def _get_config_store(self):
2441
 
        if self.conf_store is None:
2442
 
            self.conf_store =  _mod_config.BranchStore(self)
2443
 
        return self.conf_store
 
2129
        return TransportConfig(self._transport, 'branch.conf')
2444
2130
 
2445
2131
    def is_locked(self):
2446
2132
        return self.control_files.is_locked()
2447
2133
 
2448
2134
    def lock_write(self, token=None):
2449
 
        """Lock the branch for write operations.
2450
 
 
2451
 
        :param token: A token to permit reacquiring a previously held and
2452
 
            preserved lock.
2453
 
        :return: A BranchWriteLockResult.
2454
 
        """
2455
2135
        if not self.is_locked():
2456
2136
            self._note_lock('w')
2457
2137
        # All-in-one needs to always unlock/lock.
2458
2138
        repo_control = getattr(self.repository, 'control_files', None)
2459
2139
        if self.control_files == repo_control or not self.is_locked():
2460
 
            self.repository._warn_if_deprecated(self)
2461
2140
            self.repository.lock_write()
2462
2141
            took_lock = True
2463
2142
        else:
2464
2143
            took_lock = False
2465
2144
        try:
2466
 
            return BranchWriteLockResult(self.unlock,
2467
 
                self.control_files.lock_write(token=token))
 
2145
            return self.control_files.lock_write(token=token)
2468
2146
        except:
2469
2147
            if took_lock:
2470
2148
                self.repository.unlock()
2471
2149
            raise
2472
2150
 
2473
2151
    def lock_read(self):
2474
 
        """Lock the branch for read operations.
2475
 
 
2476
 
        :return: A bzrlib.lock.LogicalLockResult.
2477
 
        """
2478
2152
        if not self.is_locked():
2479
2153
            self._note_lock('r')
2480
2154
        # All-in-one needs to always unlock/lock.
2481
2155
        repo_control = getattr(self.repository, 'control_files', None)
2482
2156
        if self.control_files == repo_control or not self.is_locked():
2483
 
            self.repository._warn_if_deprecated(self)
2484
2157
            self.repository.lock_read()
2485
2158
            took_lock = True
2486
2159
        else:
2487
2160
            took_lock = False
2488
2161
        try:
2489
2162
            self.control_files.lock_read()
2490
 
            return LogicalLockResult(self.unlock)
2491
2163
        except:
2492
2164
            if took_lock:
2493
2165
                self.repository.unlock()
2495
2167
 
2496
2168
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2497
2169
    def unlock(self):
2498
 
        if self.control_files._lock_count == 1 and self.conf_store is not None:
2499
 
            self.conf_store.save_changes()
2500
2170
        try:
2501
2171
            self.control_files.unlock()
2502
2172
        finally:
2523
2193
        """See Branch.print_file."""
2524
2194
        return self.repository.print_file(file, revision_id)
2525
2195
 
 
2196
    def _write_revision_history(self, history):
 
2197
        """Factored out of set_revision_history.
 
2198
 
 
2199
        This performs the actual writing to disk.
 
2200
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2201
        self._transport.put_bytes(
 
2202
            'revision-history', '\n'.join(history),
 
2203
            mode=self.bzrdir._get_file_mode())
 
2204
 
 
2205
    @needs_write_lock
 
2206
    def set_revision_history(self, rev_history):
 
2207
        """See Branch.set_revision_history."""
 
2208
        if 'evil' in debug.debug_flags:
 
2209
            mutter_callsite(3, "set_revision_history scales with history.")
 
2210
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2211
        for rev_id in rev_history:
 
2212
            check_not_reserved_id(rev_id)
 
2213
        if Branch.hooks['post_change_branch_tip']:
 
2214
            # Don't calculate the last_revision_info() if there are no hooks
 
2215
            # that will use it.
 
2216
            old_revno, old_revid = self.last_revision_info()
 
2217
        if len(rev_history) == 0:
 
2218
            revid = _mod_revision.NULL_REVISION
 
2219
        else:
 
2220
            revid = rev_history[-1]
 
2221
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2222
        self._write_revision_history(rev_history)
 
2223
        self._clear_cached_state()
 
2224
        self._cache_revision_history(rev_history)
 
2225
        for hook in Branch.hooks['set_rh']:
 
2226
            hook(self, rev_history)
 
2227
        if Branch.hooks['post_change_branch_tip']:
 
2228
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2229
 
 
2230
    def _synchronize_history(self, destination, revision_id):
 
2231
        """Synchronize last revision and revision history between branches.
 
2232
 
 
2233
        This version is most efficient when the destination is also a
 
2234
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2235
        history is the true lefthand parent history, and all of the revisions
 
2236
        are in the destination's repository.  If not, set_revision_history
 
2237
        will fail.
 
2238
 
 
2239
        :param destination: The branch to copy the history into
 
2240
        :param revision_id: The revision-id to truncate history at.  May
 
2241
          be None to copy complete history.
 
2242
        """
 
2243
        if not isinstance(destination._format, BzrBranchFormat5):
 
2244
            super(BzrBranch, self)._synchronize_history(
 
2245
                destination, revision_id)
 
2246
            return
 
2247
        if revision_id == _mod_revision.NULL_REVISION:
 
2248
            new_history = []
 
2249
        else:
 
2250
            new_history = self.revision_history()
 
2251
        if revision_id is not None and new_history != []:
 
2252
            try:
 
2253
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2254
            except ValueError:
 
2255
                rev = self.repository.get_revision(revision_id)
 
2256
                new_history = rev.get_history(self.repository)[1:]
 
2257
        destination.set_revision_history(new_history)
 
2258
 
2526
2259
    @needs_write_lock
2527
2260
    def set_last_revision_info(self, revno, revision_id):
2528
 
        if not revision_id or not isinstance(revision_id, basestring):
2529
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2261
        """Set the last revision of this branch.
 
2262
 
 
2263
        The caller is responsible for checking that the revno is correct
 
2264
        for this revision id.
 
2265
 
 
2266
        It may be possible to set the branch last revision to an id not
 
2267
        present in the repository.  However, branches can also be
 
2268
        configured to check constraints on history, in which case this may not
 
2269
        be permitted.
 
2270
        """
2530
2271
        revision_id = _mod_revision.ensure_null(revision_id)
2531
 
        old_revno, old_revid = self.last_revision_info()
2532
 
        if self.get_append_revisions_only():
2533
 
            self._check_history_violation(revision_id)
2534
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2535
 
        self._write_last_revision_info(revno, revision_id)
2536
 
        self._clear_cached_state()
2537
 
        self._last_revision_info_cache = revno, revision_id
2538
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2272
        # this old format stores the full history, but this api doesn't
 
2273
        # provide it, so we must generate, and might as well check it's
 
2274
        # correct
 
2275
        history = self._lefthand_history(revision_id)
 
2276
        if len(history) != revno:
 
2277
            raise AssertionError('%d != %d' % (len(history), revno))
 
2278
        self.set_revision_history(history)
 
2279
 
 
2280
    def _gen_revision_history(self):
 
2281
        history = self._transport.get_bytes('revision-history').split('\n')
 
2282
        if history[-1:] == ['']:
 
2283
            # There shouldn't be a trailing newline, but just in case.
 
2284
            history.pop()
 
2285
        return history
 
2286
 
 
2287
    @needs_write_lock
 
2288
    def generate_revision_history(self, revision_id, last_rev=None,
 
2289
        other_branch=None):
 
2290
        """Create a new revision history that will finish with revision_id.
 
2291
 
 
2292
        :param revision_id: the new tip to use.
 
2293
        :param last_rev: The previous last_revision. If not None, then this
 
2294
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2295
        :param other_branch: The other branch that DivergedBranches should
 
2296
            raise with respect to.
 
2297
        """
 
2298
        self.set_revision_history(self._lefthand_history(revision_id,
 
2299
            last_rev, other_branch))
2539
2300
 
2540
2301
    def basis_tree(self):
2541
2302
        """See Branch.basis_tree."""
2550
2311
                pass
2551
2312
        return None
2552
2313
 
 
2314
    def _basic_push(self, target, overwrite, stop_revision):
 
2315
        """Basic implementation of push without bound branches or hooks.
 
2316
 
 
2317
        Must be called with source read locked and target write locked.
 
2318
        """
 
2319
        result = BranchPushResult()
 
2320
        result.source_branch = self
 
2321
        result.target_branch = target
 
2322
        result.old_revno, result.old_revid = target.last_revision_info()
 
2323
        self.update_references(target)
 
2324
        if result.old_revid != self.last_revision():
 
2325
            # We assume that during 'push' this repository is closer than
 
2326
            # the target.
 
2327
            graph = self.repository.get_graph(target.repository)
 
2328
            target.update_revisions(self, stop_revision,
 
2329
                overwrite=overwrite, graph=graph)
 
2330
        if self._push_should_merge_tags():
 
2331
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2332
                overwrite)
 
2333
        result.new_revno, result.new_revid = target.last_revision_info()
 
2334
        return result
 
2335
 
2553
2336
    def get_stacked_on_url(self):
2554
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2337
        raise errors.UnstackableBranchFormat(self._format, self.base)
2555
2338
 
2556
2339
    def set_push_location(self, location):
2557
2340
        """See Branch.set_push_location."""
2566
2349
            self._transport.put_bytes('parent', url + '\n',
2567
2350
                mode=self.bzrdir._get_file_mode())
2568
2351
 
 
2352
 
 
2353
class BzrBranch5(BzrBranch):
 
2354
    """A format 5 branch. This supports new features over plain branches.
 
2355
 
 
2356
    It has support for a master_branch which is the data for bound branches.
 
2357
    """
 
2358
 
 
2359
    def get_bound_location(self):
 
2360
        try:
 
2361
            return self._transport.get_bytes('bound')[:-1]
 
2362
        except errors.NoSuchFile:
 
2363
            return None
 
2364
 
 
2365
    @needs_read_lock
 
2366
    def get_master_branch(self, possible_transports=None):
 
2367
        """Return the branch we are bound to.
 
2368
 
 
2369
        :return: Either a Branch, or None
 
2370
 
 
2371
        This could memoise the branch, but if thats done
 
2372
        it must be revalidated on each new lock.
 
2373
        So for now we just don't memoise it.
 
2374
        # RBC 20060304 review this decision.
 
2375
        """
 
2376
        bound_loc = self.get_bound_location()
 
2377
        if not bound_loc:
 
2378
            return None
 
2379
        try:
 
2380
            return Branch.open(bound_loc,
 
2381
                               possible_transports=possible_transports)
 
2382
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2383
            raise errors.BoundBranchConnectionFailure(
 
2384
                    self, bound_loc, e)
 
2385
 
2569
2386
    @needs_write_lock
2570
 
    def unbind(self):
2571
 
        """If bound, unbind"""
2572
 
        return self.set_bound_location(None)
 
2387
    def set_bound_location(self, location):
 
2388
        """Set the target where this branch is bound to.
 
2389
 
 
2390
        :param location: URL to the target branch
 
2391
        """
 
2392
        if location:
 
2393
            self._transport.put_bytes('bound', location+'\n',
 
2394
                mode=self.bzrdir._get_file_mode())
 
2395
        else:
 
2396
            try:
 
2397
                self._transport.delete('bound')
 
2398
            except errors.NoSuchFile:
 
2399
                return False
 
2400
            return True
2573
2401
 
2574
2402
    @needs_write_lock
2575
2403
    def bind(self, other):
2597
2425
        # history around
2598
2426
        self.set_bound_location(other.base)
2599
2427
 
2600
 
    def get_bound_location(self):
2601
 
        try:
2602
 
            return self._transport.get_bytes('bound')[:-1]
2603
 
        except errors.NoSuchFile:
2604
 
            return None
2605
 
 
2606
 
    @needs_read_lock
2607
 
    def get_master_branch(self, possible_transports=None):
2608
 
        """Return the branch we are bound to.
2609
 
 
2610
 
        :return: Either a Branch, or None
2611
 
        """
2612
 
        if self._master_branch_cache is None:
2613
 
            self._master_branch_cache = self._get_master_branch(
2614
 
                possible_transports)
2615
 
        return self._master_branch_cache
2616
 
 
2617
 
    def _get_master_branch(self, possible_transports):
2618
 
        bound_loc = self.get_bound_location()
2619
 
        if not bound_loc:
2620
 
            return None
2621
 
        try:
2622
 
            return Branch.open(bound_loc,
2623
 
                               possible_transports=possible_transports)
2624
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2625
 
            raise errors.BoundBranchConnectionFailure(
2626
 
                    self, bound_loc, e)
2627
 
 
2628
2428
    @needs_write_lock
2629
 
    def set_bound_location(self, location):
2630
 
        """Set the target where this branch is bound to.
2631
 
 
2632
 
        :param location: URL to the target branch
2633
 
        """
2634
 
        self._master_branch_cache = None
2635
 
        if location:
2636
 
            self._transport.put_bytes('bound', location+'\n',
2637
 
                mode=self.bzrdir._get_file_mode())
2638
 
        else:
2639
 
            try:
2640
 
                self._transport.delete('bound')
2641
 
            except errors.NoSuchFile:
2642
 
                return False
2643
 
            return True
 
2429
    def unbind(self):
 
2430
        """If bound, unbind"""
 
2431
        return self.set_bound_location(None)
2644
2432
 
2645
2433
    @needs_write_lock
2646
2434
    def update(self, possible_transports=None):
2659
2447
            return old_tip
2660
2448
        return None
2661
2449
 
2662
 
    def _read_last_revision_info(self):
2663
 
        revision_string = self._transport.get_bytes('last-revision')
2664
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2665
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2666
 
        revno = int(revno)
2667
 
        return revno, revision_id
2668
 
 
2669
 
    def _write_last_revision_info(self, revno, revision_id):
2670
 
        """Simply write out the revision id, with no checks.
2671
 
 
2672
 
        Use set_last_revision_info to perform this safely.
2673
 
 
2674
 
        Does not update the revision_history cache.
2675
 
        """
2676
 
        revision_id = _mod_revision.ensure_null(revision_id)
2677
 
        out_string = '%d %s\n' % (revno, revision_id)
2678
 
        self._transport.put_bytes('last-revision', out_string,
2679
 
            mode=self.bzrdir._get_file_mode())
2680
 
 
2681
 
    @needs_write_lock
2682
 
    def update_feature_flags(self, updated_flags):
2683
 
        """Update the feature flags for this branch.
2684
 
 
2685
 
        :param updated_flags: Dictionary mapping feature names to necessities
2686
 
            A necessity can be None to indicate the feature should be removed
2687
 
        """
2688
 
        self._format._update_feature_flags(updated_flags)
2689
 
        self.control_transport.put_bytes('format', self._format.as_string())
2690
 
 
2691
 
 
2692
 
class FullHistoryBzrBranch(BzrBranch):
2693
 
    """Bzr branch which contains the full revision history."""
2694
 
 
2695
 
    @needs_write_lock
2696
 
    def set_last_revision_info(self, revno, revision_id):
2697
 
        if not revision_id or not isinstance(revision_id, basestring):
2698
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2699
 
        revision_id = _mod_revision.ensure_null(revision_id)
2700
 
        # this old format stores the full history, but this api doesn't
2701
 
        # provide it, so we must generate, and might as well check it's
2702
 
        # correct
2703
 
        history = self._lefthand_history(revision_id)
2704
 
        if len(history) != revno:
2705
 
            raise AssertionError('%d != %d' % (len(history), revno))
2706
 
        self._set_revision_history(history)
2707
 
 
2708
 
    def _read_last_revision_info(self):
2709
 
        rh = self._revision_history()
2710
 
        revno = len(rh)
2711
 
        if revno:
2712
 
            return (revno, rh[-1])
2713
 
        else:
2714
 
            return (0, _mod_revision.NULL_REVISION)
2715
 
 
2716
 
    def _set_revision_history(self, rev_history):
2717
 
        if 'evil' in debug.debug_flags:
2718
 
            mutter_callsite(3, "set_revision_history scales with history.")
2719
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2720
 
        for rev_id in rev_history:
2721
 
            check_not_reserved_id(rev_id)
2722
 
        if Branch.hooks['post_change_branch_tip']:
2723
 
            # Don't calculate the last_revision_info() if there are no hooks
2724
 
            # that will use it.
2725
 
            old_revno, old_revid = self.last_revision_info()
2726
 
        if len(rev_history) == 0:
2727
 
            revid = _mod_revision.NULL_REVISION
2728
 
        else:
2729
 
            revid = rev_history[-1]
2730
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2731
 
        self._write_revision_history(rev_history)
2732
 
        self._clear_cached_state()
2733
 
        self._cache_revision_history(rev_history)
2734
 
        if Branch.hooks['post_change_branch_tip']:
2735
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2736
 
 
2737
 
    def _write_revision_history(self, history):
2738
 
        """Factored out of set_revision_history.
2739
 
 
2740
 
        This performs the actual writing to disk.
2741
 
        It is intended to be called by set_revision_history."""
2742
 
        self._transport.put_bytes(
2743
 
            'revision-history', '\n'.join(history),
2744
 
            mode=self.bzrdir._get_file_mode())
2745
 
 
2746
 
    def _gen_revision_history(self):
2747
 
        history = self._transport.get_bytes('revision-history').split('\n')
2748
 
        if history[-1:] == ['']:
2749
 
            # There shouldn't be a trailing newline, but just in case.
2750
 
            history.pop()
2751
 
        return history
2752
 
 
2753
 
    def _synchronize_history(self, destination, revision_id):
2754
 
        if not isinstance(destination, FullHistoryBzrBranch):
2755
 
            super(BzrBranch, self)._synchronize_history(
2756
 
                destination, revision_id)
2757
 
            return
2758
 
        if revision_id == _mod_revision.NULL_REVISION:
2759
 
            new_history = []
2760
 
        else:
2761
 
            new_history = self._revision_history()
2762
 
        if revision_id is not None and new_history != []:
2763
 
            try:
2764
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2765
 
            except ValueError:
2766
 
                rev = self.repository.get_revision(revision_id)
2767
 
                new_history = rev.get_history(self.repository)[1:]
2768
 
        destination._set_revision_history(new_history)
2769
 
 
2770
 
    @needs_write_lock
2771
 
    def generate_revision_history(self, revision_id, last_rev=None,
2772
 
        other_branch=None):
2773
 
        """Create a new revision history that will finish with revision_id.
2774
 
 
2775
 
        :param revision_id: the new tip to use.
2776
 
        :param last_rev: The previous last_revision. If not None, then this
2777
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2778
 
        :param other_branch: The other branch that DivergedBranches should
2779
 
            raise with respect to.
2780
 
        """
2781
 
        self._set_revision_history(self._lefthand_history(revision_id,
2782
 
            last_rev, other_branch))
2783
 
 
2784
 
 
2785
 
class BzrBranch5(FullHistoryBzrBranch):
2786
 
    """A format 5 branch. This supports new features over plain branches.
2787
 
 
2788
 
    It has support for a master_branch which is the data for bound branches.
2789
 
    """
2790
 
 
2791
 
 
2792
 
class BzrBranch8(BzrBranch):
 
2450
 
 
2451
class BzrBranch8(BzrBranch5):
2793
2452
    """A branch that stores tree-reference locations."""
2794
2453
 
2795
 
    def _open_hook(self, possible_transports=None):
 
2454
    def _open_hook(self):
2796
2455
        if self._ignore_fallbacks:
2797
2456
            return
2798
 
        if possible_transports is None:
2799
 
            possible_transports = [self.bzrdir.root_transport]
2800
2457
        try:
2801
2458
            url = self.get_stacked_on_url()
2802
2459
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2810
2467
                    raise AssertionError(
2811
2468
                        "'transform_fallback_location' hook %s returned "
2812
2469
                        "None, not a URL." % hook_name)
2813
 
            self._activate_fallback_location(url,
2814
 
                possible_transports=possible_transports)
 
2470
            self._activate_fallback_location(url)
2815
2471
 
2816
2472
    def __init__(self, *args, **kwargs):
2817
2473
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2824
2480
        self._last_revision_info_cache = None
2825
2481
        self._reference_info = None
2826
2482
 
 
2483
    def _last_revision_info(self):
 
2484
        revision_string = self._transport.get_bytes('last-revision')
 
2485
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2486
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2487
        revno = int(revno)
 
2488
        return revno, revision_id
 
2489
 
 
2490
    def _write_last_revision_info(self, revno, revision_id):
 
2491
        """Simply write out the revision id, with no checks.
 
2492
 
 
2493
        Use set_last_revision_info to perform this safely.
 
2494
 
 
2495
        Does not update the revision_history cache.
 
2496
        Intended to be called by set_last_revision_info and
 
2497
        _write_revision_history.
 
2498
        """
 
2499
        revision_id = _mod_revision.ensure_null(revision_id)
 
2500
        out_string = '%d %s\n' % (revno, revision_id)
 
2501
        self._transport.put_bytes('last-revision', out_string,
 
2502
            mode=self.bzrdir._get_file_mode())
 
2503
 
 
2504
    @needs_write_lock
 
2505
    def set_last_revision_info(self, revno, revision_id):
 
2506
        revision_id = _mod_revision.ensure_null(revision_id)
 
2507
        old_revno, old_revid = self.last_revision_info()
 
2508
        if self._get_append_revisions_only():
 
2509
            self._check_history_violation(revision_id)
 
2510
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2511
        self._write_last_revision_info(revno, revision_id)
 
2512
        self._clear_cached_state()
 
2513
        self._last_revision_info_cache = revno, revision_id
 
2514
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2515
 
 
2516
    def _synchronize_history(self, destination, revision_id):
 
2517
        """Synchronize last revision and revision history between branches.
 
2518
 
 
2519
        :see: Branch._synchronize_history
 
2520
        """
 
2521
        # XXX: The base Branch has a fast implementation of this method based
 
2522
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2523
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2524
        # but wants the fast implementation, so it calls
 
2525
        # Branch._synchronize_history directly.
 
2526
        Branch._synchronize_history(self, destination, revision_id)
 
2527
 
2827
2528
    def _check_history_violation(self, revision_id):
2828
 
        current_revid = self.last_revision()
2829
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2529
        last_revision = _mod_revision.ensure_null(self.last_revision())
2830
2530
        if _mod_revision.is_null(last_revision):
2831
2531
            return
2832
 
        graph = self.repository.get_graph()
2833
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2834
 
            if lh_ancestor == current_revid:
2835
 
                return
2836
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2532
        if last_revision not in self._lefthand_history(revision_id):
 
2533
            raise errors.AppendRevisionsOnlyViolation(self.base)
2837
2534
 
2838
2535
    def _gen_revision_history(self):
2839
2536
        """Generate the revision history from last revision
2842
2539
        self._extend_partial_history(stop_index=last_revno-1)
2843
2540
        return list(reversed(self._partial_revision_history_cache))
2844
2541
 
 
2542
    def _write_revision_history(self, history):
 
2543
        """Factored out of set_revision_history.
 
2544
 
 
2545
        This performs the actual writing to disk, with format-specific checks.
 
2546
        It is intended to be called by BzrBranch5.set_revision_history.
 
2547
        """
 
2548
        if len(history) == 0:
 
2549
            last_revision = 'null:'
 
2550
        else:
 
2551
            if history != self._lefthand_history(history[-1]):
 
2552
                raise errors.NotLefthandHistory(history)
 
2553
            last_revision = history[-1]
 
2554
        if self._get_append_revisions_only():
 
2555
            self._check_history_violation(last_revision)
 
2556
        self._write_last_revision_info(len(history), last_revision)
 
2557
 
2845
2558
    @needs_write_lock
2846
2559
    def _set_parent_location(self, url):
2847
2560
        """Set the parent branch"""
2923
2636
        if branch_location is None:
2924
2637
            return Branch.reference_parent(self, file_id, path,
2925
2638
                                           possible_transports)
2926
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2639
        branch_location = urlutils.join(self.base, branch_location)
2927
2640
        return Branch.open(branch_location,
2928
2641
                           possible_transports=possible_transports)
2929
2642
 
2933
2646
 
2934
2647
    def set_bound_location(self, location):
2935
2648
        """See Branch.set_push_location."""
2936
 
        self._master_branch_cache = None
2937
2649
        result = None
2938
 
        conf = self.get_config_stack()
 
2650
        config = self.get_config()
2939
2651
        if location is None:
2940
 
            if not conf.get('bound'):
 
2652
            if config.get_user_option('bound') != 'True':
2941
2653
                return False
2942
2654
            else:
2943
 
                conf.set('bound', 'False')
 
2655
                config.set_user_option('bound', 'False', warn_masked=True)
2944
2656
                return True
2945
2657
        else:
2946
2658
            self._set_config_location('bound_location', location,
2947
 
                                      config=conf)
2948
 
            conf.set('bound', 'True')
 
2659
                                      config=config)
 
2660
            config.set_user_option('bound', 'True', warn_masked=True)
2949
2661
        return True
2950
2662
 
2951
2663
    def _get_bound_location(self, bound):
2952
2664
        """Return the bound location in the config file.
2953
2665
 
2954
2666
        Return None if the bound parameter does not match"""
2955
 
        conf = self.get_config_stack()
2956
 
        if conf.get('bound') != bound:
 
2667
        config = self.get_config()
 
2668
        config_bound = (config.get_user_option('bound') == 'True')
 
2669
        if config_bound != bound:
2957
2670
            return None
2958
 
        return self._get_config_location('bound_location', config=conf)
 
2671
        return self._get_config_location('bound_location', config=config)
2959
2672
 
2960
2673
    def get_bound_location(self):
2961
 
        """See Branch.get_bound_location."""
 
2674
        """See Branch.set_push_location."""
2962
2675
        return self._get_bound_location(True)
2963
2676
 
2964
2677
    def get_old_bound_location(self):
2969
2682
        # you can always ask for the URL; but you might not be able to use it
2970
2683
        # if the repo can't support stacking.
2971
2684
        ## self._check_stackable_repo()
2972
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2973
 
        # waste effort reading the whole stack of config files.
2974
 
        conf = _mod_config.BranchOnlyStack(self)
2975
 
        stacked_url = self._get_config_location('stacked_on_location',
2976
 
                                                config=conf)
 
2685
        stacked_url = self._get_config_location('stacked_on_location')
2977
2686
        if stacked_url is None:
2978
2687
            raise errors.NotStacked(self)
2979
 
        return stacked_url.encode('utf-8')
 
2688
        return stacked_url
 
2689
 
 
2690
    def _get_append_revisions_only(self):
 
2691
        value = self.get_config().get_user_option('append_revisions_only')
 
2692
        return value == 'True'
 
2693
 
 
2694
    @needs_write_lock
 
2695
    def generate_revision_history(self, revision_id, last_rev=None,
 
2696
                                  other_branch=None):
 
2697
        """See BzrBranch5.generate_revision_history"""
 
2698
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2699
        revno = len(history)
 
2700
        self.set_last_revision_info(revno, revision_id)
2980
2701
 
2981
2702
    @needs_read_lock
2982
2703
    def get_rev_id(self, revno, history=None):
3007
2728
        try:
3008
2729
            index = self._partial_revision_history_cache.index(revision_id)
3009
2730
        except ValueError:
3010
 
            try:
3011
 
                self._extend_partial_history(stop_revision=revision_id)
3012
 
            except errors.RevisionNotPresent, e:
3013
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2731
            self._extend_partial_history(stop_revision=revision_id)
3014
2732
            index = len(self._partial_revision_history_cache) - 1
3015
 
            if index < 0:
3016
 
                raise errors.NoSuchRevision(self, revision_id)
3017
2733
            if self._partial_revision_history_cache[index] != revision_id:
3018
2734
                raise errors.NoSuchRevision(self, revision_id)
3019
2735
        return self.revno() - index
3041
2757
    """
3042
2758
 
3043
2759
    def get_stacked_on_url(self):
3044
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2760
        raise errors.UnstackableBranchFormat(self._format, self.base)
3045
2761
 
3046
2762
 
3047
2763
######################################################################
3071
2787
    :ivar local_branch: target branch if there is a Master, else None
3072
2788
    :ivar target_branch: Target/destination branch object. (write locked)
3073
2789
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3074
 
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3075
2790
    """
3076
2791
 
 
2792
    def __int__(self):
 
2793
        # DEPRECATED: pull used to return the change in revno
 
2794
        return self.new_revno - self.old_revno
 
2795
 
3077
2796
    def report(self, to_file):
3078
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3079
 
        tag_updates = getattr(self, "tag_updates", None)
3080
2797
        if not is_quiet():
3081
 
            if self.old_revid != self.new_revid:
 
2798
            if self.old_revid == self.new_revid:
 
2799
                to_file.write('No revisions to pull.\n')
 
2800
            else:
3082
2801
                to_file.write('Now on revision %d.\n' % self.new_revno)
3083
 
            if tag_updates:
3084
 
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3085
 
            if self.old_revid == self.new_revid and not tag_updates:
3086
 
                if not tag_conflicts:
3087
 
                    to_file.write('No revisions or tags to pull.\n')
3088
 
                else:
3089
 
                    to_file.write('No revisions to pull.\n')
3090
2802
        self._show_tag_conficts(to_file)
3091
2803
 
3092
2804
 
3109
2821
        target, otherwise it will be None.
3110
2822
    """
3111
2823
 
 
2824
    def __int__(self):
 
2825
        # DEPRECATED: push used to return the change in revno
 
2826
        return self.new_revno - self.old_revno
 
2827
 
3112
2828
    def report(self, to_file):
3113
 
        # TODO: This function gets passed a to_file, but then
3114
 
        # ignores it and calls note() instead. This is also
3115
 
        # inconsistent with PullResult(), which writes to stdout.
3116
 
        # -- JRV20110901, bug #838853
3117
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
3118
 
        tag_updates = getattr(self, "tag_updates", None)
3119
 
        if not is_quiet():
3120
 
            if self.old_revid != self.new_revid:
3121
 
                note(gettext('Pushed up to revision %d.') % self.new_revno)
3122
 
            if tag_updates:
3123
 
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3124
 
            if self.old_revid == self.new_revid and not tag_updates:
3125
 
                if not tag_conflicts:
3126
 
                    note(gettext('No new revisions or tags to push.'))
3127
 
                else:
3128
 
                    note(gettext('No new revisions to push.'))
 
2829
        """Write a human-readable description of the result."""
 
2830
        if self.old_revid == self.new_revid:
 
2831
            note('No new revisions to push.')
 
2832
        else:
 
2833
            note('Pushed up to revision %d.' % self.new_revno)
3129
2834
        self._show_tag_conficts(to_file)
3130
2835
 
3131
2836
 
3145
2850
        :param verbose: Requests more detailed display of what was checked,
3146
2851
            if any.
3147
2852
        """
3148
 
        note(gettext('checked branch {0} format {1}').format(
3149
 
                                self.branch.user_url, self.branch._format))
 
2853
        note('checked branch %s format %s', self.branch.base,
 
2854
            self.branch._format)
3150
2855
        for error in self.errors:
3151
 
            note(gettext('found error:%s'), error)
 
2856
            note('found error:%s', error)
3152
2857
 
3153
2858
 
3154
2859
class Converter5to6(object):
3161
2866
 
3162
2867
        # Copy source data into target
3163
2868
        new_branch._write_last_revision_info(*branch.last_revision_info())
3164
 
        new_branch.lock_write()
3165
 
        try:
3166
 
            new_branch.set_parent(branch.get_parent())
3167
 
            new_branch.set_bound_location(branch.get_bound_location())
3168
 
            new_branch.set_push_location(branch.get_push_location())
3169
 
        finally:
3170
 
            new_branch.unlock()
 
2869
        new_branch.set_parent(branch.get_parent())
 
2870
        new_branch.set_bound_location(branch.get_bound_location())
 
2871
        new_branch.set_push_location(branch.get_push_location())
3171
2872
 
3172
2873
        # New branch has no tags by default
3173
2874
        new_branch.tags._set_tag_dict({})
3174
2875
 
3175
2876
        # Copying done; now update target format
3176
2877
        new_branch._transport.put_bytes('format',
3177
 
            format.as_string(),
 
2878
            format.get_format_string(),
3178
2879
            mode=new_branch.bzrdir._get_file_mode())
3179
2880
 
3180
2881
        # Clean up old files
3181
2882
        new_branch._transport.delete('revision-history')
3182
 
        branch.lock_write()
3183
2883
        try:
3184
 
            try:
3185
 
                branch.set_parent(None)
3186
 
            except errors.NoSuchFile:
3187
 
                pass
3188
 
            branch.set_bound_location(None)
3189
 
        finally:
3190
 
            branch.unlock()
 
2884
            branch.set_parent(None)
 
2885
        except errors.NoSuchFile:
 
2886
            pass
 
2887
        branch.set_bound_location(None)
3191
2888
 
3192
2889
 
3193
2890
class Converter6to7(object):
3197
2894
        format = BzrBranchFormat7()
3198
2895
        branch._set_config_location('stacked_on_location', '')
3199
2896
        # update target format
3200
 
        branch._transport.put_bytes('format', format.as_string())
 
2897
        branch._transport.put_bytes('format', format.get_format_string())
3201
2898
 
3202
2899
 
3203
2900
class Converter7to8(object):
3204
 
    """Perform an in-place upgrade of format 7 to format 8"""
 
2901
    """Perform an in-place upgrade of format 6 to format 7"""
3205
2902
 
3206
2903
    def convert(self, branch):
3207
2904
        format = BzrBranchFormat8()
3208
2905
        branch._transport.put_bytes('references', '')
3209
2906
        # update target format
3210
 
        branch._transport.put_bytes('format', format.as_string())
 
2907
        branch._transport.put_bytes('format', format.get_format_string())
 
2908
 
 
2909
 
 
2910
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2911
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2912
    duration.
 
2913
 
 
2914
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2915
 
 
2916
    If an exception is raised by callable, then that exception *will* be
 
2917
    propagated, even if the unlock attempt raises its own error.  Thus
 
2918
    _run_with_write_locked_target should be preferred to simply doing::
 
2919
 
 
2920
        target.lock_write()
 
2921
        try:
 
2922
            return callable(*args, **kwargs)
 
2923
        finally:
 
2924
            target.unlock()
 
2925
 
 
2926
    """
 
2927
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2928
    # should share code?
 
2929
    target.lock_write()
 
2930
    try:
 
2931
        result = callable(*args, **kwargs)
 
2932
    except:
 
2933
        exc_info = sys.exc_info()
 
2934
        try:
 
2935
            target.unlock()
 
2936
        finally:
 
2937
            raise exc_info[0], exc_info[1], exc_info[2]
 
2938
    else:
 
2939
        target.unlock()
 
2940
        return result
3211
2941
 
3212
2942
 
3213
2943
class InterBranch(InterObject):
3221
2951
    _optimisers = []
3222
2952
    """The available optimised InterBranch types."""
3223
2953
 
3224
 
    @classmethod
3225
 
    def _get_branch_formats_to_test(klass):
3226
 
        """Return an iterable of format tuples for testing.
3227
 
        
3228
 
        :return: An iterable of (from_format, to_format) to use when testing
3229
 
            this InterBranch class. Each InterBranch class should define this
3230
 
            method itself.
3231
 
        """
3232
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2954
    @staticmethod
 
2955
    def _get_branch_formats_to_test():
 
2956
        """Return a tuple with the Branch formats to use when testing."""
 
2957
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3233
2958
 
3234
 
    @needs_write_lock
3235
2959
    def pull(self, overwrite=False, stop_revision=None,
3236
2960
             possible_transports=None, local=False):
3237
2961
        """Mirror source into target branch.
3242
2966
        """
3243
2967
        raise NotImplementedError(self.pull)
3244
2968
 
3245
 
    @needs_write_lock
3246
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2969
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2970
                         graph=None):
 
2971
        """Pull in new perfect-fit revisions.
 
2972
 
 
2973
        :param stop_revision: Updated until the given revision
 
2974
        :param overwrite: Always set the branch pointer, rather than checking
 
2975
            to see if it is a proper descendant.
 
2976
        :param graph: A Graph object that can be used to query history
 
2977
            information. This can be None.
 
2978
        :return: None
 
2979
        """
 
2980
        raise NotImplementedError(self.update_revisions)
 
2981
 
 
2982
    def push(self, overwrite=False, stop_revision=None,
3247
2983
             _override_hook_source_branch=None):
3248
2984
        """Mirror the source branch into the target branch.
3249
2985
 
3251
2987
        """
3252
2988
        raise NotImplementedError(self.push)
3253
2989
 
3254
 
    @needs_write_lock
3255
 
    def copy_content_into(self, revision_id=None):
3256
 
        """Copy the content of source into target
3257
 
 
3258
 
        revision_id: if not None, the revision history in the new branch will
3259
 
                     be truncated to end with revision_id.
3260
 
        """
3261
 
        raise NotImplementedError(self.copy_content_into)
3262
 
 
3263
 
    @needs_write_lock
3264
 
    def fetch(self, stop_revision=None, limit=None):
3265
 
        """Fetch revisions.
3266
 
 
3267
 
        :param stop_revision: Last revision to fetch
3268
 
        :param limit: Optional rough limit of revisions to fetch
3269
 
        """
3270
 
        raise NotImplementedError(self.fetch)
3271
 
 
3272
 
 
3273
 
def _fix_overwrite_type(overwrite):
3274
 
    if isinstance(overwrite, bool):
3275
 
        if overwrite:
3276
 
            return ["history", "tags"]
3277
 
        else:
3278
 
            return []
3279
 
    return overwrite
3280
 
 
3281
2990
 
3282
2991
class GenericInterBranch(InterBranch):
3283
 
    """InterBranch implementation that uses public Branch functions."""
3284
 
 
3285
 
    @classmethod
3286
 
    def is_compatible(klass, source, target):
3287
 
        # GenericBranch uses the public API, so always compatible
3288
 
        return True
3289
 
 
3290
 
    @classmethod
3291
 
    def _get_branch_formats_to_test(klass):
3292
 
        return [(format_registry.get_default(), format_registry.get_default())]
3293
 
 
3294
 
    @classmethod
3295
 
    def unwrap_format(klass, format):
3296
 
        if isinstance(format, remote.RemoteBranchFormat):
3297
 
            format._ensure_real()
3298
 
            return format._custom_format
3299
 
        return format
3300
 
 
3301
 
    @needs_write_lock
3302
 
    def copy_content_into(self, revision_id=None):
3303
 
        """Copy the content of source into target
3304
 
 
3305
 
        revision_id: if not None, the revision history in the new branch will
3306
 
                     be truncated to end with revision_id.
3307
 
        """
3308
 
        self.source.update_references(self.target)
3309
 
        self.source._synchronize_history(self.target, revision_id)
3310
 
        try:
3311
 
            parent = self.source.get_parent()
3312
 
        except errors.InaccessibleParent, e:
3313
 
            mutter('parent was not accessible to copy: %s', e)
3314
 
        else:
3315
 
            if parent:
3316
 
                self.target.set_parent(parent)
3317
 
        if self.source._push_should_merge_tags():
3318
 
            self.source.tags.merge_to(self.target.tags)
3319
 
 
3320
 
    @needs_write_lock
3321
 
    def fetch(self, stop_revision=None, limit=None):
3322
 
        if self.target.base == self.source.base:
3323
 
            return (0, [])
 
2992
    """InterBranch implementation that uses public Branch functions.
 
2993
    """
 
2994
 
 
2995
    @staticmethod
 
2996
    def _get_branch_formats_to_test():
 
2997
        return BranchFormat._default_format, BranchFormat._default_format
 
2998
 
 
2999
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3000
        graph=None):
 
3001
        """See InterBranch.update_revisions()."""
3324
3002
        self.source.lock_read()
3325
3003
        try:
3326
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3327
 
            fetch_spec_factory.source_branch = self.source
3328
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3329
 
            fetch_spec_factory.source_repo = self.source.repository
3330
 
            fetch_spec_factory.target_repo = self.target.repository
3331
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3332
 
            fetch_spec_factory.limit = limit
3333
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3334
 
            return self.target.repository.fetch(self.source.repository,
3335
 
                fetch_spec=fetch_spec)
 
3004
            other_revno, other_last_revision = self.source.last_revision_info()
 
3005
            stop_revno = None # unknown
 
3006
            if stop_revision is None:
 
3007
                stop_revision = other_last_revision
 
3008
                if _mod_revision.is_null(stop_revision):
 
3009
                    # if there are no commits, we're done.
 
3010
                    return
 
3011
                stop_revno = other_revno
 
3012
 
 
3013
            # what's the current last revision, before we fetch [and change it
 
3014
            # possibly]
 
3015
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3016
            # we fetch here so that we don't process data twice in the common
 
3017
            # case of having something to pull, and so that the check for
 
3018
            # already merged can operate on the just fetched graph, which will
 
3019
            # be cached in memory.
 
3020
            self.target.fetch(self.source, stop_revision)
 
3021
            # Check to see if one is an ancestor of the other
 
3022
            if not overwrite:
 
3023
                if graph is None:
 
3024
                    graph = self.target.repository.get_graph()
 
3025
                if self.target._check_if_descendant_or_diverged(
 
3026
                        stop_revision, last_rev, graph, self.source):
 
3027
                    # stop_revision is a descendant of last_rev, but we aren't
 
3028
                    # overwriting, so we're done.
 
3029
                    return
 
3030
            if stop_revno is None:
 
3031
                if graph is None:
 
3032
                    graph = self.target.repository.get_graph()
 
3033
                this_revno, this_last_revision = \
 
3034
                        self.target.last_revision_info()
 
3035
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3036
                                [(other_last_revision, other_revno),
 
3037
                                 (this_last_revision, this_revno)])
 
3038
            self.target.set_last_revision_info(stop_revno, stop_revision)
3336
3039
        finally:
3337
3040
            self.source.unlock()
3338
3041
 
3339
 
    @needs_write_lock
3340
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3341
 
            graph=None):
3342
 
        other_revno, other_last_revision = self.source.last_revision_info()
3343
 
        stop_revno = None # unknown
3344
 
        if stop_revision is None:
3345
 
            stop_revision = other_last_revision
3346
 
            if _mod_revision.is_null(stop_revision):
3347
 
                # if there are no commits, we're done.
3348
 
                return
3349
 
            stop_revno = other_revno
3350
 
 
3351
 
        # what's the current last revision, before we fetch [and change it
3352
 
        # possibly]
3353
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3354
 
        # we fetch here so that we don't process data twice in the common
3355
 
        # case of having something to pull, and so that the check for
3356
 
        # already merged can operate on the just fetched graph, which will
3357
 
        # be cached in memory.
3358
 
        self.fetch(stop_revision=stop_revision)
3359
 
        # Check to see if one is an ancestor of the other
3360
 
        if not overwrite:
3361
 
            if graph is None:
3362
 
                graph = self.target.repository.get_graph()
3363
 
            if self.target._check_if_descendant_or_diverged(
3364
 
                    stop_revision, last_rev, graph, self.source):
3365
 
                # stop_revision is a descendant of last_rev, but we aren't
3366
 
                # overwriting, so we're done.
3367
 
                return
3368
 
        if stop_revno is None:
3369
 
            if graph is None:
3370
 
                graph = self.target.repository.get_graph()
3371
 
            this_revno, this_last_revision = \
3372
 
                    self.target.last_revision_info()
3373
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3374
 
                            [(other_last_revision, other_revno),
3375
 
                             (this_last_revision, this_revno)])
3376
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3377
 
 
3378
 
    @needs_write_lock
3379
3042
    def pull(self, overwrite=False, stop_revision=None,
3380
 
             possible_transports=None, run_hooks=True,
3381
 
             _override_hook_target=None, local=False):
3382
 
        """Pull from source into self, updating my master if any.
3383
 
 
3384
 
        :param run_hooks: Private parameter - if false, this branch
3385
 
            is being called because it's the master of the primary branch,
3386
 
            so it should not run its hooks.
3387
 
        """
3388
 
        bound_location = self.target.get_bound_location()
3389
 
        if local and not bound_location:
3390
 
            raise errors.LocalRequiresBoundBranch()
3391
 
        master_branch = None
3392
 
        source_is_master = False
3393
 
        if bound_location:
3394
 
            # bound_location comes from a config file, some care has to be
3395
 
            # taken to relate it to source.user_url
3396
 
            normalized = urlutils.normalize_url(bound_location)
3397
 
            try:
3398
 
                relpath = self.source.user_transport.relpath(normalized)
3399
 
                source_is_master = (relpath == '')
3400
 
            except (errors.PathNotChild, errors.InvalidURL):
3401
 
                source_is_master = False
3402
 
        if not local and bound_location and not source_is_master:
3403
 
            # not pulling from master, so we need to update master.
3404
 
            master_branch = self.target.get_master_branch(possible_transports)
3405
 
            master_branch.lock_write()
3406
 
        try:
3407
 
            if master_branch:
3408
 
                # pull from source into master.
3409
 
                master_branch.pull(self.source, overwrite, stop_revision,
3410
 
                    run_hooks=False)
3411
 
            return self._pull(overwrite,
3412
 
                stop_revision, _hook_master=master_branch,
3413
 
                run_hooks=run_hooks,
3414
 
                _override_hook_target=_override_hook_target,
3415
 
                merge_tags_to_master=not source_is_master)
3416
 
        finally:
3417
 
            if master_branch:
3418
 
                master_branch.unlock()
3419
 
 
3420
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3421
 
             _override_hook_source_branch=None):
3422
 
        """See InterBranch.push.
3423
 
 
3424
 
        This is the basic concrete implementation of push()
3425
 
 
3426
 
        :param _override_hook_source_branch: If specified, run the hooks
3427
 
            passing this Branch as the source, rather than self.  This is for
3428
 
            use of RemoteBranch, where push is delegated to the underlying
3429
 
            vfs-based Branch.
3430
 
        """
3431
 
        if lossy:
3432
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3433
 
        # TODO: Public option to disable running hooks - should be trivial but
3434
 
        # needs tests.
3435
 
 
3436
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3437
 
        op.add_cleanup(self.source.lock_read().unlock)
3438
 
        op.add_cleanup(self.target.lock_write().unlock)
3439
 
        return op.run(overwrite, stop_revision,
3440
 
            _override_hook_source_branch=_override_hook_source_branch)
3441
 
 
3442
 
    def _basic_push(self, overwrite, stop_revision):
3443
 
        """Basic implementation of push without bound branches or hooks.
3444
 
 
3445
 
        Must be called with source read locked and target write locked.
3446
 
        """
3447
 
        result = BranchPushResult()
3448
 
        result.source_branch = self.source
3449
 
        result.target_branch = self.target
3450
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3451
 
        self.source.update_references(self.target)
3452
 
        overwrite = _fix_overwrite_type(overwrite)
3453
 
        if result.old_revid != stop_revision:
3454
 
            # We assume that during 'push' this repository is closer than
3455
 
            # the target.
3456
 
            graph = self.source.repository.get_graph(self.target.repository)
3457
 
            self._update_revisions(stop_revision,
3458
 
                overwrite=("history" in overwrite),
3459
 
                graph=graph)
3460
 
        if self.source._push_should_merge_tags():
3461
 
            result.tag_updates, result.tag_conflicts = (
3462
 
                self.source.tags.merge_to(
3463
 
                self.target.tags, "tags" in overwrite))
3464
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3465
 
        return result
3466
 
 
3467
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3468
 
            _override_hook_source_branch=None):
3469
 
        """Push from source into target, and into target's master if any.
3470
 
        """
3471
 
        def _run_hooks():
3472
 
            if _override_hook_source_branch:
3473
 
                result.source_branch = _override_hook_source_branch
3474
 
            for hook in Branch.hooks['post_push']:
3475
 
                hook(result)
3476
 
 
3477
 
        bound_location = self.target.get_bound_location()
3478
 
        if bound_location and self.target.base != bound_location:
3479
 
            # there is a master branch.
3480
 
            #
3481
 
            # XXX: Why the second check?  Is it even supported for a branch to
3482
 
            # be bound to itself? -- mbp 20070507
3483
 
            master_branch = self.target.get_master_branch()
3484
 
            master_branch.lock_write()
3485
 
            operation.add_cleanup(master_branch.unlock)
3486
 
            # push into the master from the source branch.
3487
 
            master_inter = InterBranch.get(self.source, master_branch)
3488
 
            master_inter._basic_push(overwrite, stop_revision)
3489
 
            # and push into the target branch from the source. Note that
3490
 
            # we push from the source branch again, because it's considered
3491
 
            # the highest bandwidth repository.
3492
 
            result = self._basic_push(overwrite, stop_revision)
3493
 
            result.master_branch = master_branch
3494
 
            result.local_branch = self.target
3495
 
        else:
3496
 
            master_branch = None
3497
 
            # no master branch
3498
 
            result = self._basic_push(overwrite, stop_revision)
3499
 
            # TODO: Why set master_branch and local_branch if there's no
3500
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3501
 
            # 20070504
3502
 
            result.master_branch = self.target
3503
 
            result.local_branch = None
3504
 
        _run_hooks()
3505
 
        return result
3506
 
 
3507
 
    def _pull(self, overwrite=False, stop_revision=None,
3508
3043
             possible_transports=None, _hook_master=None, run_hooks=True,
3509
 
             _override_hook_target=None, local=False,
3510
 
             merge_tags_to_master=True):
 
3044
             _override_hook_target=None, local=False):
3511
3045
        """See Branch.pull.
3512
3046
 
3513
 
        This function is the core worker, used by GenericInterBranch.pull to
3514
 
        avoid duplication when pulling source->master and source->local.
3515
 
 
3516
3047
        :param _hook_master: Private parameter - set the branch to
3517
3048
            be supplied as the master to pull hooks.
3518
3049
        :param run_hooks: Private parameter - if false, this branch
3519
3050
            is being called because it's the master of the primary branch,
3520
3051
            so it should not run its hooks.
3521
 
            is being called because it's the master of the primary branch,
3522
 
            so it should not run its hooks.
3523
3052
        :param _override_hook_target: Private parameter - set the branch to be
3524
3053
            supplied as the target_branch to pull hooks.
3525
3054
        :param local: Only update the local branch, and not the bound branch.
3544
3073
            # -- JRV20090506
3545
3074
            result.old_revno, result.old_revid = \
3546
3075
                self.target.last_revision_info()
3547
 
            overwrite = _fix_overwrite_type(overwrite)
3548
 
            self._update_revisions(stop_revision,
3549
 
                overwrite=("history" in overwrite),
3550
 
                graph=graph)
 
3076
            self.target.update_revisions(self.source, stop_revision,
 
3077
                overwrite=overwrite, graph=graph)
3551
3078
            # TODO: The old revid should be specified when merging tags, 
3552
3079
            # so a tags implementation that versions tags can only 
3553
3080
            # pull in the most recent changes. -- JRV20090506
3554
 
            result.tag_updates, result.tag_conflicts = (
3555
 
                self.source.tags.merge_to(self.target.tags,
3556
 
                    "tags" in overwrite,
3557
 
                    ignore_master=not merge_tags_to_master))
 
3081
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3082
                overwrite)
3558
3083
            result.new_revno, result.new_revid = self.target.last_revision_info()
3559
3084
            if _hook_master:
3560
3085
                result.master_branch = _hook_master
3569
3094
            self.source.unlock()
3570
3095
        return result
3571
3096
 
 
3097
    def push(self, overwrite=False, stop_revision=None,
 
3098
             _override_hook_source_branch=None):
 
3099
        """See InterBranch.push.
 
3100
 
 
3101
        This is the basic concrete implementation of push()
 
3102
 
 
3103
        :param _override_hook_source_branch: If specified, run
 
3104
        the hooks passing this Branch as the source, rather than self.
 
3105
        This is for use of RemoteBranch, where push is delegated to the
 
3106
        underlying vfs-based Branch.
 
3107
        """
 
3108
        # TODO: Public option to disable running hooks - should be trivial but
 
3109
        # needs tests.
 
3110
        self.source.lock_read()
 
3111
        try:
 
3112
            return _run_with_write_locked_target(
 
3113
                self.target, self._push_with_bound_branches, overwrite,
 
3114
                stop_revision,
 
3115
                _override_hook_source_branch=_override_hook_source_branch)
 
3116
        finally:
 
3117
            self.source.unlock()
 
3118
 
 
3119
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3120
            _override_hook_source_branch=None):
 
3121
        """Push from source into target, and into target's master if any.
 
3122
        """
 
3123
        def _run_hooks():
 
3124
            if _override_hook_source_branch:
 
3125
                result.source_branch = _override_hook_source_branch
 
3126
            for hook in Branch.hooks['post_push']:
 
3127
                hook(result)
 
3128
 
 
3129
        bound_location = self.target.get_bound_location()
 
3130
        if bound_location and self.target.base != bound_location:
 
3131
            # there is a master branch.
 
3132
            #
 
3133
            # XXX: Why the second check?  Is it even supported for a branch to
 
3134
            # be bound to itself? -- mbp 20070507
 
3135
            master_branch = self.target.get_master_branch()
 
3136
            master_branch.lock_write()
 
3137
            try:
 
3138
                # push into the master from the source branch.
 
3139
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3140
                # and push into the target branch from the source. Note that we
 
3141
                # push from the source branch again, because its considered the
 
3142
                # highest bandwidth repository.
 
3143
                result = self.source._basic_push(self.target, overwrite,
 
3144
                    stop_revision)
 
3145
                result.master_branch = master_branch
 
3146
                result.local_branch = self.target
 
3147
                _run_hooks()
 
3148
                return result
 
3149
            finally:
 
3150
                master_branch.unlock()
 
3151
        else:
 
3152
            # no master branch
 
3153
            result = self.source._basic_push(self.target, overwrite,
 
3154
                stop_revision)
 
3155
            # TODO: Why set master_branch and local_branch if there's no
 
3156
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3157
            # 20070504
 
3158
            result.master_branch = self.target
 
3159
            result.local_branch = None
 
3160
            _run_hooks()
 
3161
            return result
 
3162
 
 
3163
    @classmethod
 
3164
    def is_compatible(self, source, target):
 
3165
        # GenericBranch uses the public API, so always compatible
 
3166
        return True
 
3167
 
 
3168
 
 
3169
class InterToBranch5(GenericInterBranch):
 
3170
 
 
3171
    @staticmethod
 
3172
    def _get_branch_formats_to_test():
 
3173
        return BranchFormat._default_format, BzrBranchFormat5()
 
3174
 
 
3175
    def pull(self, overwrite=False, stop_revision=None,
 
3176
             possible_transports=None, run_hooks=True,
 
3177
             _override_hook_target=None, local=False):
 
3178
        """Pull from source into self, updating my master if any.
 
3179
 
 
3180
        :param run_hooks: Private parameter - if false, this branch
 
3181
            is being called because it's the master of the primary branch,
 
3182
            so it should not run its hooks.
 
3183
        """
 
3184
        bound_location = self.target.get_bound_location()
 
3185
        if local and not bound_location:
 
3186
            raise errors.LocalRequiresBoundBranch()
 
3187
        master_branch = None
 
3188
        if not local and bound_location and self.source.base != bound_location:
 
3189
            # not pulling from master, so we need to update master.
 
3190
            master_branch = self.target.get_master_branch(possible_transports)
 
3191
            master_branch.lock_write()
 
3192
        try:
 
3193
            if master_branch:
 
3194
                # pull from source into master.
 
3195
                master_branch.pull(self.source, overwrite, stop_revision,
 
3196
                    run_hooks=False)
 
3197
            return super(InterToBranch5, self).pull(overwrite,
 
3198
                stop_revision, _hook_master=master_branch,
 
3199
                run_hooks=run_hooks,
 
3200
                _override_hook_target=_override_hook_target)
 
3201
        finally:
 
3202
            if master_branch:
 
3203
                master_branch.unlock()
 
3204
 
3572
3205
 
3573
3206
InterBranch.register_optimiser(GenericInterBranch)
 
3207
InterBranch.register_optimiser(InterToBranch5)